Ansible Yaml文件中有条件时如何使用?

时间:2019-12-18 09:33:47

标签: ansible yaml

我想要类似的东西

如果env =='dev'

  - hosts: "{{host}}"
    user: root

否则,如果env =='prod'

 - hosts: "{{host}}"
   user: centos

该怎么做?

2 个答案:

答案 0 :(得分:2)

Ansible使用Jinja2模板引擎,您可以这样做:

{% if env == 'dev' %}
- hosts: "{{host}}"
  user: root
{% elif env == 'prod' %}
- hosts: "{{host}}"
  user: centos
{% endif %}

答案 1 :(得分:2)

我不想将这些决定放到模板本身中,我会在配置中使用类似这样的东西:

An error occurred while listing cloudwatch-logs relations: 2 validation errors detected: Value '' at 'logGroupName' failed to satisfy constraint: Member must satisfy regular expression pattern: [\.\-_/#A-Za-z0-9]+; Value '' at 'logGroupName' failed to satisfy constraint: Member must have length greater than or equal to 1 (Service: AWSLogs; Status Code: 400; Error Code: InvalidParameterException; Request ID: 4d7fdfbc-4ad0-47ec-875f-b172e45c714b)

然后在模板中:

user_by_env:
  dev: root
  prod: centos

user: "{{ user_by_env[env] }}"

如果环境不是dev / prod而不是静默生成不正确的文件,这也会大声失败。