ansible - 如何在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 对象的关键。
解决方案
在我知道的任何情况下,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
键
推荐阅读
- gatsby - 使用静态站点生成器 (Gatsby) 和 Microsoft Graph Toolkit 生成错误
- php - 如何将这样的json数组转换为查看laravel
- python - 过采样时如何保持/扩展索引
- java - 如何使用springdoc-openapi以相反的顺序对端点进行排序
- java - 依赖maven jar的问题,我得到以下错误,
- c# - Visual Studio Webform 登录页面 (C#) 按钮 onlick 发送到 html 页面
- npm - 如何在路径“node_modules/sharp/build/Release/../../”中添加“vendor/lib/libvips.42.dylib”?
- android - 如何根据 Firebase 中的时间戳获取某些文档
- excel - MS Access 有没有办法根据以前的记录进行计算?
- android - Wayland 上的 Android 模拟器:模拟器以退出代码 134 终止