Jinja2 用于动态变量更改的大小写开关

Jinja2 case switch for dynamic variable changes

我有一个正在使用 Jinja 编辑的模板,我想知道我是否可以根据某种 case/switch.

设置某个变量

例如,我有这个配置文件:

[Service-Name]
Service_Name = hostname01

[Ports]
Ports = 22, 443, 8080

[Instance]
Instance_ID_IP = i-0asd589r52
#Instance_ID_IP = 192.168.1.1

Instance 部分可以接受 IDIP

在模板中的某处,我需要更改一个变量以根据配置收到的是 IP 还是 ID 来工作。

这是我模板中该区域的精简片段:

    {% for port in ports %}
    ElasticLoadBalancingV2TargetGroup{{ counter + loop.index0 }}:
        Type: "AWS::ElasticLoadBalancingV2::TargetGroup"
        Properties:
            Port: !FindInMap [NLBPorts, Port{{ counter + loop.index0 }}, Port]
            TargetType: "instance" # here
            HealthyThresholdCount: 3
    {% endfor %}

在显示 TargetType: "instance" 的行中,我需要它显示 instanceip

我不太确定如何实现这一点,以及它是否应该在模板内,用 Jinja2 编写或在脚本本身内。或者两者都有?

这是我的脚本:

from jinja2 import Environment, FileSystemLoader
import configparser

#Choose templates location and load to env variable
loader = FileSystemLoader('templates')
env = Environment(loader=loader)
configParser = configparser.RawConfigParser()
configFilePath = (r'endpoint.cfg')
configParser.read(configFilePath)

#Declaring variables from endpoint.cfg
service_name = configParser.get('Service-Name', 'Service_Name')
ports = configParser.get('Ports', 'Ports')
ports = tuple([int(port.strip()) for port in ports.split(',')])
instance_id_ip = configParser.get('Instance', 'Instance_ID_IP')

#Provide name of template
endpoint_service_template = env.get_template('endpointservice-template.yaml')

#Render templates
endpoint_service_result = endpoint_service_template.render({'service_name':service_name, 'ports':ports, 'instance_id_ip':instance_id_ip})

我不太确定如何实现我想要做的事情。你如何设置一个开关来检查我输入的是 ID 还是 IP,然后告诉 Jinja 使用哪一个。

我的方法是使用正则表达式来确定它是否是 IP:

import re

try:
    is_ip_address = [0<=int(x)<256 for x in re.split('\.',re.match(r'^\d+\.\d+\.\d+\.\d+$',instance_id_ip).group(0))].count(True)==4
except:
    is_ip_address = None

我不确定如何从这里继续。假设 instance_id_ipNone,我如何告诉 Jinja 它是一个 ID 而不是 IP,反之亦然?

只需将 is_ip_address 作为另一个变量传递到您的模板中:

endpoint_service_result = endpoint_service_template.render({
  'service_name':service_name,
  'ports':ports,
  'instance_id_ip':instance_id_ip,
  'is_ip_address': is_ip_address,
})

然后在模板中使用条件设置 TargetType:

TargetType: "{'ip' if is_ip_address else 'instance'}"