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

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

问题描述

这是我的group_vars/所有文件:

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

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

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天全站免登陆