【问题标题】:Ansible - List of dictionariesAnsible - 词典列表
【发布时间】:2023-02-02 21:32:51
【问题描述】:

让我介绍一下我的问题。 我的 ansible 代码中有一些 list od 字典:


my_example_list = [
    {
        "key1" : "value_of_first_key"
    },
    {
        "key2": "value_of_second_key"
    },
    {
        "key3": "value_of_third_key"
    }
]


我需要执行命令来遍历这个列表,它看起来应该是这样的:

 - name: 'Example'
   shell: 'Here is my {{ item.key }} and here is {{ item.value }}'

我做过或尝试做的事情:

我试图用 with_items 来做到这一点,但我无法指出特定键的值。 我也尝试使用 | 过滤值首先和 |最后但在我的情况下不起作用。

我想要实现的目标:

创建将遍历该列表并将分离的键 na 值注入命令的循环。

【问题讨论】:

  • 您能向我们展示一下您为解决这个问题所做的尝试吗?

标签: ansible


【解决方案1】:

我被要求展示我是如何尝试解决我的问题的:

这是一些代码:


# Showing last component failing
- name: "Try to show last component of my list"
  debug:
    msg: "{{ my_example_list[1] | last }}"

# When i'm trying to show first component of my list i get "key1"
- name: "Try to show first component of my list"
  debug:
    msg: "{{ my_example_list[1] | first }}"

# This shows me my list of dict
- name: "Trying use with_items"
  debug:
    msg: "{{ item }}"
  with_items: "{{ my_example_list }}"

# But when i'm trying point to key and value for example 
- name: "Trying use with_items point to key and value"
  debug:
    msg: "Here is my {{ item.key }} which keep {{ item.value }}"
  with_items: "{{ my_example_list }}"

# It's failing. 

抱歉,使用循环可能不是解决方案。几天来我一直在处理这个问题......作为第一步,我想知道如何正确指向键和值对。

【讨论】:

    【解决方案2】:

    我们的数据结构和命名似乎是不利的。

    以下最小示例剧本

    ---
    - hosts: localhost
      become: false
      gather_facts: false
    
      vars:
    
        example_list: |
          [
            {
              "key1" : "value_of_first_key"
            },
            {
              "key2": "value_of_second_key"
            },
            {
              "key3": "value_of_third_key"
            }
          ]
    
      tasks:
    
      - name: Example loop
        debug:
          msg: "{{ item }} is of type {{ item | type_debug }}"
        loop: "{{ example_list }}"
    
      - name: Example loop
        debug:
          msg: "{{ item.values() }}"
        loop: "{{ example_list }}"
    

    将导致输出

    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-31
      • 2020-05-13
      相关资源
      最近更新 更多