Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible: check if variable equals string

I have an ansible variable passed in on the command line as such:

ansible-playbook -e environment=staging ansible/make_server.yml

I want to load in some variables in my role dependeing on the value of environment. I have tried a lot of different methods such as:

- include_vars: staging_vars.yml
  when: environment | staging

and

- include_vars: staging_vars.yml
  when: "{{environment}} == "staging"

and

- include_vars: staging_vars.yml
  when: "{{environment}} | match('staging')"

but nothing seems to work. How do I do this?

Details:

  • I am using ansible 1.7.2
like image 717
Jordan Ell Avatar asked Dec 06 '14 18:12

Jordan Ell


People also ask

When condition with variable in Ansible?

Example #4 This example will check if the mentioned directory exists on the windows server using the registered variable output. If the variable has value, then it is considered as succeeded, and if the task fails, then the variable doesn't hold the value, so we will use “is failed” in the when condition.

How do you write an if else condition in Ansible?

Traditional programming language usually uses the if-else statement when more than one outcome is expected. In Ansible, 'when' statement is used instead to determine the outcome of a variable. So instead of using the if-else statement, you define what you want to happen.

What does Set_fact do in Ansible?

This module allows setting new variables. Variables are set on a host-by-host basis just like facts discovered by the setup module. These variables will be available to subsequent plays during an ansible-playbook run.

When Ansible variable is defined?

As per latest Ansible Version 2.5, to check if a variable is defined and depending upon this if you want to run any task, use undefined keyword. tasks: - shell: echo "I've got '{{ foo }}' and am not afraid to use it!" when: foo is defined - fail: msg="Bailing out. this play requires 'bar'" when: bar is undefined.


1 Answers

Be careful with a variable called environment, it can cause problems because Ansible uses it internally. I can't remember if it's in the docs, but here's a mailing list thread:

https://groups.google.com/forum/#!topic/ansible-project/fP0hX2Za4I0

We use a variable called stage.

It looks like you'll end up with a bunch of these in a row:

- include_vars: testing_vars.yml
  when: stage == "testing"
- include_vars: staging_vars.yml
  when: stage == "staging"
- include_vars: production_vars.yml
  when: stage == "production"

But you could also just include your environment:

- include_vars: "{{ stage }}_vars.yml"

Or, use the vars_files on a playbook level:

vars_files:
  - vars/{{ stage }}_vars.yml
like image 178
Ramon de la Fuente Avatar answered Oct 27 '22 02:10

Ramon de la Fuente