我当时正在查看Ansible https://docs.ansible.com/ansible/2.7/user_guide/playbooks_loops.html的“循环”页面,但找不到所需的内容...
我想测试“源”主机是否可以到达/连接到一组端口上的一组目标主机。例如,每组目标主机可以是一个清单组,并且每个清单组都有自己要测试的端口的列表。
这个想法是只指定两个var作为剧本的输入:一组主机组列表和一个或多个源主机列表。
应该如何进行循环?清单可以是YAML或INI文件:每个组一个或多个。 TCP连接的测试很容易...因此,重点仅放在输入变量和循环结构上。
感谢和问候。
Stef
答案 0 :(得分:0)
给出以下hosts
库存文件
server1
server2
server3
[dev]
d1
d2
d3
[dev:vars]
ports=8080,8443
[int]
i1
i2
i3
[int:vars]
ports=80,443
和以下剧本play.yml
---
- hosts: all
gather_facts: False
vars:
group: 'dev'
tasks:
- name: Just loop through a group and group_vars
debug:
msg: 'group is {{group}} target is {{item.0}} port is {{item.1}}'
loop: >
{{ groups[group] |
product(hostvars[groups[group][0]]["ports"]) |
list }}
您可以按照说明浏览清单
ansible-playbook -i hosts play.yml -l server* -e group=int
产生以下结果:
PLAY [all] *********************************************************************
TASK [Just loop through a group and group_vars] ********************************
ok: [server1] => (item=[u'i1', 80]) => {
"msg": "group is int target is i1 port is 80"
}
ok: [server1] => (item=[u'i1', 443]) => {
"msg": "group is int target is i1 port is 443"
}
ok: [server2] => (item=[u'i1', 80]) => {
"msg": "group is int target is i1 port is 80"
}
ok: [server2] => (item=[u'i1', 443]) => {
"msg": "group is int target is i1 port is 443"
}
ok: [server1] => (item=[u'i2', 80]) => {
"msg": "group is int target is i2 port is 80"
}
ok: [server3] => (item=[u'i1', 80]) => {
"msg": "group is int target is i1 port is 80"
}
ok: [server1] => (item=[u'i2', 443]) => {
"msg": "group is int target is i2 port is 443"
}
ok: [server3] => (item=[u'i1', 443]) => {
"msg": "group is int target is i1 port is 443"
}
ok: [server2] => (item=[u'i2', 80]) => {
"msg": "group is int target is i2 port is 80"
}
ok: [server1] => (item=[u'i3', 80]) => {
"msg": "group is int target is i3 port is 80"
}
ok: [server3] => (item=[u'i2', 80]) => {
"msg": "group is int target is i2 port is 80"
}
ok: [server2] => (item=[u'i2', 443]) => {
"msg": "group is int target is i2 port is 443"
}
ok: [server1] => (item=[u'i3', 443]) => {
"msg": "group is int target is i3 port is 443"
}
ok: [server3] => (item=[u'i2', 443]) => {
"msg": "group is int target is i2 port is 443"
}
ok: [server2] => (item=[u'i3', 80]) => {
"msg": "group is int target is i3 port is 80"
}
ok: [server3] => (item=[u'i3', 80]) => {
"msg": "group is int target is i3 port is 80"
}
ok: [server2] => (item=[u'i3', 443]) => {
"msg": "group is int target is i3 port is 443"
}
ok: [server3] => (item=[u'i3', 443]) => {
"msg": "group is int target is i3 port is 443"
}
PLAY RECAP *********************************************************************
server1 : ok=1 changed=0 unreachable=0 failed=0
server2 : ok=1 changed=0 unreachable=0 failed=0
server3 : ok=1 changed=0 unreachable=0 failed=0
例如,您只需要用wait_for module替换调试即可。