Ansible

ansible main.yml if else 條件

  • October 15, 2021

所以我正在執行一個 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 模板會更容易,但是劇本是這樣創建的,我必須堅持這種方法。

變數模板化發生在 YAML 解析步驟之後,因此您不能以這種方式使用它來模板化 YAML。

最簡單的方法是將條件移動到各個 Jinja 表達式中:

api_secrets:
 API_PROFILE: "{{ api_profile }}"
 SERVER_ADDRESS: "{{ server_address }}"
 MGMT_SERVER_ADDRESS: "{{ management_server_address }}"
 MGMT_SERVER_PORT: "{{ management_server_port1 if 'port' in mgmt_ports else management_server_port2 }}"
 MGMT_SERVER_USER: "{{ user1 if 'port' in mgmt_ports else user2 }}"

您也可以使用 Jinja 語句,但這會使相同結果的值更長一些。

api_secrets:
 API_PROFILE: "{{ api_profile }}"
 SERVER_ADDRESS: "{{ server_address }}"
 MGMT_SERVER_ADDRESS: "{{ management_server_address }}"
 MGMT_SERVER_PORT: "{% if 'port' in mgmt_ports %}{{ management_server_port1 }}{% else %}{{ management_server_port2 }}{% endif %}"
 MGMT_SERVER_USER: "{% if 'port' in mgmt_ports %}{{ user1 }}{% else %}{{ user2 }}{% endif %}"

引用自:https://serverfault.com/questions/1080617