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

查看:26
本文介绍了如何从字符串创建 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] }}

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

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

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

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