我试图通过能够有选择地选择带标签的执行步骤,使Ansible角色尽可能重用。到目前为止,我找不到合适的东西。
以下是我为在linux机器上启用安全更新的角色所尝试的内容:
角色摘录:
- 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
我曾经有一个循环来复制这两个文件,但是我需要能够在安全升级后激活/停用自动重启这一事实让我把它分成3个相同的步骤。我希望会有一种不那么冗长的方式。
然后因为它是一个角色,我希望能够独立运行它,我需要创建一个特定的剧本:
---
- hosts: all
gather_facts: yes
tasks:
- name: run security-upgrade role with 'noreboot' option
include_role:
name: security-upgrades
这很好用,但我似乎无法只执行应该互斥的最后两个步骤中的一个。
将tags:
添加到playbook是没用的,它不能让我有选择地执行一个选项。
答案 0 :(得分:1)
您可以分别使用when: security-upgrades_noreboot is defined
和when: security-upgrades_noreboot is undefined
来完成任务。您需要在playbook中传递变量并让它运行一个任务或另一个任务:
---
- hosts: all
gather_facts: yes
tasks:
- name: run security-upgrade role with 'noreboot' option
include_role:
name: security-upgrades
vars:
security-upgrades_noreboot: yes
这应该跳过具有when: security-upgrades_noreboot is undefined
的任务。如果你没有传递var,那么这个任务就会运行,但是会跳过另一个任务。