How To create Ansible variable from string

江枫思渺然 提交于 2019-11-30 07:38:45

问题


For Example:

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

vars:
  OsType: redhat
  OsVersion: '7_2'

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

I got Error:

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

回答1:


'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] }}

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

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

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. and remove quotes around msg as suggested in other answer.



来源:https://stackoverflow.com/questions/40956212/how-to-create-ansible-variable-from-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!