How To create Ansible variable from string

后端 未结 1 1327
抹茶落季
抹茶落季 2020-12-17 03:08

For Example:

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

vars:
  OsType: redhat
  OsVersion: \'7_2\'

tasks:
- debug: \'msg=\"{{ ami_{{Os         


        
相关标签:
1条回答
  • 2020-12-17 03:34

    '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.

    0 讨论(0)
提交回复
热议问题