所以我正在运行一个 ansible 角色,它在 defaults/role 文件夹中有一个文件 main.yml 。该文件的内容是这样的:
---
api_secrets:
'API_PROFILE': "{{ api_profile }}"
'SERVER_ADDRESS': "{{ server_address }}"
'MGMT_SERVER_ADDRESS': "{{ management_server_address }}"
现在我想在 MGMT_SERVER_ADDRESS 之后包含 api_secrets 块,如下所示:
{% if '"port" in mgmt_ports' %}
'MGMT_SERVER_PORT': "{{ management_server_port1 }}"
'MGMT_SERVER_USER': "{{ user1 }}"
{% else %}
'MGMT_SERVER_PORT': "{{ management_server_port2 }}"
'MGMT_SERVER_USER': "{{ user2 }}"
{% endif %}
从这里开始,在服务器上创建一个文件,其中包含上述内容,当然用它们的实际值替换变量。
无论我如何尝试,它总是会导致不同的错误。我尝试使用“{% if ... endif %}”,也使用 ''
错误是这样的:
ERROR! Syntax Error while loading YAML.
found character that cannot start any token
The error appears to be in '/opt/ansible/roles/api/defaults/main.yml': line 55, column 2, but may
be elsewhere in the file depending on the exact syntax problem.
The offending line appears to be:
{% if '"port" in mgmt_ports' %}
^ here
我也试过这样:
"{% if (port in mgmt_ports) %}
'MGMT_SERVER_PORT': "{{ management_server_port1 }}"
{% else %}
'MGMT_SERVER_PORT': "{{ management_server_port2 }}"
{% endif %}"
在这种情况下,错误是:
ERROR! Syntax Error while loading YAML.
could not find expected ':'
The error appears to be in '/opt/ansible/roles/api/defaults/main.yml': line 56, column 24, but may
be elsewhere in the file depending on the exact syntax problem.
The offending line appears to be:
"{% if (port in mgmt_ports) %}
'MGMT_SERVER_PORT': "{{ management_server_port1 }}"
^ here
We could be wrong, but this one looks like it might be an issue with
missing quotes. Always quote template expression brackets when they
start a value. For instance:
with_items:
- {{ foo }}
Should be written as:
with_items:
- "{{ foo }}"
这样做的正确方法是什么?
我知道使用 jinja2 模板会更容易,但是剧本是这样创建的,我必须坚持这种方法。