skip to Main Content

I want something like:

if env == ‘dev’

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

else if env == ‘prod’

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

How to do that?

2

Answers


  1. 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 %}
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search