Search code examples
salt-project

How to execute multiple scripts with Salt cmd.script?


I'm trying to apply salt state that consist of multiple scripts. But some reason only script4 is running.

Here's my state file.

#!jinja|yaml|gpg

Distro_Specific_Scripts:
  cmd.script:
    - name: Run Scripts.sh
  {% if grains['os_family'] == 'RedHat' %}
    - source: salt://scripts/files/scripts/script_for_redhat.sh
  {% elif grains['os_family'] == 'Debian' %}
    - source: salt://scripts/files/scripts/script_for_ubuntu.sh
  {% endif %}
    - source: salt://scripts/files/scripts/script2.sh
    - source: salt://scripts/files/scripts/script3.sh
    - source: salt://scripts/files/scripts/script4.sh

Would you share your experience about running multiple scripts? or Would you tell me where i went wrong.


Solution

  • There are multiple ways to write this.

    OPTION 1:

    This will be the simplest method. If you have scripts corresponding to the grains['os_family'], i.e.

    • script_for_debian.sh for Debian
    • script_for_ubuntu.sh for Ubuntu
    • script_for_redhat.sh for RedHat
    run_my_scripts:
      cmd.script:
        - names:
            - salt://scripts/files/scripts/script_for_{{ grains['os_family'] | lower }}.sh
            - salt://scripts/files/scripts/script2.sh
            - salt://scripts/files/scripts/script3.sh
            - salt://scripts/files/scripts/script4.sh
    

    OPTION 2:

    If not, then we can set the script name conditionally and outside the state declaration:

    {% set os_specific_script = salt['grains.filter_by']({
      'Debian': 'script_for_ubuntu.sh',
      'RedHat': 'script_for_redhat.sh'
    }) %}
    
    run_my_scripts:
      cmd.script:
        - names:
            - salt://scripts/files/scripts/{{ os_specific_script }}
            - salt://scripts/files/scripts/script2.sh
            - salt://scripts/files/scripts/script3.sh
            - salt://scripts/files/scripts/script4.sh
    

    If you have control over the name of scripts, OPTION 1 will be a better choice.