You haven’t described the actual overarching thing you’re trying to do with this, sometimes describing the larger task can be useful in terms of providing better guidance.
But reading between the lines, is there any reason you can’t place your intended delegation hosts into an inventory group and address them directly? For example if they’re getting special treatment as intended jumphosts or similar. Group them accordingly and run the bits of automation that’s unique to that intended system role against those group members.
I’d also tend to prefer a Jinja template over lineinfile for config if possible especially if you need to accommodate different conditional scenarios. It’s potentially a little more effort to start, but will save you pain in the long run.
That said, I think you can probably achieve what you’re trying to do with a product filter? (There’s probably easier ways to get the outcome you want too.)
https://www.packetswitch.co.uk/how-to-use-ansible-loops-with-examples/
https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_loops.html#iterating-over-nested-lists
Here’s a simplified example, you’d need to modify slightly to pull out the specific elements:
- name: debug vars
hosts: localhost
gather_facts: no
vars:
delegates:
- host1
- host2
regexes:
- regex: AllowTcpForwarding
line: AllowTcpForwarding yes
- regex: AllowAgentForwarding
line: AllowAgentForwarding yes
tasks:
- name: Do some stuff
debug:
msg: “Doing {{ item.1 }} on {{ item.0 }}”
delegate_to: “{{ item.0 }}”
loop: “{{ delegates | product(regexes) | list }}”
Which would do:
(ansible)$ ansible-playbook test/debug.yml
PLAY [debug vars] ******************************************************************************************************
TASK [Do some stuff] ***************************************************************************************************
ok: [localhost → host1] => (item=[‘host1’, {‘regex’: ‘AllowTcpForwarding’, ‘line’: ‘AllowTcpForwarding yes’}]) => {
“msg”: “Doing {‘regex’: ‘AllowTcpForwarding’, ‘line’: ‘AllowTcpForwarding yes’} on host1”
}
ok: [localhost → host1] => (item=[‘host1’, {‘regex’: ‘AllowAgentForwarding’, ‘line’: ‘AllowAgentForwarding yes’}]) => {
“msg”: “Doing {‘regex’: ‘AllowAgentForwarding’, ‘line’: ‘AllowAgentForwarding yes’} on host1”
}
ok: [localhost → host2] => (item=[‘host2’, {‘regex’: ‘AllowTcpForwarding’, ‘line’: ‘AllowTcpForwarding yes’}]) => {
“msg”: “Doing {‘regex’: ‘AllowTcpForwarding’, ‘line’: ‘AllowTcpForwarding yes’} on host2”
}
ok: [localhost → host2] => (item=[‘host2’, {‘regex’: ‘AllowAgentForwarding’, ‘line’: ‘AllowAgentForwarding yes’}]) => {
“msg”: “Doing {‘regex’: ‘AllowAgentForwarding’, ‘line’: ‘AllowAgentForwarding yes’} on host2”
}
PLAY RECAP *************************************************************************************************************
localhost : ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0