Search code examples
ansibleansible-2.x

Ansible include task files based on conditional


Just getting into ansible and want to know if you can include a file in a task main.yml based on a variable passed in --extra-vars?

Example;

main.yml -- from role/tasks

# Upload latest json to s3
- include: upload-code.yml

playbook.yml -- from playbooks

- name: Launch cloudformation stack
  hosts: 127.0.0.1
  connection: local
  roles:
    - launch.cloudformation

As you can see playbook.yml includes a role and the main.yml includes upload-code.yml

How can I include upload-code.yml based on a conditional like below

ansible-playbook playbook.yml --extra-vars "include=upload"


Solution

  • You can do this by applying a when condition to the include task.

    - include: upload-code.yml
      when:
        - include is defined
        - include == "upload"
    

    Or, if you have multiple include files you could also use include as part of the name.

    - include: "{{ include }}-code.yml"
      when: include is defined