我尝试将 json 传递给模块 uri 以进行 API 调用。
如果我将完整的 json 放入 body 参数中,效果很好:
body_format: json
body:
authorization_enabled: true
predefined_policy: "rbac.v1"
policy_data: |
{
"roles": {
"admin": {
"users": [
"myuser1",
"myuser2",
],
"allowed_actions": [
"addOrganizationMember",
"addOrganizationRepository",
"deleteOrganizationMember",
"deleteOrganizationRepository",
"updateAuthorizationPolicy",
"updateOrganizationRepository"
]
},
"owner": {
"users": [
"myuser"
]
}
}
}
如果我尝试将模板放入正文中,则 api 调用中会出现错误。
"message": "invalid input: invalid policy data"
body_format: json
body:
authorization_enabled: true
predefined_policy: "rbac.v1"
policy_data: |
{
"roles": {
"admin": {
"users": [
{% for item in admins %}
"{{ item }}",
{% endfor %}
],
"allowed_actions": [
"addOrganizationMember",
"addOrganizationRepository",
"deleteOrganizationMember",
"deleteOrganizationRepository",
"updateAuthorizationPolicy",
"updateOrganizationRepository"
]
},
"owner": {
"users": [
"myuser"
]
}
}
}
管理员变量是:
admins:
- myuser1
- myuser2
我尝试使用查找模板从文件中获取正文,但没有成功。对于静态内容或 jinja2 模板,此尝试不起作用。
body_format: json
body:
authorization_enabled: true
predefined_policy: "rbac.v1"
policy_data: "{{ lookup('ansible.builtin.template','policy.json.j2') }}"
模板是:
{
"roles": {
"admin": {
"users": [
{% for item in admins %}
"{{ item }}",
{% endfor %}
],
"allowed_actions": [
"addOrganizationMember",
"addOrganizationRepository",
"deleteOrganizationMember",
"deleteOrganizationRepository",
"updateAuthorizationPolicy",
"updateOrganizationRepository"
]
},
"owner": {
"users": [
"myuser"
]
}
}
}
如果我检查错误消息中的正文,一切看起来都很好:
"body": {
"authorization_enabled": true,
"policy_data": {
"roles": {
"admin": {
"allowed_actions": [
"addOrganizationMember",
"addOrganizationRepository",
"deleteOrganizationMember",
"deleteOrganizationRepository",
"updateAuthorizationPolicy",
"updateOrganizationRepository"
],
"users": [
"myuser1",
"myuser2"
]
},
"owner": {
"users": [
"myuser"
]
}
}
},
"predefined_policy": "rbac.v1"
},
注意:调用是在artifacthub.io api 上完成的。如果有人已经有帐户,您可以测试一下。
有什么想法吗??
这将导致无效的 JSON:
"users": [
{% for item in admins %}
"{{ item }}",
{% endfor %}
],
思考产生的结果;它总是会导致尾随逗号。例如,给定
admins
的示例值,这将产生:
"users": [
"myuser1",
"myuser2",
],
使用
to_json
过滤器可能会获得更好的结果:
{
"roles": {
"admin": {
"users": {{ admins|to_json }},
"allowed_actions": [
"addOrganizationMember",
"addOrganizationRepository",
"deleteOrganizationMember",
"deleteOrganizationRepository",
"updateAuthorizationPolicy",
"updateOrganizationRepository"
]
},
"owner": {
"users": [
"myuser"
]
}
}
}