I want to take input from the user, group name of servers separated by a comma: abc, cde in variable destination, and then I want to loop over all the servers of each group and check for each server access on given ports. Here port is the variable that I created and stored in a file. I am trying to loop over all servers of the group in the port variable and for each of them check for all ports under that particular group in the port variable.
port variable in vars file looks like:
port:
abc:
- server1
- server2
abc_port:
- 22
- 34
cde:
- server3
- server
cde_port:
- 122
- 343
I expect the result:
curl -kv server1:22
curl -kv server1:34
curl -kv server2:22
curl -kv server2:34
curl -kv server3:122
curl -kv server3:343
curl -kv server4:122
curl -kv server4:343
For servers of group abc and cde as per the group input by user which will be of form "abc ,cde"
How can I achieve this?
task:
- name: check port opening
shell: curl -kv {{item[1]}}:{{item[2]}}
with_nested:
- "{{destination.split(',')}}"
- "{{port. item[0]}}"
- "{{port. item[0] _port}}
CodePudding user response:
Create the list of the destinations first. If you declare dest in the command line, e.g. -e dest='abc,cde'
- set_fact:
dest_port: []
- set_fact:
dest_port: "{{ dest_port item.0|
product(item.1)|
map('join', ':')|
list }}"
loop: "{{ _dest|zip(_port) }}"
vars:
_d: "{{ dest|d('') }}"
_dest_keys: "{{ (_d|length > 0)|ternary(_d.split(','), []) }}"
_port_keys: "{{ _dest_keys|product(['_port'])|map('join')|list }}"
_dest: "{{ _dest_keys|map('extract', port)|list }}"
_port: "{{ _port_keys|map('extract', port)|list }}"
gives
dest_port:
- server1:22
- server1:34
- server2:22
- server2:34
- server3:122
- server3:343
- server:122
- server:343
Now, you can iterate the command
- debug:
msg: "curl -kv {{ item }}"
loop: "{{ dest_port }}"
gives (abridged)
msg: curl -kv server1:22
msg: curl -kv server1:34
msg: curl -kv server2:22
msg: curl -kv server2:34
msg: curl -kv server3:122
msg: curl -kv server3:343
msg: curl -kv server:122
msg: curl -kv server:343