如何从字符串创建Ansible变量 [英] How To create Ansible variable from string

查看:126
本文介绍了如何从字符串创建Ansible变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

我有要使用的变量{{ami_redhat_7_2}}

I Have Variable {{ ami_redhat_7_2 }} That I want to use

vars:
  OsType: redhat
  OsVersion: '7_2'

tasks:
- debug: 'msg="{{ ami_{{OsType}}_{{ OsVersion }} }}"'

我收到错误消息:

fatal: [localhost]: FAILED! => {
    "failed": true,
    "msg": "template error while templating string: expected token 'end of print statement', got '{'. String: {{ ami_{{ OsType }}_{{ OsVersion }} }}"
}

推荐答案

带有动态名称的'root'变量在Ansible中是一件棘手的事情.
如果它们是主机事实,则可以按以下方式访问它们:

'root' variables with dynamic names is a tricky thing in Ansible.
If they are host facts, you can access them like this:

{{ hostvars[inventory_hostname]['ami_'+OsType+'_'+OsVersion] }}

如果它们是与游戏相关的变量,则可以通过未记录的vars对象访问它们:

If they are play-bound variables, you can access them via undocumented vars object:

{{ vars['ami_'+OsType+'_'+OsVersion] }}

但是它们永远不会被模板化,因为vars被以特殊方式对待.

But they will never get templated, because vars is treated in a special way.

最简单的方法是使用具有预定义名称和动态键名称的字典,例如:

The easiest way for you is some dict with predefined name and dynamic key names, like:

ami:
   redhat_7_2: 827987234/dfhksdj/234ou234/ami.id

要访问它,您可以使用:

And to access it, you can use:

{{ ami[OsType+'_'+OsVersion] }}

P.S.并按照其他答案中的建议删除msg周围的引号.

P.S. and remove quotes around msg as suggested in other answer.

这篇关于如何从字符串创建Ansible变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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