Accessible variable string (aka eval)

I have a list of strings strs = ['foo', 'bar'] and some dicts foo = {'a': 1, 'b': 2}, bar = {'a': 3, 'b': 4} ... I would like to use with_items to index in the dicts name

- copy
  src: {{item}}.a
  dest: {{item}}.b
  with_items: strs

      

But I want {{item}} to refer to variables named foo and bar, not strings. In lisp or python I would use for this eval

. Is there something like this out there?

+3


source to share


2 answers


Why not install the dictionary and skip it with with_dict

?



---
- hosts: localhost
  connection: local
  vars:
    strs:
      foo:
        a: 1
        b: 2
      bar:
        a: 3
        b: 4

  tasks:
  - copy: src={{ item.value.a }} dest={{ item.value.b }}
    with_dict: strs

      

+3


source


Perhaps he needed something more dynamic, as it should.

This is possible with 2.1. I needed to get a subset of a hash having an array of some hash keys, I came across this post and then I found a solution.

I am using which .

I want to provide a completely stupid and useless but complete example.



---
- hosts: localhost
  vars:
    filenames: [ file1, file2 ]
    file1:
      a: file1.c
      b: file1.o
    file2:
      a: file2.c
      b: file2.o
    file3:
      a: file3.py
      b: file3.pyc
  tasks:
    - debug: msg="gcc -c -o {{item.b}} {{item.a}}"
      with_items: 
        - "{{ filenames | map('extract', vars) | list}}"

      

Output file for audible playback:

PLAY [localhost] ***************************************************************

TASK [setup] *******************************************************************
ok: [localhost]

TASK [debug] *******************************************************************
ok: [localhost] => (item={u'a': u'file1.c', u'b': u'file1.o'}) => {
    "item": {
        "a": "file1.c", 
        "b": "file1.o"
    }, 
    "msg": "gcc -c -o file1.o file1.c"
}
ok: [localhost] => (item={u'a': u'file2.c', u'b': u'file2.o'}) => {
    "item": {
        "a": "file2.c", 
        "b": "file2.o"
    }, 
    "msg": "gcc -c -o file2.o file2.c"
}

PLAY RECAP *********************************************************************
localhost                  : ok=2    changed=0    unreachable=0    failed=0  

      

I'm interested in reviews.

0


source







All Articles