在ansible中访问嵌套变量 [英] accessing nested variable variables in ansible

查看:41
本文介绍了在ansible中访问嵌套变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的 group_vars/all 文件:

Here is my group_vars/all file:

app_env: staging

staging:
  app_a:
    db_host: localhost
  app_b:
    db_host: localhost
production:
  app_a:
    db_host: app_a-db.example.net
  app_b:
    db_host: app_b-db.example.com

如果 app_env 环境必须是生产环境,我会通过库存变量覆盖它.这样,除非您明确将它们设置为生产环境,否则所有部署都将处于暂存阶段.

If app_env environment has to be production, I overwrite this via inventory variables. This way, all deployments are staging unless you make them production explicitly.

所以,当我想在剧本中打印变量时,我可以这样做

So, when I want to print the variable in a playbook, I can do

---
  - debug: var={{app_env}}.app_a.db_host

这有效!

但是如何访问另一个模块中的变量,即 lineinfile?

But how can I access the Variable in another module, i.e. lineinfile?

一些没有成功的例子:

- lineinfile: dest=/etc/profile line='export APP_A_DB_HOST="{{ app_env.app_a.db_host }}"'
- lineinfile: dest=/etc/profile line='export APP_A_DB_HOST="{{ app_env[app_a][db_host] }}"'
- lineinfile: dest=/etc/profile line='export APP_A_DB_HOST="{{ {{app_env}}.app_a.db_host }}"'

可行的解决方案是使用 set_fact 模块(双行代码,不是很聪明)或包含不同的变量文件,具体取决于 app_env.

Working solutions would be using the set_fact module (double lines of code, not really smart) or including different variable files, depending on app_env.

但我真的很想知道是否有访问嵌套变量变量的符号;)

But I really would like to know if theres a notation to access nested variable variables ;)

推荐答案

如果你的环境字典"不在根目录,你会让你的生活更轻松,就像这样:

You would make your life easier with your 'environment dict' not being at the root, like so:

app_env: staging

app_environments:
  staging:
    app_a:
      db_host: localhost
    app_b:
      db_host: localhost
  production:
    app_a:
      db_host: app_a-db.example.net
    app_b:
      db_host: app_b-db.example.com

然后,您应该可以使用 {{app_environments[app_env].app_a.db_host}}{{app_environments[app_env]['app_a']['db_host']}} 无处不在(Jinja 模板、任务).

Then, you should be able to use {{app_environments[app_env].app_a.db_host}} or {{app_environments[app_env]['app_a']['db_host']}} everywhere (Jinja templates, tasks).

不过要注意太多的嵌套"!

Watch out for too much "nestiness" though !

这篇关于在ansible中访问嵌套变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆