Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

jinja2 - How to format strings with jinja/ansible?

Friends,

I am learning Ansible here and trying to apply what I am learning to one of my simple projects. I got stuck trying to format some strings. I getting the following error:

fatal: [localhost]: FAILED! => {"changed": false, "msg": 
"AnsibleError: template error while templating string: 
**unexpected ']', expected ')'**. 

String: 

cluster_name = "{{ terraform['%s' | format(env)].cluster_name }}"

credentials = "{{ terraform['%s' | format(env)].credentials }}"

initial_node_count = "{{ terraform['%s' | format(env]].initial_node_count }}
format(env)].project }}""}
    ...

This is how my jinja2 file looks like:

cluster_name = "{{ terraform['%s' | format(env)].cluster_name }}"
credentials = "{{ terraform['%s' | format(env)].credentials }}"
initial_node_count = "{{ terraform['%s' | format(env]].initial_node_count }}"
...

I want to generate strings like this terraform['testing'].credentials when I run ansible-playbook site.yaml -e env=testingand write them to a file. I can't figure out another way to get this done. Any Idea?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

you want to use this syntax:

cluster_name = "{{ terraform[env].cluster_name }}"

With terraform.env, ansible will get the env key of the terraform env, but with terraform[env] , ansible will resolve env to 'testing' and get the 'testing' key of the terraform var.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...