卓:如何使用CloudFormation创建网络负载均衡器目标组?

问题描述

我们正在使用CloudFormation创建网络负载平衡器。目标类型是IP,它需要指向VPC端点的IP地址。

因此,我们需要创建“ ip”类型的目标组,并指定目标列表:

  NetworkLoadBalancerTargetGroup:
    Type: AWS::ElasticLoadBalancingV2::TargetGroup
    Properties:
      Name: !Sub '${AWS::StackName}-NLT'
      Port: 443
      Protocol: TLS
      VpcId: !Ref 'VPC'
      TargetGroupAttributes:
        - Key: deregistration_delay.timeout_seconds
          Value: 300
      targettype: ip
      Targets: # list of the primary IP addresses of the Network interface(s) associated with the VPC endpoint
        - ?????

目标必须是VPC端点的IP地址。如何引用这些?

因此创建了VPC端点:

  VpcEndpoint:
    Type: AWS::EC2::VPCEndpoint
    Properties:
      VpcEndpointType: Interface
      subnetIds:
      - !Ref ProtectedsubnetA
      - !If [IsProd,!Ref ProtectedsubnetB,!Ref 'AWS::Novalue']
      - !If [IsProd,!Ref ProtectedsubnetC,!Ref 'AWS::Novalue']
      SecurityGroupIds:
      - !Ref SecurityGroupHttpsInInternal
      - !Ref SecurityGroupHttpsOutInternal
      PrivatednsEnabled: true
      ServiceName: !Sub com.amazonaws.${AWS::Region}.execute-api
      VpcId: !Ref VPC
      PolicyDocument: '{
          "Statement": [
            {
              "Action": "*","Effect": "Allow","Resource": "*","Principal": "*"
            }
          ]
        }'

我可以这样获得网络接口ID的列表: !GetAtt VpcEndpoint.NetworkInterfaceIds

但是,这是一个字符串列表。如何在ID列表中获取每个网络接口的PrimaryPrivateIpAddress属性

为完整起见,这是网络负载平衡器和关联的侦听器的定义:

  NetworkLoadBalancer:
    Type: AWS::ElasticLoadBalancingV2::LoadBalancer
    Properties:
      LoadBalancerAttributes:
        - Key: load_balancing.cross_zone.enabled
          Value: true
      Name: !Sub '${AWS::StackName}-NLB-Protected'
      Scheme: internal
      subnets:
        - !Ref ProtectedsubnetA
        - !If [IsProd,!Ref 'AWS::Novalue']
        - !If [IsProd,!Ref 'AWS::Novalue']
      Type: network

  NetworkLoadBalancerListener:
    Type: AWS::ElasticLoadBalancingV2::Listener
    Properties:
      DefaultActions:
      - Type: forward
        TargetGroupArn: !Ref NetworkLoadBalancerTargetGroup
      LoadBalancerArn: !Ref NetworkLoadBalancer
      Port: '443'
      Protocol: TLS
      SslPolicy: ELBSecurityPolicy-TLS-1-2-Ext-2018-06
      Certificates:
        - CertificateArn: !Ref ACMCertificate

解决方法

但是,这是一个字符串列表。如何在ID列表中获取每个网络接口的PrimaryPrivateIpAddress属性?

如您所述,AWS::EC2::VPCEndpoint返回NetworkInterfaceIds,而不返回IP地址。因此,要获取实际的IP地址,您必须开发一个custom resource

这将采用 lambda函数的形式,您将向其传递ENI ID。该功能将使用 AWS SDK (例如boto3)来获取相应的IP地址。该功能会将IP地址返回给CFN,您将在目标组中使用它。