首页 > 解决方案 > 在 Ansible 中将 yaml hash 的值转换为 json hash 的键

问题描述

我试图让 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 值并将它们放入列表中。

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

标签: jsonansibleyamlansible-factsjmespath

解决方案


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

---
- 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,"
}

推荐阅读