请参阅下面的第一个电话,哪个有效。这是我如何在系统上创建模板的示例。注意我必须使用 {% raw %} ... {% endraw %} 所以 ansible 不会尝试解释我模板中的变量。
- name: Create a template : OK
uri:
url: https://{{ ip }}/api/v1/templates
method: POST
headers:
Authorization: "{{ token }}"
Content-Type: application/json
body: |
{
"name": "{{ template_name }}",
"type": "v1",
"description": "{{ template_name }}",
"content": "template: | {% raw %}\n {\n \"class\": \"ABC\",\n \"param\": {{param1::integer}}\n }{% endraw %}"
}
body_format: json
timeout: 60
status_code: 202
validate_certs: false
register: json_response
输出正常:
ok: [notahost] => {
"invocation": {
"module_args": {
"body": {
"content": "template: | \n {\n \"class\": \"ABC\",\n \"param\": {{param1::integer}}\n }",
"description": "test1",
"name": "test1",
"type": "v1"
},
"body_format": "json",
现在,我试图将模板的内容移到一个名为 template1.j2 的文件中。
模板1.j2:
{% raw %}
{
"class": "ABC",
"param": {{param1::integer}}
}
{% endraw %}
我将模板 template1.j2 插入到我的 JSON 正文中(注意我在模板中添加了 {% raw %} ... {% endraw %})。
- name: Create a template NOK
uri:
url: https://{{ ip }}/api/v1/templates
method: POST
headers:
Authorization: "{{ token }}"
Content-Type: application/json
body: |
{
"name": "{{ template_name }}",
"type": "v1",
"description": "{{ template_name }}",
"content": "template: | {{ lookup('file','template1.j2') }}"
}
body_format: json
timeout: 60
status_code: 202
validate_certs: false
register: json_response
输出 NOK:
fatal: [notahost]: FAILED! => {
"content": "{\"message\":\"request body has an error: failed to decode request body: invalid character '\\\\n' in string literal\"}\n",
"invocation": {
"module_args": {
"body": "{\n \"name\": \"test2\",\n \"type\": \"v1\",\n \"description\": \"test2\",\n \"content\": \"template: | \n{\n \"class\": \"ABC\",\n \"param\": {{param1::integer}}\n} \n\"\n}\n",
"body_format": "json",
出于某种原因,看起来我这样做的方式不起作用,ansible 仍然尝试在创建时解释我的模板中的变量。
关于如何在 ansible 任务之外使用我的模板进行工作的任何想法?
PS:我尝试使用 shell ansible 模块加载模板文件,但没有帮助。
谢谢和问候, 罗曼