AWS — Как передать ARN из шаблона формирования облака в функцию aws lambda

#amazon-web-services #aws-lambda #amazon-cloudformation

#amazon-веб-сервисы #aws-lambda #amazon-cloudformation

Вопрос:

У меня есть AWS lambda, который отправляет уведомление в тему SNS.

Лямбда-функция

 def send_sns_notification(message):
    sns = boto3.client('sns')
    response = sns.publish(
        TopicArn='arn:aws:sns:ca-central-1:xxxxx',    
        Message=message, 
        MessageAttributes={
            'AWS.SNS.SMS.SenderID': {
              'DataType': 'String',
              'StringValue': 'Airflow'   
            },
            'AWS.SNS.SMS.SMSType': {
              'DataType': 'String',
              'StringValue': 'Transactional'   
            }
        }   
    )
 

И мы используем шаблон формирования облака для развертывания SNS Topic , AWS Lambda и SNS Subscription . Как мне получить доступ к ARN для темы, созданной с помощью CloudFormation.

Шаблон формирования облака

  Lambda:
    Type: AWS::Serverless::Function
    Properties:
      Description: sends sns notification if dag in airflow fails
      FunctionName: "airflow-notification"
      Handler: send_sns_notification.py
      Runtime: python3.6
      ReservedConcurrentExecutions: !Ref AWS::NoValue
      Role: !FindInMap [EnvVariables, Parameters, LambdaRole]
      VpcConfig:
        SecurityGroupIds:
          - !FindInMap [EnvVariables, Parameters, VPCSecurityGroupId]
        SubnetIds:
          - !FindInMap [EnvVariables, Parameters, VPCSubnetId1]
          - !FindInMap [EnvVariables, Parameters, VPCSubnetId2]

  SNSTopic:
    Type: AWS::SNS::Topic
    Properties:
      TopicName: !FindInMap [EnvVariables, Parameters, SNSTopicName]
      DisplayName: airflow
      KmsMasterKeyId: !FindInMap [EnvVariables, Parameters, SNSCMK]


  SNSSubscription:
    Type: AWS::SNS::Subscription
    Properties:
      Endpoint: gaurangnshah@gmail.com
      Protocol: email
      TopicArn: !Ref 'SNSTopic'
 

Ответ №1:

Передайте ARN в качестве переменной среды.

  Lambda:
    Type: AWS::Serverless::Function
    Properties:
      Description: sends sns notification if dag in airflow fails
      FunctionName: "airflow-notification"
      Handler: send_sns_notification.py
      Runtime: python3.6
      ReservedConcurrentExecutions: !Ref AWS::NoValue
      Role: !FindInMap [EnvVariables, Parameters, LambdaRole]
      VpcConfig:
        SecurityGroupIds:
          - !FindInMap [EnvVariables, Parameters, VPCSecurityGroupId]
        SubnetIds:
          - !FindInMap [EnvVariables, Parameters, VPCSubnetId1]
          - !FindInMap [EnvVariables, Parameters, VPCSubnetId2]
      Environment:
        Variables: 
          TopicArn: !Ref 'SNSTopic'
 

Комментарии:

1. как мне создать зависимость, чтобы сначала создавалась тема SNS, а затем AWS lambda ?

2. @GaurangShah Зависимость неявна при использовании !Ref . docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide /…

Ответ №2:

Альтернативный подход заключается в следующем;

 account_id = boto3.client('sts').get_caller_identity().get('Account')

currentRegion = os.environ['AWS_REGION']

# write logic to define SNS_TOPIC variable, you can keep/form it from environment variables or hardcode or other suitable alternative. Here, SNS_TOPIC will hold only name of the SNS Topic

 

Наконец, задайте / сформируйте значение для TopicArn, используя один из следующих операторов;

TopicArn = ":".join(["arn", "aws", "sns", currentRegion, account_id, SNS_TOPIC])

или

TopicArn= ":".join(["arn:aws:sns:ca-central-1",SNS_TOPIC])