简体   繁体   English

在Jinja2中重写群组模板

[英]rewrite a group template in Jinja2 and ansible

I have a few templates where I need to decorate some server names and I'd like to do this in one line so that I can use the string as a variable. 我有一些模板,需要在其中装饰一些服务器名称,并且我想在一行中完成此操作,以便可以将字符串用作变量。

{{ group_vars["dbservers"] | WHAT GOES HERE | list }}

that will take a list like 这将需要一个清单

[dbservers]
db-1
db-2
db-3

and then in the template I need them like this: 然后在模板中,我需要这样:

{
  servers: [
    "http://db-1:1234", 
    "http://db-2:1234", 
    "http://db-3:1234"
  ] ....
}

As of now I am doing something like this: 截至目前,我正在执行以下操作:

servers: [
{% for h in groups["dbservers"] %}
"http://{{hostvars[h].ansible_fqdn}}:{{ mymagicport}}"
{% if not loop.last %},{% endfor %}
{% endfor %}
]

which I don't love at all. 我一点都不爱。 I'd like to be able to store this in a usable way and then just call config.to_nice_json 我希望能够以一种可用的方式存储它,然后只需调用config.to_nice_json

But I can't seem to find the right recipe to inline the value. 但是我似乎找不到合适的方法来内联价值。 I have been messing around with the map function but to no avail. 我一直在搞乱map功能,但无济于事。 Any ideas? 有任何想法吗?

It is doable with map and regex_replace : 它可以通过mapregex_replace

hosts : 主持人

[db-servers]
db-1 fqdn_fact=db-server-1
db-2 fqdn_fact=db-srv-2
db-3 fqdn_fact=server-3

playbook : 剧本

---
- hosts: localhost
  gather_facts: no
  vars:
    mymagicport: '1234'
  tasks:
    - debug:
        msg: "{{ groups['db-servers'] | map('regex_replace','(.*)','http://\\1:'+mymagicport) | list }}"
    - debug:
        msg: "{{ groups['db-servers'] | map('extract',hostvars,'fqdn_fact') | map('regex_replace','(.*)','http://\\1:'+mymagicport) | list }}"

First task – to work with inventory hostnames, second task – to work with arbitrary fact from hostvars . 第一项任务-使用清单主机名,第二项任务-使用hostvars任意事实。

result: 结果:

TASK [debug] *******************************************************************
ok: [localhost] => {
    "msg": [
        "http://db-1:1234",
        "http://db-2:1234",
        "http://db-3:1234"
    ]
}

TASK [debug] *******************************************************************
ok: [localhost] => {
    "msg": [
        "http://db-server-1:1234",
        "http://db-srv-2:1234",
        "http://server-3:1234"
    ]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM