ansible字符串到变量(aka eval)

时间:2014-11-06 12:15:24

标签: ansible

我有一个字符串列表strs = ['foo','bar']和一些dicts 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中有类似的东西吗?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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-playbook的输出是:

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  

我对反馈感兴趣。

相关问题