0

I'm stuck trying to use a variable in another variable declaration. Here is the code in my playbook:

- hosts: operate
  roles:
    - { role: dns, vargroup: 'test' }

- hosts: test
  roles:
    - common
    - certbot
    - ...

And now the very first lines of my dns role:

- debug: var=vargroup

- name: Extracting IP(s) {{vargroup}}
  vars:
    extractip: "{{ hostvars[groups['{{ vargroup }}'][0]]['ip'] }}"
  set_fact:
    newip: "{{ item.expose }}"
  with_items: 
    - '{{ extractip }}'

Vargroup is correclty printed in debug and my task name. But in the extractip part, i've got this error:

{
    "msg": "'dict object' has no attribute '{{ vargroup }}'",
    "_ansible_no_log": false
}

Obviously, i've try hardcoding the line like:

    extractip: "{{ hostvars[groups['test'][0]]['ip'] }}"

And it worked like a charm. I really don't know how to use this var in my var declaration :)

1 Answer 1

1

This is probably caused by the way quotes works in YAML. After variable substitution '{{ extractip }}' will become '{{ hostvars[groups['{{ vargroup }}'][0]]['ip'] }}'. It will try to interprete '{{ vargroup }}' as a plain string instead of variable.

Just use double quotes and it will work

  with_items: 
    - "{{ extractip }}"

Since Ansible doesn't support nesting "{{ }}" construct, but you can simply remove that part and just use "{{ hostvars[groups[vargroup][0]]['ip'] }}".

Sign up to request clarification or add additional context in comments.

5 Comments

Hello, thank you for your help ! Unfortunately it is still not working :/
Try this "{{ hostvars[groups[vargroup][0]]['ip'] }}"
Worked ! Thank you :) Regarding this doc: docs.ansible.com/ansible/latest/reference_appendices/… I tried: extractip: "{{ hostvars[groups[{{ lookup('vars', 'vargroup') }}][0]]['ip'] }}" Do you know why it is not working ?
Because, as explained above, you cannot nest jinja2 expression expansion markers (double curly braces). This would work: "{{ hostvars[groups[lookup('vars', 'vargroup')][0]]['ip'] }}". But that is not really following the KISS principle.
Thank you guys ! I got it now :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.