2014-11-06 78 views
3

我有一個字符串列表strs = ['foo','bar']和一些字典foo = {'a':1,'b':2},bar = { 'a':3,'b':4}。我想使用with_items索引到一個名爲類型的字典ansible string to variable(aka eval)

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

但我想{{項目}}引用名爲foo的變量和酒吧,而不是字符串。在lisp或python中,我會使用eval。有沒有類似的事情?

回答

3

爲什麼不設置字典並使用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 
0

也許他需要一些更具活力的東西如下。

這可能與2.1。 我需要得到一個散列的子集,其中包含一些散列鍵的數組,我偶然發現了這篇文章,然後我找到了一個解決方案。我使用that

我選擇提供一個完全愚蠢和無用但完整的例子。

--- 
- 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}}" 

ansible-劇本的輸出是這樣的:

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 

我感興趣的反饋。