Score:1

Ansible include_vars: Including dictionary variables from a file

I'm trying to load dictionary variables from a file and can't access the variables inside. Could you please help me? sorry for so simple a question

Here is a working code example:

---
  tasks:
  - name: Dict test
    vars:
      users:
        alice:
          name: Alice Appleworth
          telephone: 123-456-7890
        bob:
          name: Bob Bananarama
          telephone: 987-654-3210
    debug:
      msg: "User {{ item.key }} is {{ item.value.name }} ({{ item.value.telephone }})"
    loop: "{{ lookup('dict', users) }}"

But when I add the dict to a file and use include_vars to load it, the above code doesn't work.

File: test1.yml

users:
  alice:
    name: Alice Appleworth
    telephone: 123-456-7890
  bob:
    name: Bob Bananarama
    telephone: 987-654-3210

The following code doesn't work

  tasks:
  - name: Dict test
    include_vars: test1.yml
    debug:
      msg: "User {{ item.key }} is {{ item.value.name }} ({{ item.value.telephone }})"
    loop: "{{ lookup('dict', users) }}"

But ansible dubuging -vvv shows

ok: [localhost] => {
    "ansible_facts": {
        "users": [
            {
                "alice": null,
                "name": "Alice Appleworth",
                "telephone": "123-456-7890"
            },
            {
                "bob": null,
                "name": "Bob Bananarama",
                "telephone": "987-654-3210"
            }
        ]
    },
cn flag
Generally "does not work" is meaningless by itself -- you should cite the error-message(s) you're getting...
Score:2
th flag

"Doesn't work" is a very vague description of your problem, but this is not a valid task definition:

  - name: Dict test
    include_vars: test1.yml
    debug:
      msg: "User {{ item.key }} is {{ item.value.name }} ({{ item.value.telephone }})"
    loop: "{{ lookup('dict', users) }}"

include_vars and debug are individual actions so they need to be separate tasks; as you have it this should give you the helpful error ERROR! conflicting action statements: include_vars, debug

  - include_vars: test1.yml

  - name: Dict test
    debug:
      msg: "User {{ item.key }} is {{ item.value.name }} ({{ item.value.telephone }})"
    loop: "{{ users | dict2items }}"
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.