hoan
hoan

Reputation: 1396

Ansible optional variable in configuration file

In the configuration file of the service I want to configure, I have an optional parameter which can be completely omitted. The templating language for my configuration file is Jinja2.

What I want is to be able to define a variable in my Ansible vars.yml file:

optional_service_parameter: "value"

Whenever the variable is defined in vars.yml I want to use it in the service configuration:

config:
  parameter1: {{ parameter_var_1 }} 
  parameter2: {{ parameter_var_2 }}
  optional_parameter: {{ optional_service_parameter }}

When the variable optional_service_parameter is not set in vars.yml, the optional_service_parameter should be omitted in my service configuration file. What is the best way to achieve this?

Upvotes: 1

Views: 563

Answers (1)

Sriram
Sriram

Reputation: 674

You can try using when condition with lookup of variable. Below is the example. I have used set_facts with when condition to keep it simple. If the variable is found then it will print the message else it will not print. Hope this helps.

- hosts: all
  gather_facts: no
  tasks:
    - name: testing
      debug:
        msg: "{{ optional_service_parameter }}"
      when: lookup('vars', 'optional_service_parameter', errors='ignore', default=false)

Upvotes: 1

Related Questions