Bindu G
Bindu G

Reputation: 103

use dynamic variable as dictionary name

I have playbook as below:

- name: fetch host group name
  set_fact: 
    group_name: '{{ group_names[0]  }}'

- name: get memory and storage minimum requirements
  set_fact:
    min_memory: "{{ group_name.memory }}"
    min_storage: "{{ group_name.storage }}"

In defaults/main.yml

#memory and storage settings
primary:
  memory: 32
  storage: 128

my inventory host is in primary group. when I run playbook, I am seeing below error. TASK [ansible-elastic-cloud-enterprise : get memory and storage minimum requirements] **************************************************************************************************************************** fatal: [192.168.153.5]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'str object' has no attribute 'memory'\n\nThe error appears to be in '/cygdrive/c/Users/test/Downloads/ansible-elastic-cloud-enterprise-master/roles/ansible-elastic-cloud-enterprise/tasks/base/general/checkmemorystorage.yml': line 7, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n- name: get memory and storage minimum requirements\n ^ here\n"}

Upvotes: 1

Views: 350

Answers (1)

Frenchy
Frenchy

Reputation: 17007

you want to use the content of variable like another variable, so use lookup vars:

sample:

- name: dynamic var
  hosts: localhost
  gather_facts: no
  vars:
    groupname: ["primary", "secondary"]
    primary:
      memory: 32
      storage: 128
  tasks:

    - set_fact:
        id: "{{ lookup('vars', groupname[0]) }}"
  
    - debug: msg="{{ id.memory }} -- {{ id.storage }} "

result:

ok: [localhost] => {
    "msg": "32 -- 128 "

in your case you should write:

- name: fetch host group name
  set_fact: 
    group_name: '{{ lookup("vars", group_names[0] }}'

Upvotes: 2

Related Questions