【问题标题】:jinja2 how to extend listjinja2 如何扩展列表
【发布时间】:2020-03-12 00:42:23
【问题描述】:

我正在尝试使用 ansible set_fact Jinja2 创建一个列表, 但它创建了两个不同的列表

变量:lb_listeners 设置为 [80, 443]

代码:

- 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 -%}

实际输出

[{'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'}]}]

如何在一个列表中获得它?

【问题讨论】:

标签: python ansible jinja2 devops


【解决方案1】:

您正在将字符串模板 {{ 嵌入到事实分配的中间;你想要的是在 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 }}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-18
    • 2019-03-12
    相关资源
    最近更新 更多