Ansible重复angular色

我使用Ansible来pipe理一些运行多个虚拟主机的网站和数据库服务器。 对于每个网站,我需要将数据库angular色分配给dbservers组,将网站angular色分配给Web服务器组。 所以我的剧本看起来像这样:

- hosts: dbservers roles: - { role: database, vhost: 'host1.com', db: 'customdb' } - { role: database, vhost: 'other.com' } - hosts: webservers roles: - { role: website, vhost: 'host1.com', db: 'customdb' } - { role: website, vhost: 'other.com' } 

这个效果很好,但是因为我不得不两次重复一切,所以这很糟糕。 从默认值(如本例中的vhost host1.com上的db)更改某些参数时,这是特别容易出错的。

有没有办法写这个,所以我可以有一个具有所有必要参数的虚拟主机列表,并自动将不同的angular色添加到每个虚拟主机条目的不同主机组?

最明显的答案 – 使用复杂的variables(字典)来保存你的值,然后传递整个variables:

 - layouts: - layout1: vhost: host1.com db: customdb - layout2: vhost: other.com 

然后使用这些传递给angular色:

 - hosts: dbservers roles: - { role: database, layout: layouts.layout1 } - { role: database, layout: layouts.layout2 } - hosts: webservers roles: - { role: webserver, layout: layouts.layout1 } - { role: webserver, layout: layouts.layout2 } 

过去我成功地做到了这一点。 要填充布局,您可以使用各种技术:将“group_vars / all”与“vars_files”结合使用“host_vars”等

我所做的是创buildangular色apache ,它安装了apache,并为所有vhosts, apache-vhost ,安装了一个vhost, host1-comother-com做了一些configuration。 那么剧本会是这样的:

 - hosts: host1-com-servers roles: - apache - host1-com - hosts: other-com-servers roles: - apache - other-com 

现在, host1-com将有这样的:

 - meta: - dependencies: - role: apache-vhost server_name: host1.com server_aliases: - www.host1.com extras: | Alias /static /var/local/myapp/static <Location /static> Require all granted </Location> # Whatever else you want whatever_other_variables_apache-vhost_needs: XXX 

(这是一个实现细节,但是apache-vhostangular色根据传递给它的variables准备了一些必要的vhostconfiguration,并且还在vhostconfiguration中添加了extrasvariables。)

同样,对于数据库,您可以具有postgresqlangular色, postgresql-databaseangular色等。

您可以按照angular色对主机进行分组,而不必按angular色对主机进行分组,只有在该主机在该angular色的指定组中find该主机,Ansible才能在主机上运行给定angular色。

 [role_db_customdb] other.com [role_db_otherdb] host1.com [role_website] host1.com other.com 

您甚至可以将parameter passing给angular色,如下面的剧本中的db参数所示。

 --- - hosts: all roles: - { role: database, db: 'customdb', when: inventory_hostname in groups.role_db_customdb } - { role: database, db: 'otherdb', when: inventory_hostname in groups.role_db_otherdb } - { role: website, when: inventory_hostname in groups.role_webservers }