6

假设我有一个剧本,其中包含一些用于安装应用服务器的角色,并且我喜欢在生产服务器和测试服务器上应用相同的剧本。

生产服务器和测试服务器都有相同的角色列表,除了一个,它只应该应用于生产服务器。

是否可以以某种方式指定此角色仅适用于使用相同剧本的生产服务器?

例如,如果剧本是:

---
- hosts: appserver
  roles:
    - { role: mail, tags: ["mail"] }
    - { role: firewall, tags: ["firewall"] }
    - { role: webserver, tags: ["webserver"] }
    - { role: cache, tags: ["cache"] }

我有两个库存:一个用于生产,一个用于测试。

当我使用测试清单运行剧本时,我不希望执行“防火墙”角色。

我的想法是做一些事情,比如在“生产”库存中设置一个变量,并使用类似“如果设置了 <var>,然后执行角色“防火墙” ”......我不知道这是否可能,如果它是,怎么办?

4

3 回答 3

10

production_environment您可以在清单文件中定义变量,例如,在剧本中分配truefalse赋值并使用条件:when

---
- hosts: appserver
  roles:
    - { role: mail, tags: ["mail"] }
    - { role: firewall, tags: ["firewall"], when: production_environment }
    - { role: webserver, tags: ["webserver"] }
    - { role: cache, tags: ["cache"] }

或者您可以inventory_file直接访问变量。例如,如果您使用-i production

---
- hosts: appserver
  roles:
    - { role: mail, tags: ["mail"] }
    - { role: firewall, tags: ["firewall"], when: inventory_file == "production" }
    - { role: webserver, tags: ["webserver"] }
    - { role: cache, tags: ["cache"] }

你走哪条路是一个行政决定。第二种方法使用较少的步骤,但需要在 playbook 中“硬编码”库存文件名。

于 2016-10-13T01:30:21.147 回答
7

为什么不直接使用库存组?制作两个库存:

测试:

[application]
my-dev-server

生产:

[application]
company-prod-server

[firewall]
company-prod-server

并按如下方式更改您的剧本:

---
- hosts: firewall
  roles:
    - { role: firewall, tags: ["firewall"] }

- hosts: application
  roles:
    - { role: mail, tags: ["mail"] }
    - { role: webserver, tags: ["webserver"] }
    - { role: cache, tags: ["cache"] }
于 2016-10-13T07:02:18.310 回答
3
- { role: firewall, tags: ["firewall"], when: MyVar }

请参阅将“何时”应用于角色和包含

于 2016-10-13T01:25:08.203 回答