Reputation: 1387
I am new to Ansible and trying to understand what is wrong with my syntax.
My goal is that only one of the roles will be selected. I do not want to use 'when'.
Here is what I wrote (I am using Ansible v2.9.5):
- name: Install external DB for Cloudera Manager Server
hosts: db_server
roles:
- {{% if (databases_type == "postgresql") %} role: postgresql {% else %} {% endif %}
{% if (databases_type == "mysql") %} role: mariadb {% else %} {% endif %}
{% if (databases_type == "oracle") %} role: oracledb}
When I run the playbook I get a syntax error but it is not clear enough.
Thanks in advance.
Upvotes: 1
Views: 17782
Reputation: 68024
A simple dictionary might be a cleaner option. For example
shell> cat playbook.yml
- name: Install external DB for Cloudera Manager Server
hosts: db_server
vars:
my_roles:
postgresql: postgresql
mysql: mariadb
oracle: oracledb
tasks:
- include_role:
name: "{{ my_roles[databases_type] }}"
Example
Let's create the roles
shell> cat roles/postgresql/tasks/main.yml
- debug:
var: role_name
shell> cat roles/mariadb/tasks/main.yml
- debug:
var: role_name
shell> cat roles/oracledb/tasks/main.yml
- debug:
var: role_name
Next, let's create an inventory with three servers, group_vars with default databases_type and host_vars with the variables for two hosts test_01 and test_02. The third host test_03 will use the variables from group_vars.
shell> cat hosts
[db_server]
test_01
test_02
test_03
shell> cat group_vars/db_server
databases_type: mysql
shell> cat host_vars/test_01
databases_type: postgresql
shell> cat host_vars/test_02
databases_type: oracle
Then the playbook gives (abridged)
shell> ansible-playbook -i hosts playbook.yml
PLAY [Install external DB for Cloudera Manager Server] *****************
TASK [include_role : {{ my_roles[databases_type] }}] *******************
TASK [postgresql : debug] **********************************************
ok: [test_01] =>
role_name: postgresql
TASK [oracledb : debug] ************************************************
ok: [test_02] =>
role_name: oracledb
TASK [mariadb : debug] *************************************************
ok: [test_03] =>
role_name: mariadb
Upvotes: 2
Reputation: 979
I believe that this is what you are looking for. In the below example, fruit is the variable name. If fruit is equal to Apple then I like it else I do not like it. Let me know if you face any issue or you need more explanation on this.
If else syntax:
- name: "[ If Else Example ]"
command: "echo {{ 'I like it' if fruit == 'Apple' else 'I do not like it'}}"
register: if_reg
- debug:
msg: "{{ if_reg.stdout }}"
Upvotes: 2
Reputation: 2848
It seems you have double curly bracket:
- {{% if ...
Try removing it to make single curly bracket:
e.g.
- {% if ...
also last line could remove ending curly bracket and put endif:
{% if (databases_type == "oracle") %} role: oracledb {% endif %}
Upvotes: 0