7wick
7wick

Reputation: 421

How to use when condition in ansible yaml file?

I want something like:

if env == 'dev'

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

else if env == 'prod'

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

How to do that?

Upvotes: 0

Views: 263

Answers (2)

Istvan Szekeres
Istvan Szekeres

Reputation: 189

I prefer not to put these kind of decisions into the template itself, I would use something like this in the config:

user_by_env:
  dev: root
  prod: centos

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

Then in the template:

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

This also loudly fails in case the env is not dev/prod instead of silently producing an incorrect file.

Upvotes: 2

flyx
flyx

Reputation: 39778

Ansible uses the Jinja2 templating engine, which lets you do:

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

Upvotes: 2

Related Questions