在Ansible中,可以使用set_fact
模块来添加一个额外字段到已定义的一组值中。
以下是一个示例代码,假设已经有一个名为hosts.yaml
的主机清单文件,其中包含了一组主机及其相关的一些属性:
# hosts.yaml
hosts:
- name: host1
ip: 192.168.1.100
- name: host2
ip: 192.168.1.101
然后,可以在Ansible playbook中使用set_fact
模块来添加一个额外字段,例如role
:
# playbook.yaml
- name: Add extra field to host group
hosts: localhost
gather_facts: false
tasks:
- name: Read hosts.yaml file
include_vars:
file: hosts.yaml
name: host_vars
- name: Add extra field
set_fact:
host_vars: "{{ host_vars.hosts | map('combine', {'role': 'webserver'}) | list }}"
- name: Debug host_vars
debug:
var: host_vars
运行这个playbook后,host_vars
变量将包含一个额外的字段role
:
TASK [Debug host_vars] ****************************************************************************************************
ok: [localhost] => {
"host_vars": [
{
"ip": "192.168.1.100",
"name": "host1",
"role": "webserver"
},
{
"ip": "192.168.1.101",
"name": "host2",
"role": "webserver"
}
]
}
通过使用map
过滤器和combine
函数,可以将额外的字段添加到每个主机对象中。最后,将结果转换为列表格式。