Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To create Ansible variable from string

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 }} }}"
}
like image 930
yaniv refael Avatar asked Dec 04 '16 06:12

yaniv refael


1 Answers

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

like image 159
Konstantin Suvorov Avatar answered Sep 28 '22 03:09

Konstantin Suvorov