Loop in a loop

30 views
Skip to first unread message

Acrobis Nubian

unread,
Feb 20, 2017, 11:48:15 AM2/20/17
to Ansible Project
Hi all,

If someone could help me on the following:

I am trying to automate as maximum as possible the addition of authorized keys to my new remote servers by doing the below playbook, but I am getting the following error:
===============================================================
fatal: [web]: FAILED! => {"failed": true, "msg": "'list object' has no attribute 'name'"}
fatal: [db]: FAILED! => {"failed": true, "msg": "'list object' has no attribute 'name'"}
===============================================================

I've tried playing with the list of variables, tried also new loop with_item after the with_file, still no good luck, could someone please tell me how can I achieve my goal by having authorized_key module going to each file without specifying each time the full address like public_keys/web/authorized_key

- hosts: all
  vars:
    pcs:
      - name: web
      - name: db
  tasks:
  - name: Set up authorized_keys for the deploy user
    authorized_key: user=root key="{{ item }}"
    with_file:
      - public_keys/{{ pcs.name }}/authorized_key

Kai Stian Olstad

unread,
Feb 20, 2017, 2:46:39 PM2/20/17
to ansible...@googlegroups.com
Something like this should work:

- name: Set up authorized_keys for the deploy user
authorized_key: user=root key="{{ lookup('file', 'public_keys/{{
item.name }}/authorized_key') }}"
with_items: pcs

--
Kai Stian Olstad

Acrobis Nubian

unread,
Feb 21, 2017, 11:54:52 AM2/21/17
to Ansible Project, ansible-pr...@olstad.com
Thanks Kai! That's another way of looking at the problem :) Much appreciated!

But also I'm still curious, if I'd need to do a loop in a loop like I intended in the previous example, is it possible to do that in Ansible?


Kind regards,
Acrobis

Kai Stian Olstad

unread,
Feb 21, 2017, 12:24:08 PM2/21/17
to ansible...@googlegroups.com
To do a loop in a loop in Ansible, you need to put the inner loop in a
yaml file, and the use - include: with a loop and loop_control.
You can see an example here:
https://docs.ansible.com/ansible/playbooks_loops.html#loop-control

--
Kai Stian Olstad

Acrobis Nubian

unread,
Feb 21, 2017, 1:26:41 PM2/21/17
to Ansible Project, ansible-pr...@olstad.com
Thanks Kai! You were really helpful!

Kind regards,
Acrobis
Reply all
Reply to author
Forward
0 new messages