Ansible - 将loopItem用作现有变量的哈希键

时间:2018-03-23 14:24:29

标签: hash ansible

我使用Ansible 2.4.2.0。

我有一个剧本并定义了一个变量def label_map_to_dict(path): file = open(path, 'r') ids = [] labels = [] for line in file: if 'id:' in line: ids.append(int(line.split(':')[1].strip())) if 'name:' in line: labels.append(line.split("'")[1]) return dict(zip(labels, ids)) 。我有一个看起来像的注册变量:

host: mymachine

我现在想要使用"json": { "results": [ { [...], "item": "myname", "stdout_lines": "abc" [...] }, { [...], "item": "myname2", "stdout_lines": "xyz" [...] { ] } 的值作为新哈希的键(与我的item一起)。 像这个任务:

host

我希望我的哈希看起来像:

-name Create Hash
    set_fact:
      "{{ host[item.item] }}": "{{ item.stdout_lines }}"
    with_items:
      - "{{ json.results }}" `

我知道"mymachine": { "myname": "abc", "myname2": "xyz" } 的迭代有效,json.resultsitem.item可以访问。但item.stdout_lines - 部分不起作用。我尝试了括号的所有组合,我得到了不同的错误信息,具体取决于我使用的括号组合。

希望有人能告诉我正确的语法。

1 个答案:

答案 0 :(得分:2)

  

我希望我的哈希看起来像:

"mymachine": {
  "myname": "abc",
  "myname2": "xyz"
}

如果要定义名为mymachine的字典,为什么您的代码甚至不包含字符串mymachine

  

"{{ host[item.item] }}": - 部分不起作用

为什么它应该工作,如果尝试使用它是代码中第一次出现host?你引用一个变量而不定义它。

这是您想要实现的正确语法:

- name: Create Hash
  set_fact:
    mymachine: "{{ mymachine | default({}) | combine(myelement) }}"
  vars:
    myelement: "{ '{{ item.item }}':'{{ item.stdout_lines }}' }"
  with_items:
    - "{{ json.results }}"