Joel
Joel

Reputation: 689

How to access an ansible block variable in a file from the same block

I define a yml variable files for ansible with the following structure:

appserver:
   root_directory: C:\app
   config_directory: '{{ root_directory }}\config'

it seems the second variable config_directory cannot be interpreted correctly, I get a VARIABLE NOT FOUND ERROR.

I tried with:

appserver:
   root_directory: C:\app
   config_directory: '{{ appserver.root_directory }}\config'

It does not work either, I have a very long trace of error, the most interesting part is :

recursive loop detected in template string:{{ appserver.root_directory }}\config

When I use double quotes instead of simple quotes,

appserver: root_directory: C:\app config_directory: "{{ appserver.root_directory }}\config"

I get the following error:

 The offending line appears to be:

 app_root: D:\WynsureEnvironments\Application
 wynsure_root: "{{ appserver.root_directory }}\config"
                                              ^ here
 We could be wrong, but this one looks like it might be an issue with
 missing quotes.  Always quote template expression brackets when they
 start a value. For instance:

with_items:
  - {{ foo }}

Should be written as:

with_items:
  - "{{ foo }}"

When using variable blocks, how can I reuse variables to assign new variables?

Thanks!

Upvotes: 0

Views: 1247

Answers (1)

Zeitounator
Zeitounator

Reputation: 44615

You cannot use such a recursive jinja2 variable declaration in ansible.

Here are 2 (non exhaustive list) alternative solutions:

  1. Don't use a hash. Prepend your vars names. You will typically find this type of naming conventions in e.g. reusable roles on ansible galaxy
appserver_root_directory: C:\app
appserver_config_directory: '{{ appserver_root_directory }}\config'
  1. If you really need a hash of this kind, declare a "private" variable outside of your hash and reuse it inside.
_appserver_root: C:\app
appserver:
  root_directory: "{{ _appserver_root }}"
  config_directory: "{{ _appserver_root }}\config"

Upvotes: 3

Related Questions