jinja2 ansible-访问复杂变量 [英] jinja2 ansible - accessing complex var
问题描述
我已经花了几个小时试图给一个.pgpass
文件模板化,因为它的结构相当复杂.我认为我需要一个嵌套的"for"循环来访问所需的内容,但是我不确定如何正确地向下钻取.
I've spent hours trying to template a .pgpass
file given a fairly complex variable structure. I think I need a nested "for" loop to access what I need, but I'm not sure how to drill down properly.
这是var:
clients:
- client1:
postgres_users:
- name: user1
pass: mypassword1
- name: user3
pass: mypassword2
postgres_user_priv_ssh_key: |
a
multiline
var
postgres_user_pub_ssh_key: "ssh-rsa blahblahblah"
- client2:
postgres_users:
- name: user3
pass: mypassword3
- name: user4
pass: mypassword4
postgres_user_priv_ssh_key: |
a.n.other
multiline
var
postgres_user_pub_ssh_key: "ssh-rsa blahblahblahdeblah"
.pgpass
文件的格式为:
hostname:port:database:username:password
因此,对于客户"下的每个客户",我需要遍历并渲染每个客户的name
和pass
.我已经尝试了jinja2模板的如此多次迭代,可能不值得一试,因为它们都不起作用:)我愿意以某种方式重组数据,但是我觉得这是一种相当不错的方法对其进行结构化,因为可能需要多台机器将其读取以用于其他目的(一对多?)
So, for each "client" under "clients", I need to iterate through and render the name
and pass
of each one. I've tried so many iterations of the jinja2 template, that it's probably not worth putting any down here, as none of them worked :) I'm open to restructuring the data in some way, but I feel that that's a fairly good way to structure it, as it may need to be read by multiple machines for other purposes (one to many?)
任何建议表示赞赏!
推荐答案
这是一本剧本/模板.请注意在变量结构中所做的一些更改.更具体地说,clients
不再是列表变量.还为db_name
和db_port
添加了2个变量:
here is a playbook/template. please note some changes done in the variable structure. More specifically, the clients
is not a list variable anymore. added 2 more variables for db_name
and db_port
as well:
---
- name: test play
hosts: localhost
connection: local
gather_facts: false
become: yes
vars:
db_port: 5432
db_name: "*"
clients:
client1:
postgres_users:
- name: user1
pass: mypassword1
- name: user3
pass: mypassword2
postgres_user_priv_ssh_key: |
a
multiline
var
postgres_user_pub_ssh_key: "ssh-rsa blahblahblah"
client2:
postgres_users:
- name: user3
pass: mypassword3
- name: user4
pass: mypassword4
postgres_user_priv_ssh_key: |
a.n.other
multiline
var
postgres_user_pub_ssh_key: "ssh-rsa blahblahblahdeblah"
tasks:
- name: run the template
template:
src: templates/testt.j2
dest: /tmp/testt.txt
jinja模板:
{% for db_client in lookup('dict', clients) %}
{% for user in clients[db_client.key].postgres_users %}
{{ db_client.key }}:{{ db_port }}:{{ db_name }}:{{ user.name }}:{{ user.pass }}
{% endfor %}
{% endfor %}
结果:
[root@optima-ansible ILIAS]# cat /tmp/testt.txt
client1:5432:*:user1:mypassword1
client1:5432:*:user3:mypassword2
client2:5432:*:user3:mypassword3
client2:5432:*:user4:mypassword4
[root@optima-ansible ILIAS]#
希望有帮助
这篇关于jinja2 ansible-访问复杂变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!