Ansible - 是否可以向清单内的主机添加标签?

Ansible - is it possible to add tags to hosts inside inventory?

正如主题所说,我的问题是是否可以为清单中描述的主机添加标签?

我的目标是能够 运行 具有该特定标签的特定 host/group 主机上的 ansible-playbook,例如仅在具有标签 'Env=test and Type=test'[=13= 的服务器上]

例如,当我 运行 剧本时:

ansible-playbook -i hosts test.yml --extra-vars "Env=${test} Type=${test}"

我将在命令中传递标签,它将 运行 仅在过滤后的主机上。

非常感谢!

更新:

或者,也许在动态库存中做一些事情? https://docs.ansible.com/ansible/latest/dev_guide/developing_inventory.html#developing-inventory

[tag_Name_staging_foo]

[tag_Name_staging_bar]

[staging:children]
tag_Name_staging_foo
tag_Name_staging_bar

回答你的问题

Is it possible to add tags to hosts inside inventory to run the ansible-playbook on a specific host/group of hosts?

否,tags仅适用于任务

When you apply tags: attributes to structures other than tasks, Ansible processes the tag attribute to apply ONLY to the tasks they contain. Applying tags anywhere other than tasks is just a convenience so you don’t have to tag tasks individually.

主机没有ansible "tags"; tasks have tags 并且它们用于有条件地执行任务,而不是有条件地定位主机。

有几种方法可以有条件地定位主机,根据我的经验,最好的方法是 ansible groups。将您要定位的主机放在一个组中;然后在游戏中直接针对这个群体:

 - hosts: my_host_group
   tasks: [ ... ] 

或者将 playook 限制为播放中目标主机的子集:

ansible-playbook -l my_limited_hosts_group playbook.yaml