Search code examples
ansible

Ansible run role with specific tag defined in playbook


Usecase

I have a playbook test.yml in which multiple roles are executed:

- name: 'create cnames'
  hosts: sysops_setup_grafana_server

  roles:
  - role: test.sysops.vcenter_vm
  - role: test.sysops.certificate

Within the role test.sysops.vcenter_vm there are multiple included tasks:

---
- name: 'configure active directory'
  ansible.builtin.include_tasks: ad.yml
  tags:
  - 'vcenter_vm'
  - 'vcenter_vm:ad:computer'

- name: 'configure eam'
  ansible.builtin.include_tasks: eam.yml
  tags:
  - 'vcenter_vm'
  - 'vcenter_vm:eam'
  - 'vcenter_vm:eam:service_ou'
  - 'vcenter_vm:eam:groups'


- name: 'configure dns'
  ansible.builtin.include_tasks: dns.yml
  tags:
  - 'vcenter_vm'
  - 'vcenter_vm:dns'
  - 'vcenter_vm:dns:arecords'
  - 'vcenter_vm:dns:cnames'
  - 'vcenter_vm:dns:cleanup'

Problem

I want the playbook test.yml to run the role test.sysops.vcenter_vm with the tag vcenter_vm:dns:cnames, without explicitly setting the tags in the ansible-playbook test.yml --tags 'vcenter_vm:dns:cnames' command.

TAGS_RUN

I know that the TAGS_RUN configuration settings exists. But as I am working in a shared environment, I do not want to change anything in the ansible.cfg file.


Solution

  • How to define tags during playbook run?

    Whereby it is possible to Access tags at run time or read the variable content, it is not possible to set or change them later.

    I know that the TAGS_RUN configuration settings exists. But as I am working in a shared environment, I do not want to change anything in the ansible.cfg file.

    Without changing the config file every time, or have multiple config files in place, there is only the following option. A minimal example playbook

    ---
    - hosts: localhost
      become: false
      gather_facts: false
    
      tasks:
    
      - set_fact:
          ansible_run_tags: "dynamic_after"
    
      - debug:
          msg: "Show given tags: {{ ansible_run_tags }}"
        tags: always
    

    called via

    ANSIBLE_RUN_TAGS='static_before' ansible-playbook tags.yml
    

    will result into an output of

    TASK [debug] ********************************
    ok: [localhost] =>
      msg: 'Show given tags: [''static_before'']'
    

    But still one need to define the tags before on CLI. Otherwise Previewing the results of using tags via --list-tasks wouldn't be possible.

    ANSIBLE_RUN_TAGS='static_before' ansible-playbook tags.yml --list-tasks
    
    playbook: tags.yml
    
      play #1 (localhost): localhost        TAGS: []
        tasks:
          debug     TAGS: [always]
    

    Documentation