AWS announces preview of AWS Interconnect - multicloud
AWS announces AWS Interconnect – multicloud (preview), providing simple, resilient, high-speed private connections to other cloud service providers. AWS Interconnect - multicloud is easy to configure and provides high-speed, resilient connectivity with dedicated bandwidth, enabling customers to interconnect AWS networking services such as AWS Transit Gateway, AWS Cloud WAN, and Amazon VPC to other cloud service providers with ease.
Como faço para corrigir a dependência circular entre uma permissão do AWS Lambda e os recursos do grupo de destino no AWS CloudFormation?
Quero corrigir a dependência circular entre uma permissão do AWS Lambda (AWS::Lambda::Permission) e os recursos do grupo de destino (AWS::ElasticLoadBalancingV2::TargetGroup) no AWS CloudFormation.
Resolução
Uma dependência circular pode ocorrer ao configurar um AWS::ElasticLoadBalancingV2::TargetGroup com um destino de função Lambda e um recurso AWS::Lambda::Permission associado. Essa situação ocorre devido às seguintes interdependências:
Para registrar uma função Lambda como um destino usando sua propriedade Targets, o AWS::ElasticLoadBalancingV2::TargetGroup requer o AWS::Lambda::Permission para permitir que o Elastic Load Balancing invoque a função Lambda.
Além disso, o AWS::Lambda::Permission requer o ARN do AWS::ElasticLoadBalancingV2::TargetGroup em sua propriedade SourceArn para restringir as permissões de invocação a grupos de destino específicos.
Nesse caso, o AWS::ElasticLoadBalancingV2::TargetGroup não pode ser totalmente criado sem o AWS::Lambda::Permission. Mas o AWS::Lambda::Permission não pode ser criada sem o ARN do AWS::ElasticLoadBalancingV2::TargetGroup. Como resultado, o CloudFormation não consegue determinar qual recurso criar primeiro. Essa situação é um erro de dependência circular.
Para corrigir essa dependência circular, substitua a propriedade Targets do AWS::ElasticLoadBalancingV2::TargetGroup por um recurso personalizado baseado em Lambda para registrar a função Lambda como um destino.
Use um recurso personalizado baseado em Lambda para registrar sua função do Lambda como um destino em seu grupo de destino
Use um modelo do CloudFormation para definir um recurso personalizado baseado em Lambda para registrar sua função do Lambda como um destino em seu grupo de destino.
Lembre-se dos seguintes fatores ao criar o modelo:
- O modelo do CloudFormation inclui um exemplo da função Lambda HelloWorld e recursos ELBv2 para referência.
- Esse modelo fornece uma função RegisterTargetsFunction adicional do Lambda e um perfil de execução associada e um recurso personalizado. O recurso personalizado invoca a função do Lambda sempre que o recurso personalizado é criado, atualizado ou excluído.
- Durante a criação do recurso personalizado, a função do Lambda RegisterTargetsFunction registra a função Lambda definida como o destino no grupo de destino fornecido. Durante a exclusão do recurso personalizado, a função cancela o registro do destino.
- É possível modificar o modelo com seu próprio código.
- Esse modelo usa recursos personalizados baseados em AWS Lambda e assume que você está familiarizado com as melhores práticas do Lambda e com a solução de problemas.
Crie seu modelo do CloudFormation
Para criar seu modelo do CloudFormation, use o seguinte exemplo:
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. AWSTemplateFormatVersion: 2010-09-09 Description: HelloWorld Lambda function template for Application Load Balancer Lambda as target Parameters: # VPC in which the LoadBalancer and the LoadBalancer SecurityGroup will be created VpcId: Type: AWS::EC2::VPC::Id # Subnets in which the LoadBalancer will be created. Subnets: Type: List<AWS::EC2::Subnet::Id> # Name of the TargetGroup TargetGroupName: Type: String Default: 'MyTargets' Resources: LambdaExecutionRole: Type: AWS::IAM::Role Properties: AssumeRolePolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Principal: Service: - lambda.amazonaws.com Action: - sts:AssumeRole Path: "/" Policies: - PolicyName: AllowRegisterAndDeregisterTargets PolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Action: - 'elasticloadbalancing:RegisterTargets' Resource: !GetAtt TargetGroup.TargetGroupArn - Effect: Allow Action: - 'elasticloadbalancing:DeregisterTargets' Resource: '*' # Lambda function which displays an HTML page with "Hello from Lambda!" message upon invocation HelloWorldFunction: Type: 'AWS::Lambda::Function' Properties: Code: ZipFile: | def lambda_handler(event, context): return { "statusCode": 200, "statusDescription": "HTTP OK", "isBase64Encoded": False, "headers": { "Content-Type": "text/html" }, "body": "<h1>Hello from Lambda!</h1>" } MemorySize: 128 Handler: index.lambda_handler Timeout: 30 Runtime: python3.12 Role: !GetAtt LambdaExecutionRole.Arn LoadBalancer: Type: AWS::ElasticLoadBalancingV2::LoadBalancer Properties: Scheme: internet-facing Subnets: !Ref Subnets SecurityGroups: - !Ref LoadBalancerSecurityGroup HttpListener: Type: 'AWS::ElasticLoadBalancingV2::Listener' Properties: DefaultActions: - TargetGroupArn: !Ref TargetGroup Type: forward LoadBalancerArn: !Ref LoadBalancer Port: 80 Protocol: HTTP LoadBalancerSecurityGroup: Type: AWS::EC2::SecurityGroup Properties: GroupDescription: Allow HTTP to client host VpcId: !Ref VpcId SecurityGroupIngress: - IpProtocol: tcp FromPort: 80 ToPort: 80 CidrIp: 0.0.0.0/0 HelloWorldFunctionInvokePermission: Type: AWS::Lambda::Permission Properties: FunctionName: !GetAtt HelloWorldFunction.Arn Action: 'lambda:InvokeFunction' Principal: elasticloadbalancing.amazonaws.com SourceArn: !GetAtt TargetGroup.TargetGroupArn TargetGroup: Type: AWS::ElasticLoadBalancingV2::TargetGroup Properties: Name: !Ref TargetGroupName TargetType: lambda # Custom resource for Lambda function - "RegisterTargetsFunction" RegisterTargets: DependsOn: [TargetGroup, HelloWorldFunctionInvokePermission] Type: Custom::RegisterTargets Properties: ServiceToken: !GetAtt RegisterTargetsFunction.Arn ServiceTimeout: 15 # Input parameters for the Lambda function LambdaFunctionARN: !GetAtt HelloWorldFunction.Arn TargetGroupARN: !GetAtt TargetGroup.TargetGroupArn # Lambda function that performs RegisterTargets API call RegisterTargetsFunction: Type: AWS::Lambda::Function Properties: Code: ZipFile: | import logging import boto3, json, botocore import cfnresponse #Define logging properties for 'logging' log = logging.getLogger() log.setLevel(logging.INFO) #Main Lambda function to be executed def lambda_handler(event, context): try: # print the event type sent from cloudformation log.info ("'" + str(event['RequestType']) + "' event was sent from CFN") # Input Parameters TargetGroupARN = event['ResourceProperties']['TargetGroupARN'] LambdaFunctionARN = event['ResourceProperties']['LambdaFunctionARN'] log.info("TargetGroup ARN value is:" + TargetGroupARN) log.info("Lambda Function ARN value is:" + LambdaFunctionARN) responseData = {} # ELBV2 initilize client = boto3.client('elbv2') # Initilize Vars response = '' error_msg = '' if event['RequestType'] == "Create" or event['RequestType'] == "Update": # Make the RegisterTargets API call try: response = client.register_targets( TargetGroupArn=TargetGroupARN, Targets=[ { 'Id': LambdaFunctionARN }, ] ) except botocore.exceptions.ClientError as e: error_msg = str(e) if error_msg: log.info("Error Occured:" + error_msg) response_msg = error_msg # SIGNAL BACK TO CLOUDFORMATION log.info("Trying to signal FAILURE back to cloudformation.") responseData = {"Message" : response_msg, "Function" : context.log_stream_name} cfnresponse.send(event, context, cfnresponse.FAILED, responseData) else: response_msg = "Successfully registered Lambda(" + LambdaFunctionARN + ") as Target" log.info(response_msg) # SIGNAL BACK TO CLOUDFORMATION log.info("Trying to signal SUCCESS back to cloudformation.") responseData = {"Message" : response_msg, "Function" : context.log_stream_name} cfnresponse.send(event, context, cfnresponse.SUCCESS, responseData) # log the end of the create event log.info ("End of '" + str(event['RequestType']) + "' Event") elif "Delete" in str(event['RequestType']): # Make the DeregisterTargets API call try: response = client.deregister_targets( TargetGroupArn=TargetGroupARN, Targets=[ { 'Id': LambdaFunctionARN }, ] ) except botocore.exceptions.ClientError as e: error_msg = str(e) if error_msg: log.info("Error Occured:" + error_msg) response_msg = error_msg # SIGNAL BACK TO CLOUDFORMATION log.info("Trying to signal FAILURE back to cloudformation.") responseData = {"Message" : response_msg, "Function" : context.log_stream_name} cfnresponse.send(event, context, cfnresponse.FAILED, responseData) else: response_msg = "Successfully deregistered Lambda(" + LambdaFunctionARN + ") as Target" log.info(response_msg) # SIGNAL BACK TO CLOUDFORMATION log.info("Trying to signal SUCCESS back to cloudformation.") responseData = {"Message" : response_msg, "Function" : context.log_stream_name} cfnresponse.send(event, context, cfnresponse.SUCCESS, responseData) # log the end of the create event log.info ("End of '" + str(event['RequestType']) + "' Event") else: log.info ("RequestType sent from cloudformation is invalid.") log.info ("Was expecting 'Create', 'Update' or 'Delete' RequestType(s).") log.info ("The detected RequestType is : '" + str(event['RequestType']) + "'") # SIGNAL BACK TO CLOUDFORMATION log.info("Trying to signal FAILURE back to cloudformation due to invalid request type.") responseData={"Function" : context.log_stream_name} cfnresponse.send(event, context, cfnresponse.FAILED, responseData) except Exception as e: log.info ("Function failed due to the following error:") print (e) # SIGNAL BACK TO CLOUDFORMATION log.info("Trying to signal FAILURE back to cloudformation due to the error.") responseData={"Function" : context.log_stream_name} cfnresponse.send(event, context, cfnresponse.FAILED, responseData) Handler: index.lambda_handler Role: !GetAtt LambdaExecutionRole.Arn Runtime: python3.12 Timeout: '15' Outputs: Message: Description: Message returned from Lambda Value: !GetAtt - RegisterTargets - Message
Use seu modelo do CloudFormation para criar a pilha do CloudFormation
- Salve o modelo que você criou como um arquivo YAML.
- Use a AWS CLI ou o console do CloudFormation para criar uma pilha.
Observação: se você receber erros ao executar comandos da AWS Command Line Interface (AWS CLI), consulte Solucionar erros da AWS CLI. Além disso, verifique se você está usando a versão mais recente da AWS CLI. - Use os parâmetros da pilha VPCid, Subnets e TargetGroupName para especificar o nome desejado do Amazon Virtual Private Cloud (Amazon VPC), das sub-redes e do grupo de destino.
- Depois que a pilha atingir o estado CREATE_COMPLETE, acesse a seção Saídas do console da AWS CloudFormation para ver a seguinte mensagem:
“Lambda adicionado com sucesso(arn:aws:lambda:<region>:<account_id>:function:<function_name>) como Destino” - Verifique o grupo de destino para checar se o destino foi registrado.
- Tópicos
- Management & Governance
- Idioma
- Português

Conteúdo relevante
- Resposta aceitafeita há 10 meses
- feita há 6 meses
AWS OFICIALAtualizada há 3 anos