Search code examples
ansibleansible-2.xansible-inventoryansible-facts

Ansible running all task even if tags are used


Here is my tasks with 2 tags

- name: Set custom iptables rules
  iptables_raw:
    name: 'iptables_custom_rules'
    rules: '{{ iptables_custom_rules }}'
  tags: 'commonrules'


- name: Set XXX iptable rules
  iptables_raw:
    name: 'iptables_wsg_rules'
    rules: '{{ iptables_wsg_rules }}'
  tags: 'wsgrules'

In the iptable.yml file I included role with tag

- hosts: iptables
  roles:
    - { role: "Iptables", tags: "commonrules" }

It should run only tag with commonrules, but when I run the playbook it runs all the tasks.


Solution

  • Tags are (de)activated only on the command line of ansible-playbook with the --tags/--skip-tags options.
    Tags declaration inside playbooks and roles are only to declare the tags that activates those tasks and roles.

    By default ansible runs as if --tags all had been specified.

    So, if you want to run only the tasks with 'commonrules' tag, you have to:

    1. remove the tag from the roles section (or it will apply to all tasks of the role)
    2. call ansible-playbook with option --tags commonrules

    If you want to dynamically apply a task, the best way is to use a when condition based on a flag that is defined only for the hosts the tasks need to be applied for.

    - name: Set custom iptables rules
      iptables_raw:
        name: 'iptables_custom_rules'
        rules: '{{ iptables_custom_rules }}'
      when: commonrules | default(False)
    
    - name: Set XXX iptable rules
      iptables_raw:
        name: 'iptables_wsg_rules'
        rules: '{{ iptables_wsg_rules }}'
      when: wsgrules | default(False)
    

    Then, in the group_vars or host_vars files, something like:

    # group_vars/common.yml
    commonrules: True
    
    # group_vars/wsg.yml
    wsgrules: True
    

    Or even better, you can even tests the existence of the iptables_XXX_rules variable in the when condition, so task will be executed only for hosts that have those variables defined.