Search code examples
ansible

How to build a conditional command in Ansible?


Currently, my task looks like this:

- name: Create snapshot
  command: nodetool -u foo -pw bar snapshot

The -u (username) and -pw (password) are credentials to use nodetool. However, not all environments have authentication for nodetool. In case they don't have authentication, then I would need to use the task without -u and -pw, like:

- name: Create snapshot
  command: nodetool snapshot

I don't want to have two playbooks (one for authentication required environments, and one for without it). So I'm looking for something of the sort:

- name: Create snapshot
  command: nodetool [IF(auth_required){-u foo -pw bar}] snapshot

With auth_required being a boolean variable in my vars file. How can I do something like this in Ansible?


Solution

  • Use the module set_fact to create the variable my_cmd and use the filter ternary to branch the control flow. For example,

    shell> cat pb.yml
    - hosts: localhost
    
      tasks:
    
        - set_fact:
            my_cmd: "nodetool {{ params }}snapshot"
          vars:
            params: "{{ auth_required | bool |
                        ternary('-u foo -pw bar ', '') }}"
    
        - debug:
            var: my_cmd
    

    gives

    shell> ansible-playbook pb.yml -e auth_required=false
      ...
      my_cmd: nodetool snapshot
    
    shell> ansible-playbook pb.yml -e auth_required=true
      ...
      my_cmd: nodetool -u foo -pw bar snapshot
    

    Test it. Then, use the command

        - name: Create snapshot
          command: "{{ my_cmd }}"