如何使用标签在ansible中的两个任务之间进行选择



我想在安装或升级中使用标记来选择特定的任务集:假设场景是:我有一个任务a和一个任务B,我想使用标签来选择a或B到目前为止,我有这样一个角色:在我的任务/main.yml:中

- name: "Configuration"
include: 03-configuration.yml
when: upgrade
tags:
- configuration

所以我启动了这样的剧本,这让我转到文件03-configuration.yml,并播放这个文件中的所有内容

ansible-playbook -v ThePlayBook.yml --tags "configuration"

03-configuration.yml文件:

- name: "A"
- name: "B"

但正如你在这个文件03-configuration.yml中看到的,我有两个任务,我说的是A和B,所以现在它将尝试执行这两个任务;安装";或";升级";发射其中任何一个。

例如,给定文件

shell> cat configuration.yml 
- debug:
msg: installation
tags: installation
- debug:
msg: upgrade
tags: upgrade

将其包含在战术手册中

shell> cat playbook.yml
- hosts: localhost
tasks:
- include_tasks: configuration.yml
when: upgrade|default(false)|bool
tags: configuration

当你在没有任何标签的情况下运行这个剧本时

shell> ansible-playbook playbook.yml -e upgrade=true

所有任务都执行

TASK [debug] **************************************************************
ok: [localhost] => 
msg: installation
TASK [debug] **************************************************************
ok: [localhost] => 
msg: upgrade

当您使用配置标签仅运行它时

shell> ansible-playbook playbook.yml -e upgrade=true -t configuration

文件被包括但没有任务被执行


TASK [include_tasks] ********************************************************
included: /export/scratch/tmp8/configuration.yml for localhost

tags: configuration不会由包含文件中的任务继承。请参阅标记继承以了解includes。。。。如果要执行这样的任务,如果在命令行上指定了标记,则需要两个标记。例如

shell> ansible-playbook playbook.yml -e upgrade=true -t configuration,installation

给出简略的

TASK [debug] **************************************************************
ok: [localhost] => 
msg: installation

请参阅标签中的更多详细信息。

您可能会使用类似的方法

---
- hosts: localhost
become: false
gather_facts: false
tasks:
- name: "Config"
include_tasks: install_update.yml
tags:
- config
- name: "A"
debug:
tags: install
- name: "B"
debug:
tags: update

通过呼叫

ansible-playbook ThePlayBook.yml --tags="config"
ansible-playbook ThePlayBook.yml --tags="config,install"
ansible-playbook ThePlayBook.yml --tags="config,update"

导致的输出

PLAY RECAP **********************
localhost                  : ok=1
...
TASK [A] ************************
ok: [localhost] =>
msg: Hello world!
PLAY RECAP **********************
localhost                  : ok=2
...
TASK [B] ************************
ok: [localhost] =>
msg: Hello world!
PLAY RECAP **********************
localhost                  : ok=2

进一步读数

  • include_tasksimport_tasks之间有什么区别

相关内容