gpt4 book ai didi

Ansible:循环中设置每个项目的标签

转载 作者:行者123 更新时间:2023-12-02 04:17:46 25 4
gpt4 key购买 nike

是否可以在 with_item 语句中为每个项目设置 tags

假设我有一个任务:

- name: ensure required packages are installed
apt: pkg={{ item }} state=present
with_items:
- package_1
- package_2
sudo: yes

当用户在命令行中定义 --tags "second" 时,我只想安装 package_2

是否可以使用标签表达式或任何其他方式来获得所需的行为?

最佳答案

五年后我也想知道同样的事情,然后我碰巧发现了这个话题。经过一些实验后,我发现以下方法可以相当成功地工作,而无需指定额外的变量。它还可以与 --skip-tags 一起使用。

示例 1:使用自定义标签名称:

- name: ensure required packages are installed
apt: pkg={{ item }} state=present
loop:
- {pkg_name: package_1, tag: first}
- {pkg_name: package_2, tag: second}
- {pkg_name: package_3, tag: third}
sudo: yes
when:
- (ansible_run_tags == ['all'] and ansible_skip_tags == []) or (item.tag in ansible_run_tags) or (item.tag not in ansible_skip_tags and (item.tag in ansible_run_tags or ansible_run_tags == ['all']))
tags:
- always

测试了以下场景:

ansible-playbook test.yaml --tags first
Installs only the first package.

ansible-playbook test.yaml --skip-tags first
Installs only the second and third packages.

ansible-playbook test.yaml --skip-tags first --tags third
Installs only the third package (because 'second' isn't in the tag list.)

为了简单起见,我可以考虑使用实际的包名称作为标签。在这种情况下,我提出...

示例 2:使用包名称作为标签名称:

- name: ensure required packages are installed
apt: pkg={{ item }} state=present
loop:
- httpd
- ansible
- docker
sudo: yes
when:
- (ansible_run_tags == ['all'] and ansible_skip_tags == []) or (item in ansible_run_tags) or (item not in ansible_skip_tags and (item in ansible_run_tags or ansible_run_tags == ['all']))
tags:
- always

预期结果(未测试):

ansible-playbook test.yaml --tags ansible
Installs only the 'ansible' package

ansible-playbook test.yaml --skip-tags httpd
Installs only the 'ansible' and 'docker' packages skipping 'httpd'.

ansible-playbook test.yaml --tags mongodb
Installs nothing since 'mongodb' is not in the list.

ansible-playbook test.yaml
Installs all packages in the list.

关于Ansible:循环中设置每个项目的标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32648604/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com