Search code examples
salt-project

Why doesnt salt export and command execution happen?


I have a salt state file (approach 1):

export_port:
  cmd.run:
    - name: export PORT=53000
    - cwd: /tmp
execute_cmd:
  cmd.run:
    - name: ./test.sh db host user log
    - cwd: /tmp

When a job is executed, the state file returns an error stating that the psql program is not installed.

I tried the salt sate file with a shell script which has all the export and shell commands above (approach 2):

script:
  cmd.script:
    - name: /tmp/test.sh
    - source: /source/dir/test.sh
    - cwd: /tmp

And the shell script has:

#! /bin/sh
export PORT=53000
./test.sh db host user log

Both the approach are for same task to export a value and execute a command. The second approach works fine as expected. I am not sure why the first approach failed. Any thoughts?


Solution

  • The thing is you're executing two cmd.run sequentially, each one spawning a new and independent shell, so the environment variable exported in the first is not available in the second one.

    It should work with

    execute_cmd:
      cmd.run:
        - name: PORT=53000 ./test.sh db host user log
        - cwd: /tmp
    

    or better using the env parameter defined in cmd.run doc https://docs.saltstack.com/en/latest/ref/states/all/salt.states.cmd.html#salt.states.cmd.run

    execute_cmd:
      cmd.run:
        - name: ./test.sh db host user log
        - cwd: /tmp
        - env:
          - PORT: 53000