Ansible 重复角色

Sve*_*ven 7 ansible

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

- 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' }
Run Code Online (Sandbox Code Playgroud)

这很有效,但它很难看,因为我必须重复两次。当从默认值更改某些参数时,这尤其容易出错(例如本例中 vhost host1.com 上的 db)。

有没有办法写这个,这样我就可以有一个包含所有必需参数的虚拟主机列表,并为每个虚拟主机条目自动将不同的角色添加到不同的主机组?

Dro*_*096 8

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

- layouts:
  - layout1:
      vhost: host1.com
      db: customdb
  - layout2:
      vhost: other.com
Run Code Online (Sandbox Code Playgroud)

然后使用它们传递给角色:

- 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 }
Run Code Online (Sandbox Code Playgroud)

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


Ant*_*des 5

我所做的是创建角色apache,它安装 apache 并为所有虚拟主机做一些配置apache-vhost,安装虚拟主机host1-com,和other-com. 那么剧本会是这样的:

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

- hosts: other-com-servers
  roles:
    - apache
    - other-com
Run Code Online (Sandbox Code Playgroud)

现在,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
Run Code Online (Sandbox Code Playgroud)

(这是一个实现细节,但该apache-vhost角色根据传递给它的变量准备了一些基本的 vhost 配置,并且还在extrasvhost 配置中添加了变量。)

同样,对于数据库,您可以拥有一个postgresql角色、一个postgresql-database角色等等。


小智 4

您可以按角色对主机进行分组,而不是按功能对主机进行分组,并且仅当在该角色的指定组中找到该主机时,才让 Ansible 在主机上运行给定的角色。

[role_db_customdb]
other.com

[role_db_otherdb]
host1.com

[role_website]
host1.com
other.com
Run Code Online (Sandbox Code Playgroud)

您甚至可以将参数传递给角色,如db下面的 playbook 中的参数所示。

---
- 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 }
Run Code Online (Sandbox Code Playgroud)