简体   繁体   中英

How to set an Ansible tag from within a playbook?

I would like to skip some of the plays based on a conditional value. I could have a task at the beginning that would skip some of the other tasks when a condition is met.

I know I could always use set_fact and use this as a condition to run the other plays (roles and tasks) or evaluate the said condition directly in each play I want to skip.

However, since the plays already have a tagging system in place, is there something like set_tags in Ansible that I could leverage on to avoid having to add conditions all over my plays and bloat my already heavy playbook.

Something such as:

- name: skip terraform tasks if no file is provided
  hosts: localhost
  tasks:
    set_tags:
      - name: terraform
        state: skip
    when: terraform_files == ""

The two plays I'd like to skip:

- name: bootstrap a testing infrastructure
  hosts: localhost
  roles:
    - role: terraform
      state: present
  tags:
    - create_servers
    - terraform

[...]

- name: flush the testing infrastructure
  hosts: localhost
  roles:
    - role: terraform
      state: absent
  tags:
    - destroy_servers
    - terraform

If I understood correctly, the following should do.

- name: bootstrap a testing infrastructure
  hosts: localhost
  roles:
    - role: terraform
      state: present
      when: terraform_files != ""
  tags:
    - create_servers
    - terraform

[...]

- name: flush the testing infrastructure
  hosts: localhost
  roles:
    - role: terraform
      state: absent
      when: terraform_files != ""
  tags:
    - destroy_servers
    - terraform

This is basically the same as setting the when clause on every single tasks in the role. So each task will be inspected but skipped if the condition is false.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM