mayer
mayer

Reputation: 145

Ansible "item is undefined" when using {{ item }} in "vars" section

I have some codes like below, I want to iterate each host in groups['A'] and groups['B'] to create the group.

- name: Create a group
  group:
    name: "test_group"
    state: "present"
  delegate_to: "{{ item }}"
  vars:
    ansible_ssh_user: "{{ lookup('env', 'USER') }}@user@{{ item }}"
  with_items:
    - "{{ groups['A'] }}"
    - "{{ groups['B'] }}"

Because I want to modify the ansible ssh connection user to connect to the "delegate_to" host, I override the ansible_ssh_user in this task, but it won't work and give me the error message like

FAILED! => {"msg": "'item' is undefined"}

But if I comment out the lines of

vars:
    ansible_ssh_user: "{{ lookup('env', 'USER') }}@user@{{ item }}"

It gives no errors.

Upvotes: 0

Views: 695

Answers (2)

mayer
mayer

Reputation: 145

Finally, I got a workaround, it involves all groups I need to use in my playbook. And use "when" condition like

delegate_to: "{{ item }}"
with_items:
  - "{{ groups['A'] }}"
  - "{{ groups['B'] }}"
when: "inventory_hostname == item"

to let the task only run on the hosts mentioned in the "with_items" section.

It's not a very cool workaround but works for me... Thank you for looking at this problem!

Upvotes: 0

The HCD
The HCD

Reputation: 510

try changing the var to:

 ansible_ssh_user: "{{ lookup('env', 'USER') }}@user@{{ ansible_hostname }}

this works fine for me:

- name: 'install public key on every server'
  authorized_key:
    user: '{{ myuser}}'
    key: "{{ myuser.ssh_public_key }}"
  delegate_to: '{{ item }}'
  with_items:
    - '{{ groups["A"] }}'
    - '{{ groups["B"] }}'
    - '{{ groups["C"] }}'

maybe you could try but before I delegated a set_fact and recovered it locally...

Upvotes: 0

Related Questions