【问题标题】:Variable interpolation with ansible filters and environment variables使用 ansible 过滤器和环境变量进行变量插值
【发布时间】:2016-08-20 05:47:05
【问题描述】:

我有一个引导用户 OSX 工作站的角色。在其中,我需要确保正确设置 xdg 变量,使用以下优先级:

  • defaults/main.yml
  • 用户的环境变量
  • 任何其他值(在 vars、host_vars、命令行等中设置)

我尝试了几种不同的方法,但我遇到的基本问题是我无法嵌套变量插值,所以在 defaults/main. yml 失败:

# 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'))) }}"

我尝试的下一种方法是使用第一种方法设置默认值(如果为空则为空字符串),然后检查并在角色/myrole/tasks/main.yml 中设置默认值:

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

但我也无法让它发挥作用。有什么建议或意见吗?

【问题讨论】:

    标签: filter ansible jinja2


    【解决方案1】:

    在 jinja 文档中找到答案 - 使用 jinja 字符串连接运算符 (~):

    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) }}"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-23
      • 2018-11-18
      • 2015-10-24
      相关资源
      最近更新 更多