可转换字符串到变量(又名eval)



我有一个字符串strs = [ 'foo', 'bar' ]和一些dict foo = {'a': 1, 'b': 2}, bar = {'a': 3, 'b': 4}的列表。我想使用with_items来索引到命名的dicts

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

但我希望{{item}}引用名为foo和bar的变量,而不是字符串。在lisp或python中,我会使用eval。ansible中有类似的东西吗?

为什么不设置一个字典并使用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

也许他需要一些更动态的东西,如下所示。

这在2.1中是可能的。我需要得到一个散列的子集,其中包含一些散列键的数组,我偶然发现了这篇文章,然后我找到了一个解决方案。

我用这个。

我选择提供一个完全愚蠢、无用但完整的例子。

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

我对反馈很感兴趣。

相关内容

最新更新