首页 > 解决方案 > AWS CloudFormation - 如何获取硬件 VPN 的 VGW 外部 IP 地址

问题描述

根据我对 AWS CloudFormation 文档的阅读,AWS::EC2::VPNConnection资源不提供硬件 VPN 的外部 IP 地址的返回值。

我可以在 CloudFormation 中获取外部 IP 地址吗?如果最好的选择是使用 CloudFormation 中的 Lambda 资源,那么指向现有代码的指针将不胜感激。

标签: amazon-cloudformation

解决方案


如果不求助于 Lambda 支持的自定义资源,我找不到获取外部 IP 地址的方法,所以我写了一个。我已经在模板中包含了相关资源。您可以在此gist中找到完整的示例模板。

VPNOutsideIPGenerator:
Type: AWS::Lambda::Function
Properties:
  FunctionName: !Sub 'arn:aws:lambda:${AWS::Region}:${AWS::AccountId}:function:get-outside-ip'
  Handler: "index.lambda_handler"
  Timeout: 15
  Role: !GetAtt 'LambdaRole.Arn'
  Runtime: python3.6
  Code:
    ZipFile: |
      import logging
      import boto3
      import cfnresponse

      def lambda_handler(event, context):
          logger = logging.getLogger()
          logger.setLevel(logging.INFO)
          vpn_connection_id = event['ResourceProperties'].get('VPNID', None)
          ec2client = boto3.client('ec2')
          response = ec2client.describe_vpn_connections(VpnConnectionIds=[ vpn_connection_id ])
          responseData = {}
          responseData['OutsideIpAddress1'] = response['VpnConnections'][0]['VgwTelemetry'][0]['OutsideIpAddress']
          responseData['OutsideIpAddress2'] = response['VpnConnections'][0]['VgwTelemetry'][1]['OutsideIpAddress']
          logger.info('responseData {}'.format(responseData))
          cfnresponse.send(event, context, cfnresponse.SUCCESS, responseData)

推荐阅读