所以我试图理解如何在剧本中传递角色变量,我偶然发现了语法。我不知道怎么告诉ansible只创建一个mysql数据库,如果它不存在。它特意将它作为角色变量传递给我发现具有挑战性。可以通过state = present吗?
这是我的代码:
---
- name: Install MySQL
host: development
roles:
- {role: mysql, mysql_db: [{name: benz}], when: ????,
mysql_users: [{name: ben3, pass: foobar, priv: "*.*:ALL"}], when: ???}
答案 0 :(得分:1)
我不相信roles
是解决问题的最佳方法,因为在评估角色语句之前无法注册变量。从文档中,您只能使用在执行Playbook之前实际获得评估的ansible facts
。另一条评论,when
关键字只能在role
语句中使用一次:
---
- 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'"}
如果您需要检查是否存在mysql数据库,那么最好将检查放在playbook任务中。您可以使用register
关键字查看数据库是否存在:
---
- 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
希望这有帮助。