![Ansible-使用 if elif else 根据条件定义变量](https://linux22.com/image/772629/Ansible-%E4%BD%BF%E7%94%A8%20if%20elif%20else%20%E6%A0%B9%E6%8D%AE%E6%9D%A1%E4%BB%B6%E5%AE%9A%E4%B9%89%E5%8F%98%E9%87%8F.png)
我有以下多个角色:haproxy,java,nginx,tomcat
├── ansible-test-host.yml
├── hapoxy
├── java
├── myplaybook.yml
├── nginx
└── tomcat
基本剧本是:myplaybook.yml
如下所示:
---
- hosts: test-local
connection: local
vars:
java_version: "1.8.0"
roles:
- java
因此,我的要求取决于指定的角色 java/tomcat/nginx 等,我有一个要填充的模板文件。假设我的逻辑如下:
if
role == java then in template.j2 I have to set `JAVA_TOOL_OPTIONS= -Xmx10g -Xms5g`
elif
role == tomcat then in template.j2 I have to set `JAVA_OPTS= -Xmx10g -Xms5g`
else
NOTHING
endif
我还有其他潜在场景需要整理,但如果我得到了休息的基础,我就可以做到。
我在 java role main.yml 中尝试过的是这里
---
# tasks file for java
- name: output the 'ansible_' magic variables
debug:
msg: [
"ansible_role_names = {{ ansible_role_names | default({}) }}",
"ansible_dependent_role_names = {{ ansible_dependent_role_names }}",
"ansible_play_role_names = {{ ansible_play_role_names | default([]) | join(',') }}"
]
- name: set facts
set_fact:
DEFAULT_VAR: >
{% if "{{ ansible_play_role_names | default([]) | join(',') }}" == "java" %}
JAVA_TOOL_OPTIONS
{% elif "{{ ansible_play_role_names | default([]) | join(',') }}" == 'tomcat' %}
CATALINA_OPTS
{% else %}
NOTHING
{% endif %}
- name: output my custom var- try1
debug:
msg: >
{% if "{{ ansible_play_role_names | default([]) | join(',') }}" == "java" %}
JAVA_TOOL_OPTIONS
{% else %}
NOTHING
{% endif %}
- name: output my custom var - echo
debug:
msg: "{{ DEFAULT_VAR }}"
我的输出如下
TASK [java : output the 'ansible_' magic variables] ****************************************************
ok: [127.0.0.1] => {
"msg": [
"ansible_role_names = ['java']",
"ansible_dependent_role_names = []",
"ansible_play_role_names = java"
]
}
TASK [java : set facts] ********************************************************************************
ok: [127.0.0.1]
TASK [java : output my custom var- try1] ***************************************************************
ok: [127.0.0.1] => {
"msg": " NOTHING \n"
}
TASK [java : output my custom var - echo] **************************************************************
ok: [127.0.0.1] => {
"msg": " NOTHING \n"
}
PLAY RECAP *********************************************************************************************
127.0.0.1 : ok=5 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
请帮助提供指示以实现此目的。