ansibleansible-inventoryansible-role

Ansible - passing a var if it exists


I am running an ansible playbook like this:

ansible-playbook -i inventory/inventory1.yml playbooks/playbook1.yml 
    --extra-vars "environment=my_env var=my_var"

My inventory1.yml looks like this:

    ...
      children:
        env1:
          hosts:
            env1.domain.com:
          vars:
            port: '8000'
            name: name1
            parameter: 'parameter1'
        env2:
          hosts:
            env2.domain.com:
          vars:
            port: '8000'
            name: name2
        env3:
          hosts:
            env3.domain.com:
          vars:
            port: '8000'
            name: name3
            parameter: 'parameter1'

Note: Parameter only exists in some envs (env1 and env3).

My playbook1.yml:

---
- hosts: "{{ environment }}"

  roles:
   - my_role

My_role (main.yml):

- name: My_role
  command: ansible-playbook
    -i inventory/inventory2.yml playbook2.yml
    --extra-vars="
    environment={{ environment }}
    parameter={{ parameter }}
    "

As you can see I am using a playbook (playbook1.yml) to run second playbook(playbook2.yml), and I am using some vars from inventory1.yml when I am running playbook2.yml.

As I only have the variable "parameter" in some environments (env1 and env3) I want to pass the variable if it exists (in the --extra-vars). If it doesn't exist, I don't want to pass it (nor can I pass it).

How can I do this in the main.yml (in my_role) ? Is there any condition or any statement that I can use for this?


Solution

  • One way that I have achieved the similar thing in the past was using if else construct:

    - name: My_role
      command: ansible-playbook -i inventory/inventory2.yml playbook2.yml --extra-vars="environment={{ environment }} {{ 'parameter='~parameter if parameter is defined }}"
    

    As per your requirement, you can change the if conditions:

    "parameter is defined" - check for declaration
    "parameter | length > 0" - check for non-emptiness

    Let me know if that works for you, look for syntax error if you get due to quotes.

    Edited

    Forgot about the case where parameter is not defined, 'else' was must. [[ in latest version of ansible 'else' is not necessary, I have tested it on 2.13.1 ]]

    - name: My_role
      command: ansible-playbook -i inventory/inventory2.yml playbook2.yml --extra-vars="environment={{ environment }} {{ 'parameter='~parameter if parameter is defined else '' }}"