0
votes

I've got a role that bootstraps a user's OSX workstation. In it, I need to ensure that xdg variables are set properly, using the following precedence:

  • defaults/main.yml
  • user's environment variable
  • any other value (set in vars, host_vars, command line, etc)

I've tried a couple different approaches, but the basic problem I'm having is that I can't nest variable interpolation, so approach one (and all the others I could think of to try) in defaults/main.yml have failed:

# if the env var doesn't exist, it'll set it to an empty string, doesn't look
# like there is a way to specify the 'default' string that should be used
# xdg_cache_home: "{{ lookup('env','XDG_CACHE_HOME') }}"

# this is just bad syntax, can't have nested '{{ }}'
# xdg_config_home: "{{ lookup('env','XDG_CACHE_HOME') | default("{{ home }}/.cache", true) }}"

# this simply fails to define the variable, i'm not sure why
# xdg_cache_home: "{{ default( lookup('env','XDG_CACHE_HOME'), join(lookup('env', 'HOME', '.cache'))) }}"

The next approach I tried was to just set the defaults using the first method (empty string if empty) and then inspect and set a default value in the roles/myrole/tasks/main.yml:

- name: set default xdg_cache_home
  set_fact: xdg_cache_home="{{ join(lookup('env', 'HOME', '/.cache')) }}"
  when: "{{ xdg_cache_home }}" == ""

But I can't get that to work either. Any suggestions or advice?

1

1 Answers

2
votes

Found the answer in the jinja documentation - using the jinja string concatenation operator (~):

xdg_cache_home: "{{ lookup('env', 'XDG_CACHE_HOME') | default(ansible_user_dir ~ '/.cache', true) }}"
xdg_config_home: "{{ lookup('env', 'XDG_CONFIG_HOME') | default(ansible_user_dir ~ '/.config', true) }}"
xdg_data_home: "{{ lookup('env', 'XDG_DATA_HOME') | default(ansible_user_dir ~ '/.local/share', true) }}"