megha
megha

Reputation: 833

Ansible if else using shell script

I am using following ansible tasks for triggering certain a task based on user's choice.

This is working:

tasks:
  - name: Run python script for generating Repos Report
    command: python GetRepos.py -o {{ org }} -p {{ pat }}
    register: result
  - debug: msg="{{result.stdout}}"
    when: choice == "Repos"

  - name: Run python script for generating projects Report
    command: python Getprojects.py -o {{ org }} -p {{ pat }}
    register: result
  - debug: msg="{{result.stdout}}"
    when: choice == "projects"

But I want to use a shell script with if else statement to run this in one task as below:

tasks:
   - name: run python script
     shell: |
       if [choice == "repos"]
       then
       cmd: python GetRepos.py -o {{ org }} -p {{ pat }} 
       elif [choice == "projects"]
       then
       cmd: python Getprojects.py -o {{ org }} -p {{ pat }}         
       fi
    register: cmd_output
  - debug: msg="{{cmd_output.stdout}}"

But this does not execute the task; it just ends without error.

Is this the right syntax for shell?

How can I achieve these 2 separate working tasks in just one task using the shell module?

Upvotes: 2

Views: 3582

Answers (1)

costaparas
costaparas

Reputation: 5237

The cmd: in a shell script will try to run cmd: as a command, which you don't want.

Also, the if statement conditions need spaces on either side - otherwise, it would try to run [choice as a command, which you also don't want.

Also prefer to use single equals instead of double equals, to make it more portable (the remote hosts could have various different shells!).

The other issue is that choice as used inside the shell script is just a literal string. You need to add the braces {{ }} to interpolate the value, as done elsewhere in the playbook.

Taking into consideration the above, the following should work for you:

tasks:
  - name: run python script
    shell: |
      if [ "{{ choice }}" = "repos" ]
      then
          python GetRepos.py -o "{{ org }}" -p "{{ pat }}"
      elif [ "{{ choice }}" = "projects" ]
      then
          python Getprojects.py -o "{{ org }}" -p "{{ pat }}"
      fi
    register: cmd_output
  - debug:
      msg: "{{ cmd_output.stdout }}"

Upvotes: 1

Related Questions