Ansible: Conditional Playbooks

I have praised Ansible tags all about the previous post. Unfortunately, tags don't go along with Ansible Tower complex workflows. Let me guide you through the playbook transformation we've done. The answer to this challenge is extra variables.

Practically, it's the only answer for now if you want to keep the same functionality for Ansible and Ansible Tower. You can define it as an extra variable or add a user survey and pass it down to all jobs in the workflow.

Let's get the example from the previous piece and sprinkle it with that extra variables support. Modified playbook tries to use an external tower_operation variable or uses 'start' or 'stop' values if the variable is undefined.

---
## WebLogic Domain Control Playbook
## Stop Section
- name: Stop Managed Servers
  hosts: wls_hosts
  tags:
   - stop
   - server-stop
  vars:
    tower_op: "{{ tower_operation|default('stop') }}
  roles: 
    - role: domain-ctl
      vars:
        process: server
        state: stop
      when: tower_op in ['stop','server-stop'] 

- name: Stop Admin Server
  hosts: wls_host_admin
  tags:
   - stop
   - admin-stop
  vars:
    tower_op: "{{ tower_operation|default('stop') }}
  roles: 
    - role: domain-ctl
      vars:
        process: admin
        state: stop
      when: tower_op in ['stop','admin-stop'] 
        
- name: Stop NodeManager
  hosts: wls_hosts
  tags:
   - stop
   - nm-stop
  vars:
    tower_op: "{{ tower_operation|default('stop') }}
  roles: 
    - role: domain-ctl
      vars:
        process: node
        state: stop
      when: tower_op in ['stop','nm-stop'] 

## Start Section        
- name: Start NodeManager
  hosts: wls_hosts
  tags:
   - start
   - nm-start
  vars:
    tower_op: "{{ tower_operation|default('start') }}
  roles: 
    - role: domain-ctl
      vars:
        process: node
        state: start
      when: tower_op in ['start','nm-start'] 

- name: Start Admin Server
  hosts: wls_host_admin
  tags:
   - start
   - admin-start
  vars:
    tower_op: "{{ tower_operation|default('start') }}
  roles: 
    - role: domain-ctl
      vars:
        process: admin
        state: start     
      when: tower_op in ['start','admin-start'] 


- name: Start Managed Servers
  hosts: wls_hosts
  tags:
   - start
   - server-start
  vars:
    tower_op: "{{ tower_operation|default('start') }}
  roles: 
    - role: domain-ctl
      vars:
        process: server
        state: start
      when: tower_op in ['start','server-start'] 

...
wls-doman-ctl.yml

Now you have more options to control playbook execution:

  • From the command line with tags, for example --tags stop.
  • From the command line with extra variable -e "tower_operation='stop'".
  • Declare an extra variable for the Ansible Tower Workflow as a survey or extra variable.