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.
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