如何使用拆分方法检索字典值



拆分字典在 ansible 中不起作用。安斯布 - 2.5.15

任何人都可以帮助任何解决方案。

我试图从字典中获取值,但无法获取值。

尝试的代码:

- hosts: localhost
  connection: local
  tasks:
    - set_fact:
       some_module: "{{ item.split(': ')[1] }}"
      with_items:
        - git: true
        - gradle: false

得到以下错误:

The task includes an option with an undefined variable. The error was: 'dict object' has no attribute 'split'

预期成果如下:

[真、假]

您可以将其作为哈希映射处理并获取键或值:

- hosts: localhost
  connection: local
  tasks:
    - set_fact:
       some_module: "{{ item.values }}"
      with_items:
        - {git: true}
        - {gradle: false}

(针对 Ansible 2.9 及更高版本进行了更新(

给定列表

    l:
      - git: true
      - gradle: false

任务

    - set_fact:
        out: "{{ l|map('dict2items')|
                   flatten|
                   map(attribute='value')|
                   list }}"

给出所需的结果

  out:
  - true
  - false

如果数据是字典,例如

    d:
      git: true
      gradle: false

解决方案会简单得多,例如下面的任务给出相同的结果

    - set_fact:
        out: "{{ d.values()|list }}"

笔记

您的数据不是字典。这是一个列表

    - git: true
    - gradle: false

字典如下

    git: true
    gradle: false

让我们先从数据创建一个字典,然后使用 dict2items 过滤器。

下面的玩法

- hosts: localhost
  vars:
    data1:
      - {git: true}
      - {gradle: false}
    data2: {}
  tasks:
    - set_fact:
        data2: "{{ data2|combine(item) }}"
      loop: "{{ data1 }}"
    - debug:
        msg: "{{ data2|dict2items|json_query('[].value') }}"

给:

"msg": [
    true, 
    false
]

dict2items 从 Ansible 2.6 开始可用。在旧版本中,使用简单的filter_plugin hash_utils.py

$ cat filter_plugins/hash_utils.py
def hash_to_tuples(h):
    return h.items()
def hash_keys(h):
    return h.keys()
def hash_values(h):
    return h.values()
class FilterModule(object):
    ''' utility filters for operating on hashes '''
    def filters(self):
        return {
            'hash_to_tuples' : hash_to_tuples
            ,'hash_keys'     : hash_keys
            ,'hash_values'   : hash_values
        }

以下任务

- debug:
    msg: "{{ data2|hash_values }}"

给出的结果与上面带有 dict2Items 的构造相同。您可能需要尝试其他筛选器并查看有关filter_plugin的详细信息。

最新更新