【问题标题】:AWS::WAFv2::WebACLAssociation ResourceArn for Application Load Balancer in CloudFormationAWS::WAFv2::WebACLAssociation ResourceArn 用于 CloudFormation 中的应用程序负载均衡器
【发布时间】:2021-04-17 00:55:53
【问题描述】:

我有一个 CloudFormation 模板,它可以创建一个像这样的 ElasticBeanstalk 环境:

        "ApplicationEnvironment": {
            "Type": "AWS::ElasticBeanstalk::Environment",
            "Properties": {
                "ApplicationName": {
                    "Ref": "Application"
                },
                "SolutionStackName": "64bit Amazon Linux 2018.03 v2.11.2 running Java 8",
                "VersionLabel": { 
                    "Ref": "AppVersion"
                },
                "Tier": {
                    "Name": "WebServer",
                    "Type": "Standard"
                },
                "OptionSettings": [
                    ...
                    {
                        "Namespace": "aws:elasticbeanstalk:environment",
                        "OptionName": "EnvironmentType",
                        "Value": "LoadBalanced"
                    },
                    {
                        "Namespace": "aws:elasticbeanstalk:environment",
                        "OptionName": "LoadBalancerType",
                        "Value": "application"
                    },
                    ...

---
        "WAF": {
            "Type": "AWS::WAFv2::WebACL",
            "Properties": {
                "DefaultAction": {
                    "Type": "BLOCK"
                },              
                "Scope": "REGIONAL",
                "VisibilityConfig": {
                    "CloudWatchMetricsEnabled": "false",
                    "MetricName": { "Fn::Join": [ "", [ { "Ref": "AWS::StackName" }, "metric-waf" ] ] },
                    "SampledRequestsEnabled": "false"
                },
                "Rules": [
                    {
                        "Action" : {
                          "Type" : "BLOCK"
                        },
                        "Priority" : 0,
                        "Statement" : {
                            "ManagedRuleGroupStatement": {
                                "VendorName": "AWS",
                                "Name": "AWSManagedRulesCommonRuleSet"
                            }
                        }
                    }
                ]
            }
        },
        "WAFAssociation": {
            "Type" : "AWS::WAFv2::WebACLAssociation",
            "Properties" : {
                "ResourceArn" : ???,
                "WebACLArn" : { "Ref": "WAF" }
            }
        }

我打算将 Beanstalk ALB 与 WebACL 关联,但不知道如何引用模板创建的应用程序负载均衡器 ARN。我不能只放入硬编码的 ARN,因为它总是根据模板创建的内容而变化。

有什么方法可以在 ResourceArn 字段中引用 ALB ARN?还是我需要在 Beanstalk 选项设置中的某处应用 WebACL?

【问题讨论】:

  • 我无法得到该答案,因为我无法从 ApplicationEnvironment 资源中引用 ALB:“AppAssociateWebACL”:{“Type”:“AWS::WAFv2::WebACLAssociation”、“Properties” : { "ResourceArn": { "Fn::GetAtt": [ "ApplicationEnvironment", "AWSEBV2LoadBalancer" ] 模板错误:资源 ApplicationEnvironment 不支持 Fn::GetAtt 中的属性类型 AWSEBV2LoadBalancer }, "WebACLArn": "..." } },
  • 另外,如果我只使用: "AppAssociateWebACL": { "Type": "AWS::WAFv2::WebACLAssociation", "Properties": { "ResourceArn": { "Ref" : "AWSEBV2LoadBalancer " }, "WebACLArn": "..." } },我得到:模板格式错误:模板资源块中未解决的资源依赖项 [AWSEBV2LoadBalancer]

标签: amazon-web-services amazon-elastic-beanstalk amazon-cloudformation amazon-waf


【解决方案1】:

我认为唯一的方法是通过 自定义资源 获取 EB 环境名称,使用describe_environment_resources API 调用来获取 EB 环境信息(包括 LA arn),然后返回给您的卡住了。

以下是可以添加到模板中的此类资源的工作示例

  LambdaBasicExecutionRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Statement:
        - Effect: Allow
          Principal:
            Service: lambda.amazonaws.com
          Action: sts:AssumeRole
      Path: /
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/AmazonEC2FullAccess
        - arn:aws:iam::aws:policy/AWSElasticBeanstalkFullAccess
        - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole

  MyCustomResource:
    Type: Custom::GetEBLoadBalancerArn
    Properties:
      ServiceToken: !GetAtt 'MyCustomFunction.Arn'
      EBEnvName: !Ref MyEnv

  MyCustomFunction:
    Type: AWS::Lambda::Function
    Properties:
      Handler: index.lambda_handler
      Description: "Get ARN of EB Load balancer"
      Timeout: 30
      Role: !GetAtt 'LambdaBasicExecutionRole.Arn'
      Runtime: python3.7
      Code:
        ZipFile: |
          import json
          import logging
          import cfnresponse
          import boto3

          logger = logging.getLogger()
          logger.setLevel(logging.INFO)

          eb = boto3.client('elasticbeanstalk')
          ec2 = boto3.client('ec2')

          def lambda_handler(event, context):
            logger.info('got event {}'.format(event))  
            try:

              responseData = {}

              if event['RequestType'] in ["Create"]:                      

                eb_env_name = event['ResourceProperties']['EBEnvName']

                response = eb.describe_environment_resources(
                    EnvironmentName=eb_env_name
                )

                lb_arn = response['EnvironmentResources']['LoadBalancers'][0]['Name']

                logger.info(str(response['EnvironmentResources']['LoadBalancers'][0]['Name']))

                responseData = {
                  "LBArn": lb_arn
                }

                cfnresponse.send(event, context, 
                                 cfnresponse.SUCCESS, responseData)

              else:
                logger.info('Unexpected RequestType!') 
                cfnresponse.send(event, context, 
                                  cfnresponse.SUCCESS, responseData)

            except Exception as err:

              logger.error(err)
              responseData = {"Data": str(err)}
              cfnresponse.send(event,context, 
                               cfnresponse.FAILED,responseData)
            return    

拥有您将使用的资源:

        "WAFAssociation": {
            "Type" : "AWS::WAFv2::WebACLAssociation",
            "Properties" : {
                "ResourceArn" : { "GetAtt": ["MyCustomResource", "LBArn"] },
                "WebACLArn" : { "Ref": "WAF" }
            }
        }

【讨论】:

  • @Steven 嗨。您有机会尝试自定义资源吗?
  • 我使用 json 格式,找不到像这样内联代码的方法。相反,我将函数分离到一个 s3 zip 对象中,并且还包含了stackoverflow.com/questions/49885243/… 中概述的 cfnresponse
  • 谢谢,马辛!我已经为此苦苦挣扎了好几天,终于能够用您的宝贵答案做到这一点。
  • @Steven 很高兴听到它成功了。您可以查看LambdaBasicExecutionRole 权限。对于这个答案,我让他们非常宽容。要遵循良好的做法,您必须将它们减少到使 lambda 函数正常工作所需的量。
  • 我最终应用了一项策略并删除了对 beanstalk 完全访问权限的引用:"Policies": [{ "PolicyName": "DescribeEnvironment", "PolicyDocument": { "Version" : "2012 -10-17”,“声明”:[ {“效果”:“允许”,“操作”:[“elasticbeanstalk:DescribeEnvironmentResources”],“资源”:{“Fn::Sub”:“arn:aws:elasticbeanstalk :${AWS::Region}:${AWS::AccountId}:environment/${Application}/${ApplicationEnvironment}" } } ] } }],
猜你喜欢
  • 2018-02-26
  • 2017-09-27
  • 2022-06-23
  • 1970-01-01
  • 2019-12-30
  • 2018-10-14
  • 1970-01-01
  • 2019-06-22
  • 2018-02-21
相关资源
最近更新 更多