coolnodje
coolnodje

Reputation: 807

Best way to selectively enable execution steps for a play in Ansible

I'm trying to make Ansible roles as reusable as possible by being able to selectively choose execution steps with tags. So far I've failed to find something appropriate.

Here's what I've tried for a role enabling security updates on a linux machine:

Roles excerpt:

- name: Copy the 20auto-upgrades templates to enable automatic security updates
  copy:
    src: 20auto-upgrades
    dest: /etc/apt/apt.conf.d/20auto-upgrades
    owner: root
    group: root
    mode: 0644
  become: yes

- name: Copy the 50unattended-upgrades templates to configure security updates with AUTOMATIC REBOOT
  copy:
    src: 50unattended-upgrades-reboot
    dest: /etc/apt/apt.conf.d/50unattended-upgrades
    owner: root
    group: root
    mode: 0644
  become: yes
  tags: 
    - reboot

- name: Copy the 50unattended-upgrades templates to configure security updates with NO AUTOMATIC REBOOT
  copy:
    src: 50unattended-upgrades-noreboot
    dest: /etc/apt/apt.conf.d/50unattended-upgrades
    owner: root
    group: root
    mode: 0644
  become: yes
  tags:
    - noreboot

I used to have a loop to copy these 2 files, but the fact that I need to be able to activate/deactivate autoreboot after security upgrade made me split it into 3 identical steps. I wish there would be a less verbose way.

Then since it's a role and I want to be able to run it independently, I need to create a specific playbook:

---
- hosts: all
  gather_facts: yes
  tasks:
  - name: run security-upgrade role with 'noreboot' option
    include_role:
      name: security-upgrades

This works well, but I can't seem to be able to execute only one of the two last steps that should be mutually exclusive. Adding tags: to the playbook is not useful, it doesn't enable me to selectively execute one option.

Upvotes: 1

Views: 399

Answers (1)

Grigory Sergeev
Grigory Sergeev

Reputation: 374

You can use when: security-upgrades_noreboot is defined and when: security-upgrades_noreboot is undefined with your tasks respectively. You will need to pass the variable in the playbook and have it run one task or the other:

---
- hosts: all
  gather_facts: yes
  tasks:
  - name: run security-upgrade role with 'noreboot' option
    include_role:
      name: security-upgrades
    vars: 
      security-upgrades_noreboot: yes

This should skip the task that has when: security-upgrades_noreboot is undefined. If you don't pass the var, this task will run, but the other one is skipped.

Upvotes: 1

Related Questions