Amazon web services AWS::WAFv2::WebACLAssociation ResourceArn用于云信息中的应用程序负载平衡器

Amazon web services AWS::WAFv2::WebACLAssociation ResourceArn用于云信息中的应用程序负载平衡器,amazon-web-services,amazon-elastic-beanstalk,amazon-cloudformation,amazon-waf,elasticbeanstalk,Amazon Web Services,Amazon Elastic Beanstalk,Amazon Cloudformation,Amazon Waf,Elasticbeanstalk,我有一个CloudFormation模板,它创建了一个ElasticBeanstalk环境,如下所示: "ApplicationEnvironment": { "Type": "AWS::ElasticBeanstalk::Environment", "Properties": { "ApplicationNam

我有一个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吗?

我认为唯一的方法是通过一个自定义资源,该资源采用EB env名称,使用
描述环境\u资源
API调用来获取EB env信息(包括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" }
            }
        }

您可能会看到“我看不到”的答案,因为我无法从ApplicationEnvironment资源中引用ALB:“AppAssociateWebACL”:{“Type”:“AWS::WAFv2::WebACLAssociation”,“Properties”:{“ResourceArn”:{“Fn::GetAtt”:[“ApplicationEnvironment”,“AWSEBV2LoadBalancer”]模板错误:资源应用程序环境不支持Fn::GetAtt},“WebACLArn”:“…”}}中的属性类型AWSEBV2LoadBalancer,如果我只使用:“AppAssociateWebACL”:{“类型”:“AWS::WAFW2::WebACLAssociation”,“属性”:“{”ResourceArn:{”Ref:“AWSEBV2LoadBalancer”},“WebACLArn:“…”},我得到:模板格式错误:未解析的资源依赖项[AWSEBV2LoadBalancer]位于template@Steven你好您有机会尝试过自定义资源吗?我使用json格式,但找不到这样内联代码的方法。相反,我将函数分离为一个s3 zip对象,并包含了在Thank,Marcin!“我已经为此奋斗了好几天,终于能够用你宝贵的答案来完成这件事。”史蒂文很高兴听到这个问题得到了解决。您可以查看
lambdasicexecutionrole
权限。对于这个回答,我让他们非常宽容。为了遵循良好的实践,您必须将它们简化为使lambda函数工作所需的内容。我最终应用了一个策略,并删除了对beanstalk完全访问的引用:“策略”:[{“PolicyName”:“descripbeenvironment”,“PolicyDocument”:{“Version”:“2012-10-17”,“Statement”:[{“效果”:“允许”、“操作”:[“elasticbeanstalk:DescribeenEnvironmentResources”],“资源”:{“Fn::Sub”:“arn:aws:elasticbeanstalk:${aws::Region}:${aws::AccountId}:environment/${Application}/${ApplicationEnvironment}}}}}],