Search code examples
ansiblecase-when

Ansible Playbook: How to run Play based on when condition?


I have a playbook with multiple plays. Here is what it looks like:

- name: Play A
  hosts: localhost
  roles:
    - do task to get either B or C

- name: Play B
  hosts: Host B
  roles:
    - do necessary task

- name: Play C
  hosts: Host C
  roles:
    - do necessary task

- name: Play D
  host: localhost
  roles:
    - create_logs

Whenever the playbook is triggered, it will first run the first play to get either B or C result.

The result is to determine the Host attribute to run the play such as the IP address and the OS of the host.

After that, based on the result, for example if the result is B, I will run the Play B and skip the play C.

Else if the result is C, I will skip the play B and run the Play C.

Play D will be run as the last Play regardless of the result from the previous Plays.

How can I do this? I have tried using 'when' condition but it said that it is not an attribute for Play.


Solution

  • I have found other way on how to do it. The difference between Host B and Host C is only the IP address and the OS type.

    Hence, I am editing the inventory/hosts file and refresh_inventory after the play completed necessary task when the playbook is running, then before finishing the last task, I edit back the inventory/hosts file to its default value that I have setup.

    the parent playbook:

    - name: Play A
      hosts: localhost
      roles:
        - do task to get either B or C
        - edit/replace ip address & host type for the targeted hosts in inventory/hosts file with using when condition
        - refresh_inventory
    
    - name: Play B_C
      hosts: switches_host
      roles:
        - do necessary task
    
    - name: Play D
      host: localhost
      roles:
        - create_logs
        - - edit/replace back to initial value
    

    the inventory:

    switches_host:
          ansible_host: s.s.s.s
          ansible_user: user
          ansible_ssh_pass: pswd
          ansible_network_os: xo.sx