...

Open source softwares - SaltStack

Back to Course

Lesson Description


Lession - #1530 SaltStack Remote Execution


Remote Execution abilities, a feature that I feel Saltstack has implemented better than other automation tools.

Running a command in a State

For this illustration let's pretend that we want to execute the script/ root/ scripts/test.sh on systems with the nginx software loaded. To do this we can simply add the command into the nginx state file.

On the Salt Master edit the nginx/init.sls file


 vi/ salt/ states/ base/ nginx/init.sls


Append the following

- run 
- name/ root/ scripts/test.sh 


The below entry will tell Salt to run the command named/ root/ scripts/test.sh every time the systems state is managed.

Using onlyif and unless

What if we only want to run the command when certain conditions are true? Well salt can handle that too. We can us the onlyif and unless options to tell Salt to only run the command if certain conditions are met.

Onlyif

Onlyif will execute the command only if the supplied command is true. In the below illustration we will only executetest.sh if the file exists.

illustration

test.sh 
 cmd 
- run 
- name/ root/ scripts/test.sh 
- onlyif test- f/ root/ scripts/test.sh 


Unless

While onlyif executes the named command if the supplied command returns true, unless will only execute the named command if the supplied command returns false. In this illustration we will execute the commandtest.sh only when the nginx configtest fails.

Illustration


 cmd 
- run 
- name/ root/ scripts/test.sh 
- unless/ usr/ sbin/ service nginx configtest 


Stateful commands

If you want Salt to understand whether your script passed or failed you can do this by making the command stateful.

Adding stateful to the state file

In the state file we will tell Salt that the command is stateful by appending- stateful True.

illustration


- run 
- name/ root/ scripts/test.sh 
- unless/ usr/ sbin/ service nginx configtest 
- stateful True 


Adding state status to the script

Now that salt knows the command is “ stateful ” the script must also tell Salt what has changed and if it was successful or not. To do this you can append two lines at the end of the scripts output.

Illustration of a good run


 echo""## This echos an empty line and is required 
 echo" changed = yes comment = ' I executed something and it changed'" 
 


Illustration of a failed run


 echo""## This echos an empty line and is required 
 echo" changed = no comment = ' I executed something and it didn't change'" 
  


It's ok if your script also has other output. Salt will only be looking at the last two lines of output; so you must make sure that these lines are at the end. For further information about running commands in states check out the Saltstack cmd state docs.