megha
megha

Reputation: 833

ansible if else statement to run only required task

I am working on playbook which should run with conditions

For example when choice = repos I want to run first task and if choice = projects I want to run second task

tasks:
  - name: Run python script for generating Empty 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 Empty Repos Report
    command: python GetRepos.py -o {{ org }} -p {{ pat }}
    register: result
  - debug: msg="{{result.stdout}}"
    when:
      - "{{ choice }}" == "Projects"

This gives me error because of wrong syntax , what's the right syntax to achieve this ?

Upvotes: 1

Views: 216

Answers (1)

Vladimir Botka
Vladimir Botka

Reputation: 68294

This is the correct syntax

tasks:

  - debug:
      msg: Run first task
    when: choice == "Repos"

  - debug:
      msg: Run second task
    when: choice == "Projects"

Optionally, use the default value to avoid crashing due to the undefined variable choice. For example

    when: choice|default("Undefined") == "Projects"

Upvotes: 1

Related Questions