Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What if a remote environment variable doesn't exist? Ansible take this as an fatal error. How to avoid that?

Tags:

ansible

I want to do some check using remote environment variables, which can be read from format like this

{{ ansible_env.NGINX_HOME }}

This "path" or environment variable can be absent, and that's the purpose of that check anyway.

But Ansible treat this as a fatal error, showing error message like

One or more undefined variables: 'dict object' has no attribute 'NGINX_HOME'

What can I do to just skip this?

like image 803
Zhenkai Avatar asked Sep 18 '14 09:09

Zhenkai


People also ask

How do you pass an environment variable in Ansible?

Ansible Environment variables are used to set the environment variable for action on the remote host using environment keyword, which can be set at the playbook level or the task level and which doesn't affect the ansible configuration file or the environment set for the user and it doesn't include automatically to the ...

How can I set the path or any other environment variable for a task or entire playbook?

How can I set the PATH or any other environment variable for a task or entire play?  Setting environment variables can be done with the environment keyword. It can be used at the task or other levels in the play.

What plug in should be used in Ansible to get access to environment variables?

You can access the environment variables on the local server using the lookup plugin. It lets you access the system data and environment variables.

How do I keep secret data on my playbook Ansible?

How do I keep secret data in my playbook? ¶ If you would like to keep secret data in your Ansible content and still share it publicly or keep things in source control, see Vault. This can be used to keep verbose output but hide sensitive information from others who would otherwise like to be able to see the output.


2 Answers

Using a Jinja filter you can specify a default value if the variable is undefined:

{{ ansible_env.NGINX_HOME|default('') }}

This will default the value to an empty string if it doesn't exist.

Another options is if you are using that var in a task you can conditionally run the task only if that var is defined:

- shell: echo {{ ansible_env.NGINX_HOME}}
  when: "'NGINX_HOME' in ansible_env"
like image 175
jarv Avatar answered Oct 24 '22 00:10

jarv


You can also set all variables as not mandatory in ansible.cfg.

And set variables as mandatory case by case with {{var | mandatory }}

http://docs.ansible.com/ansible/playbooks_filters.html#forcing-variables-to-be-defined

like image 22
ant31 Avatar answered Oct 24 '22 01:10

ant31