Search code examples
ansibleansible-2.xconfiguration-management

Can I use ansible-playbook "--extra-vars" to execute roles conditionally


I have an Ansible playbook I am working on and I am trying to make the execution a little more dynamic. I have two roles that don't always need to be run in conjunction, sometimes only one of them needs to be run. I have been digging into the Ansible docs, and I am wondering if I can pass --extra-vars parameters to only run a specific role.

Currently, my playbook looks like this:

---
- hosts: default
  become: true

  roles:
      - role: upgrades
        when: {{ upgrades_role }}

      - role: custom-packages 
        when: {{ custom_packages_role }}

So, the goal is to be able to run:

ansible-playbook playbook.yml -e "upgrades_role=upgrades"

And this would only run the upgrades role and skip the custom_packages role.

Similarly, if I want to run both roles on the same hosts/system:

ansible-playbook playbook.yml -e "upgrades_role=upgrades custom_packages_role=custom-packages"

This would run both roles.

Based on my understating of Ansible syntax and the --extra-vars, -e parameter, this seems like it should work. I just want to be sure I am doing this the proper way and avoiding anti-patterns.

Ansible Version: 2.14


Solution

  • The most common way will be to use tags; updating the example in the question:

    ---
    - hosts: default
      become: true
    
      roles:
          - role: upgrades
            tags: upgrades
    
          - role: custom-packages 
            tags: packages
    ...
    

    So, the goal is to be able to run:

    # Execute all the roles
    ansible-playbook playbook.yml
    
    # Execute only the upgrade
    ansible-playbook playbook.yml -t upgrades
    
    # Execute only the setup of custom packages
    ansible-playbook playbook.yml -t packages
    

    Here is the documentation for tags.

    Using variables and when is possible, but you'll need to ensure to cast it to bool.