我正在尝试从Debian 11服务器创建一个接口名称列表以及他们的mac地址,最初,我只是想让mac地址井然有序,但现在我意识到我需要这样的列表:
eth0 <SOME_MAC>
eth1 <SOME_MAC>
...
我希望将这个列表作为变量传递,然后在下一个任务中使用它在/etc/systemd/network
目录中创建一个/etc/systemd/network
文件。
我正在使用的当前任务是:
- name: Get mac addresses of all interfaces except local
debug:
msg: "{{ ansible_interfaces |
map('regex_replace','^','ansible_') |
map('extract',hostvars[inventory_hostname]) |
selectattr('macaddress','defined') |
map(attribute='macaddress') |
list }}"
如您所见,我正在使用debug
模块测试我的代码,我不知道如何创建我想要的列表并将其作为变量传递。
上面的代码给出了以下结果:
ok: [target1] =>
msg:
- 08:00:27:d6:08:1a
- 08:00:27:3a:3e:ff
- f6:ac:58:a9:35:33
- 08:00:27:3f:82:c2
- 08:00:27:64:6a:f8
ok: [target2] =>
msg:
- 08:00:27:34:70:60
- 42:04:1a:ff:6c:46
- 42:04:1a:ff:6c:46
- 08:00:27:d6:08:1a
- 08:00:27:9c:d7:af
- f6:ac:58:a9:35:33
对于使用哪个模块将列表作为变量传递以及如何首先创建列表的任何帮助都是值得赞赏的。
敬请注意,我使用的是Ansible v5.9.0,每个服务器可能有任意数量的接口,其中一些可能具有ethx
接口名称格式,而另一些则可能具有enspx
、brx
等接口格式。
更新:根据注释中的建议,我必须提到,我需要为每个目标列出一个列表,这些列表将在一个自然的主机循环任务中使用,该任务将针对每个目标运行。
更新2:作为我刚接触过Ansible的,根据我同事的建议,我的印象是,一个接口名称列表以及它们的MAC地址被空格隔开是我需要作为一个变量传递给下一个任务的,然而,在整个评论和回答中,我现在意识到我绝对是在朝着错误的方向前进。请接受我的道歉,并将其归咎于我缺乏经验和知识。最后,我们发现,接口名及其MAC地址的字典是Ansible中最适合这种操作的。
发布于 2022-08-09 16:54:35
我就是这样做的。
请注意,我的示例使用了json_query
过滤器,它要求在您的ansible控制器上使用pip install jmespath
。
---
- name: Create a formated list for all interfaces
hosts: all
vars:
elligible_interfaces: "{{ ansible_interfaces | reject('==', 'lo') }}"
interfaces_list_raw: >-
{{
hostvars[inventory_hostname]
| dict2items
| selectattr('value.device', 'defined')
| selectattr('value.device', 'in', elligible_interfaces)
| map(attribute='value')
}}
interface_query: >-
[].[device, macaddress]
interfaces_formated_list: >-
{{ interfaces_list_raw | json_query(interface_query) | map('join', ' ') }}
tasks:
- name: Show our calculated var
debug:
var: interfaces_formated_list
这给出了与我的本地主机竞争的结果:
$ ansible-playbook -i localhost, /tmp/test.yml
PLAY [Create a formated list for all interfaces] **************************************************************************************************
TASK [Gathering Facts] ****************************************************************************************************************************
ok: [localhost]
TASK [Show our calculated var] ********************************************************************************************************************
ok: [localhost] => {
"interfaces_formated_list": [
"docker0 02:42:98:b8:4e:75",
"enp4s0 50:3e:aa:14:17:8f",
"vboxnet0 0a:00:27:00:00:00",
"veth7201fce 92:ab:61:7e:df:65"
]
}
PLAY RECAP ****************************************************************************************************************************************
localhost : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
正如您所看到的,这显示了您可能希望在用例中筛选出的几个接口。您可以检查interfaces_list_raw
并创建额外的过滤器以实现您的目标。但至少你知道这个主意。
https://stackoverflow.com/questions/73294924
复制相似问题