I don't believe roles
is the best way to approach the problem because you can't register variables before a role statement gets evaluated. From the documentation you can only use ansible facts
that actually get evaluated before your playbook executes. Another comment, the when
keyword is meant to be used only once in the role
statement:
---
- name: Install MySQL
host: development
roles:
- {role: mysql,
mysql_db: [{name: benz}],
mysql_users: [{name: ben3, pass: foobar, priv: "*.*:ALL"}],
when: "some_ansible_fact == 'Whatever'"}
You are probably better off putting your checks in playbook tasks if you need to check whether a mysql database exists or not. you can use the register
keyword to see if a database exists:
---
- name: Install Mysql
hosts: all
user: myrootuser
sudo: True
tags: mytag
vars:
mysql_users: [{name: ben3, pass: foobar, priv: "*.*:ALL"}]
mysql_db: mydatabasename
tasks:
- name: Install the mysql package
apt: pkg=mysql-server state=present
- name: Find out the master log file name and position
command: >
/usr/bin/mysql -umysql_user -pmysql_password
-e "SHOW DATABASES;"
register: databases
- name: Create users if they don't exist
command: >
# or run whatever you need to run here to create users
/usr/bin/mysql -umysql_user -pmysql_password
-e "CREATE USER {{ mysql_users[0]['name'] }};"
when: databases.stdout.find('{{ mysql_db }}') != -1
Hope this helps.