0
votes

Sorry if there are many posts about variables inside variable my use case is different. Trying to access an element from a variable list "efs_list" based on the index-number of the current host. There are three hosts in the inventory

  vars:
    efs_list:
      - efs1
      - efs2
      - efs3
    sdb_index: "{{ groups['all'].index(inventory_hostname) }}" 

The values should be as follows host1- efs1 host2- efs2 host3- efs3

Tried accessing it through efs_list.{{ sdb_index }} for - debug: var=efs_list.{{ sdb_index }} the output is as intended

ok: [10.251.0.174] => {
    "efs_list.0": "efs1"
}
ok: [10.251.0.207] => {
    "efs_list.1": "efs2"
}
ok: [10.251.0.151] => {
    "efs_list.2": "efs3"
}

But for

     - debug:
        msg: "{{ efs_list.{{ sdb_index }} }}"

fatal: [10.251.0.174]: FAILED! => {"msg": "template error while templating string: expected name or number. String: {{ efs_list.{{ sdb_index }} }}"}

---
- name: SDB Snapshots Creation
  hosts: all
  remote_user: "centos"
  become: yes
  vars:
    efs_list:
      - efs1
      - efs2
      - efs3
    sdb_index: "{{ groups['all'].index(inventory_hostname) }}" 

  tasks:
    - debug: var=efs_list.{{ sdb_index }}

    - debug:
        msg:  "{{ efs_list.{{ sdb_index }} }}"

    - name: Get  Filesystem ID
      become: false
      local_action: command aws efs describe-file-systems --creation-token "{{ efs_list.{{ sdb_index }} }}"
         --region us-east-1 --query FileSystems[*].FileSystemId --output text  
      register: fs_id

It should attribute the element of list to current indexenter code here

1

1 Answers

0
votes

extract filter will do the job. The input of the filter must be a list of indices and a container (array in this case). The tasks below

- set_fact:
    sdb_index: "{{ [] + [ groups['all'].index(inventory_hostname) ] }}"
- debug:
    msg: "{{ sdb_index|map('extract', efs_list)|list }}"

give

ok: [host1] => {
    "msg": [
        "efs1"
    ]
}
ok: [host2] => {
    "msg": [
        "efs2"
    ]
}
ok: [host3] => {
    "msg": [
        "efs3"
    ]
}

If the hosts are not sorted in the inventory it's necessary to sort them in the play

- set_fact:
    my_hosts: "{{ groups['all']|sort }}"
- set_fact:
    sdb_index: "{{ [] + [ my_hosts.index(inventory_hostname) ] }}"
- debug:
    msg: "{{ sdb_index|map('extract', efs_list)|list }}"