【问题标题】:transform values of yaml hash into keys of json hash in Ansible在 Ansible 中将 yaml hash 的值转换为 json hash 的键
【发布时间】:2019-09-03 01:32:54
【问题描述】:

我正在尝试让 Ansible 将哈希数组转换为键值对列表,其中键是第一个哈希中的一个值,而值是第一个哈希中的不同值。

一个例子会有所帮助。

我想转换:-

TASK [k8s_cluster : Cluster create | debug result of private ec2_vpc_subnet_facts] ***
ok: [localhost] => {
    "result": {
        "subnets": [
            {
                "availability_zone": "eu-west-1c", 
                "subnet_id": "subnet-cccccccc", 
            }, 
            {
                "availability_zone": "eu-west-1a", 
                "subnet_id": "subnet-aaaaaaaa", 
            }, 
            {
                "availability_zone": "eu-west-1b", 
                "subnet_id": "subnet-bbbbbbbb", 
            }
        ]
    }
}

进入

eu-west-1a: subnet-aaaaaaaa   
eu-west-1b: subnet-bbbbbbbb    
eu-west-1c: subnet-cccccccc 

我试过result.subnets | map('subnet.availability_zone': 'subnets.subnet_id')(根本不起作用)和json_query('subnets[*].subnet_id',它只是挑选出subnet_id 值并将它们放入一个列表中。

我想我可以使用 Zip 和 Hash in Ruby 来做到这一点,但我不知道如何在 Ansible 中进行这项工作,或者更具体地说是在 Jmespath 中进行。

【问题讨论】:

    标签: json ansible yaml ansible-facts jmespath


    【解决方案1】:

    Jmespath 不允许在多选哈希中使用动态名称。我发现 an extension to jmespath 允许通过使用键引用来做这样的事情,但它不是普通 jmespath 实现的一部分,也不是 ansible。

    要在简单的 ansible 中执行此操作,您必须创建一个新变量并使用循环填充它。使用其他过滤器可能还有其他方法,但这是我想出的解决方案:

    - name: Create the expected hash
      set_fact:
        my_hash: >-
          {{
            my_hash
            | default({})
            | combine({ item.availability_zone: item.subnet_id })
          }}
      loop: "{{ subnets }}"
    
    - name: Print result
      debug:
        var: my_hash
    

    【讨论】:

      【解决方案2】:

      我已经生成了下面的列表,我将在生成的列表中添加一个新行(想先分享这个)

      ---
      - name: play
        hosts: localhost
        tasks:
          - name: play
            include_vars: vars.yml
      
          - name: debug
            debug:
              msg: "{% for each in subnets %}{{ each.availability_zone }}:{{ each.subnet_id  }}{% raw %},{% endraw %}{% endfor %}"
      

      输出--->

      ok: [localhost] => {
          "msg": "eu-west-1c:subnet-cccccccc,eu-west-1a:subnet-aaaaaaaa,eu-west-1b:subnet-bbbbbbbb,"
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-08-13
        • 2013-07-30
        • 1970-01-01
        • 1970-01-01
        • 2019-07-15
        • 2018-07-13
        • 2012-04-08
        • 2011-06-22
        相关资源
        最近更新 更多