简体   繁体   中英

Ansible; using a loop to cycle through variables

I have an inventory in which many host_vars are set. Each host will contain a different number of datasets.

eg

host: host1
ip-addr: 192.0.2.12/24
datasets:
  set1:
     var1: 'east'
     var2: 'west'
  set2:
     var1: 'north'
     var2: 'south'

I can create a loop to count the datasets, but I don't seem able to use it to reference [varX]:

 - name: "test loop"
   debug:
     msg: 
         - "{{ item }}"
         - "{{ 'datasets.set' + item + '.var1' }}"
         - "{{ datasets.set1.var1 }}"
    loop: "{{ query('sequence', 'start=1 end='+((datasets|length)|string)) }}"

This appears to assemble the variable name I'm attempting to reference, however does not return the value associated with it. Manually calling that variable does return the interesting value.

ok: [host1] => (item=1) => {
    "msg": [
        "1",
        "datasets.set1.var1",
        "east"
    ]
}
ok: [host1] => (item=2) => {
    "msg": [
        "2",
        "datasets.set2.var1",
        "east"
    ]
}

Is what I'm doing possible, or should I be approaching it from another angle?

thanks in advance.

The task

    - debug:
        msg: "set{{ item }}.var1 = {{ datasets['set' ~ item].var1 }}"
      loop: "{{ range(1, datasets|length+1)|list }}"

gives

    "msg": "set1.var1 = east"
    "msg": "set2.var1 = north"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM