简体   繁体   English

jinja2 如何扩展列表

[英]jinja2 how to extend list

I am trying to create a single list using ansible set_fact Jinja2, But its creating two different lists我正在尝试使用 ansible set_fact Jinja2 创建一个列表,但它创建了两个不同的列表

Variable: lb_listeners is set to [80, 443]变量:lb_listeners 设置为 [80, 443]

code:代码:

- name: "Build listeners map"
  set_fact:
    lb_lstnr_map: >-
      {%- set lb_lstnr_map = [] -%}
      {%- for port in lb_listeners -%}
        {%- if port|int == 443 and cert_arn.startswith('arn:') -%}
          {{  lb_lstnr_map + [{
            'Protocol': 'HTTPS',
            'Port': 443,
            'DefaultActions': [ { 'Type': 'forward', 'TargetGroupName': tg_name } ],
            'SslPolicy': ssl_policy,
            'Certificates': [ { 'CertificateArn': cert_arn } ]
            }]
         }}
        {%- elif port|int != 443 -%}
          {{ lb_lstnr_map + [{
            'Protocol': 'TCP' if lb_type == 'network' else 'HTTP',
            'Port': port,
            'DefaultActions': [ { 'Type': 'forward', 'TargetGroupName': tg_name } ]
            }]
          }}
        {%- endif -%}
      {%- endfor -%}

Actual output实际产量

[{'Protocol': 'HTTP', 'Port': 8080, 'DefaultActions': [{'Type': 'forward', 'TargetGroupName': 'dev-sample-app-tga'}]}] 
[{'Protocol': 'HTTPS', 'Port': 443, 'DefaultActions': [{'Type': 'forward', 'TargetGroupName': 'dev-sample-app-tga'}], 'SslPolicy': 'ELBSecurityPolicy-2016-08', 'Certificates': [{'CertificateArn': 'arn:aws:x:x'}]}]

How can get that in a single list?如何在单个列表中获得它?

You are embedding string templates {{ in the middle of a fact assignment;您在事实赋值的中间嵌入字符串模板{{ ; what you want is to do all the python stuff in jinja2, and only emit the structure at the end:你想要的是在 jinja2 中做所有的 python 东西,最后只发出结构:

set_fact:
    lb_lstnr_map: >-
      {%- set lb_lstnr_map = [] -%}
      {%- for port in lb_listeners -%}
      {%-   if port|int == 443 and cert_arn.startswith('arn:') -%}
      {%-     set _ = lb_lstnr_map.append({'Protocol': 'HTTPS'}) -%}
      {%-   elif port|int != 443 -%}
      {%-    set _ = lb_lstnr_map.append({
                'Protocol': 'TCP' if lb_type == 'network' else 'HTTP',
             }) -%}
      {%-   endif -%}
      {%- endfor -%}
      {{ lb_lstnr_map }}

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

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