Ansible / Jinja2如何将列表格式化为我的配置文件的字段?

时间:2017-12-14 17:50:09

标签: ansible jinja2 ansible-template

我有以下内容并牢记我不知道这个传入变量中有多少个ips,但为了简单起见,我从2开始。

dataset = structure(list(quantity = c("(100) x 10mg zepose valium ..(cipla in strips)", 
"-- 20x2mg -- diclazepam", "(10) clonazepam 2mg / roche rivotril"
)), class = "data.frame", row.names = c(NA, -3L), .Names = "quantity")

我尝试使用带Ansible的模板在文件中格式化它们。

vars:
  host_ips: ['10.0.0.100', '10.0.0.200']

我使用Jinja2中的哪种语法使主机ips看起来像上面的目标行?我知道我必须进行迭代。

3 个答案:

答案 0 :(得分:1)

source

答案 1 :(得分:0)

-targets: [{% for ip in host_ips %}'{{ ip }}:5051',{% endfor %}]

test.yml playbook:

vars:
  host_ips: ['10.0.0.100', '10.0.0.200','10.0.0.300']
tasks:
  - debug: msg=[{% for ip in host_ips %}'{{ ip }}:5051',{% endfor %}]

ansible-playbook -i localhost test.yml

TASK [debug] *******************************************************************************************
ok: [localhost] => {
    "msg": [
        "10.0.0.100:5051", 
        "10.0.0.200:5051", 
        "10.0.0.300:5051"
    ]
}

答案 2 :(得分:0)

这里没有必要与Jinja2循环斗争。您只需为列表元素应用转换(例如使用mapregex_replace过滤器):

host_ips | map('regex_replace', '(.*)', '\\1:9090')

使用上述结构,您可以:

  • 用它在Ansible中设置一个新变量:

    - set_fact:
        targets: "{{ host_ips | map('regex_replace', '(.*)', '\\1:9090') | list }}"
    

或" 使用模板将文件格式化为"根据您的请求,它是列表的JSON表示:

  • 输出中带双引号:

    - targets: {{ host_ips | map('regex_replace', '(.*)', '\\1:9090') | list | to_json }}
    

    procudes:

    - targets: ["10.0.0.100:9090", "10.0.0.200:9090"]
    
  • 如果您确实需要输出中的单引号,只需替换它们:

    - targets: {{ host_ips | map('regex_replace', '(.*)', '\\1:9090') | list | to_json | regex_replace('"', '\'') }}
    

    产生

    - targets: ['10.0.0.100:9090', '10.0.0.200:9090']