首页 > 解决方案 > 如何在ansible playbook中将变量作为json对象键传递?

问题描述

我正在尝试执行 curl 命令,该命令将变量作为 json 正文中的键,但变量没有被替换为导致 400 错误的值:

tasks:
- name: set source tag 
  uri:
    url: https://****/api/v2/source
    method: POST
    body: 
      tags: 
         "{{ ec2_tag_KubernetesCluster }}": true
         "{{ ec2_tag_Environment }}": true
         "{{ ec2_tag_aws_autoscaling_groupName }}": true
      sourceName: "{{ ec2_tag_hostname }}"
    body_format: "json"  
    headers:
      Content-Type: "application/json"
      Accept: "application/json" 

输出:

"changed": false,
"connection": "close",
"content": "{\"status\":{\"result\":\"ERROR\",\"message\":\"invalid tag: {{ ec2_tag_Environment }}\",\"code\":400}}",
"content_length": "91",
"content_type": "application/json",
"date": "Tue, 22 Jun 2021 11:24:33 GMT",
"elapsed": 0,
"invocation": {
    "module_args": {
        "attributes": null,
        "backup": null,
        "body": {
            "sourceName": "eks-****-2-2a-worker53",
            "tags": {
                "{{ ec2_tag_Environment }}": true,
                "{{ ec2_tag_KubernetesCluster }}": true,
                "{{ ec2_tag_aws_autoscaling_groupName }}": true
            }
        },
        "body_format": "json",
        "client_cert": null,
        "client_key": null,
        "content": null,
        "creates": null,
        "delimiter": null,
        "dest": null,
        "directory_mode": null,
        "follow": false,
        "follow_redirects": "safe",
        "force": false,
        "force_basic_auth": false,
        "group": null,
        "headers": {
            "Accept": "application/json",

如您所见,“ec2_tag_hostname”被替换为变量值,但“ec2_tag_Environment”、“ec2_tag_KubernetesCluster”和“ec2_tag_aws_autoscaling_groupName”没有被替换,因为它们是 json 对象的关键。

标签: ansible

解决方案


在我知道的任何情况下,YAML 都不支持动态密钥;您将需要将插值上移一级以实现您所追求的目标:

    body: >-
      {{
      {
      "tags": {
         ec2_tag_KubernetesCluster: True,
         ec2_tag_Environment: True,
         ec2_tag_aws_autoscaling_groupName: True,
      },
      "sourceName": ec2_tag_hostname,
      }
      }}
    body_format: "json"  

之所以有效,是因为与 yaml 不同,python(以及因此 jinja2)确实支持动态dict


推荐阅读