CloudFormation을 사용하여 API 게이트웨이 모니터링을 위한 SNS 알림 생성 방법

9812 단어 awssnslambdacloud
안녕하세요 Devs,
작년에 올린 게시물에서 제가 설명했습니다how to create SNS notification for Lambda monitoring.이제 API 게이트웨이 모니터링을 추가하고 CloudFormation을 사용하여 전체 스택을 생성하여 이 기능을 더욱 확장할 것입니다.

우리가 실제 해석을 시작하기 전에 나는 먼저 기본 개념을 설명할 것이다.


  • SNS란? SNS는 AWS 알림 또는 이벤트 관리 서비스로 구독과 게시 등 두 가지 단점이 있다.이러한 이벤트의 상태에 따라 SNS는 다른 SNS나 람바다 또는 SMS 또는 이메일(모든 미디어)에 알릴 수 있습니다.SNS 주제 및 Amazon Kinesis Data Firehose, Amazon SQS, AWS Lambda, HTTP, 이메일, 모바일 푸시 알림 및 모바일 텍스트 메시지(SMS) 등 지원되는 종단점 유형을 사용하여 게시된 메시지를 받습니다.AWS 파일https://docs.aws.amazon.com/sns/latest/dg/welcome.html에 잘 설명되어 있는 차트

  • Lambda는 무엇입니까? Lambda는 AWS 서버 없는 서비스 (컴퓨터) 입니다. Python, NodeJs 등의 코드를 실행할 용기를 제공합니다.Net, GoLang, Java 등. 코드 실행 프로그램과 같습니다.람바다는 API 게이트웨이, SNS, 스텝스 함수 등 다양한 방식으로 터치할 수 있다. 람바다는 고가용성 컴퓨팅 인프라
  • 에서 코드를 실행한다.

  • API 게이트웨이란 무엇입니까? AWS API 게이트웨이는 AWS 서비스로 REST, HTTP와 WebSocket API를 창설, 발표, 유지보수, 감시하고 보호하는 데 사용되며, 그 어떠한 다른 API 단점과 같습니다.
  • *CloudFormation*-AWS CloudFormation은 개발자와 기업이 간단한 방식으로 관련 AWS와 외부 자원을 만들고 정확한 순서로 관리할 수 있는 마력이다.​이것은 인프라 시설과 코드처럼 유효하다.

  • CloudFormation을 사용하여 생성하는 방법부터 살펴보겠습니다.


    1. 우선 기본 클라우드 구조를 만들 것이다-
    참고로 AWS는 많은 용례를 바탕으로 한 미리 정의된 템플릿을 제공했고 여기https://aws.amazon.com/cloudformation/resources/templates/도 참고할 수 있다.
    우리는 0부터 시작한다.yaml이나 json 형식의 템플릿을 만들어야 합니다.템플릿은 자원을 어떻게 만드는지, 그것들의 설정이 무엇인지, 그리고 서로 연결하는 방법을 알려 줍니다.{}에서 언급한 것은 모두 사용자 정의나 사용자 정의의 값 이름입니다.
    AWSTemplateFormatVersion: '2010-09-09'
    Parameters:
      {ParamsName}:
        Type: String
        Description: Description of params 
        Default: default value
    Resources:
      {ResourceCustomName}:
        Type: AWS::ApiGateway::RestApi
        Properties:
          ApiKeySourceType: HEADER
          Description: An API Gateway with a Lambda Integration
          EndpointConfiguration:
            Types:
              - EDGE
          Name: Name of resources which are going to be used publicly. 
    
    2. 클라우드 매개변수 정의(선택 사항): 이 단계는 선택 사항입니다.CloudFormation stack을 실행할 때 매개 변수를 전달하려면 이 옵션을 선택하십시오. 그렇지 않으면 무시합니다.동적 배치를 더욱 잘 하기 위해서 나는 이 단계를 추천할 것이다.
    Parameters:
      ArtifactsBucket:
        Type: String
        Description: The S3 bucket where the artifacts are stored
        Default: 'awsugblr-cnf-demo'
      LambdaArtifactsKey:
        Type: String
        Description: The key from the S3 Bucket with the artifacts to deploy 
        Default: 'lambda-sample.zip'
      FunctionName:  
        Type: String
        Description: Name of the function
        Default: 'lambda-apigateway-sns-test'
    
    3. Lambda 리소스 만들기: Lambda 리소스를 만들 때 역할을 만들어야 하거나, IAM에서 사용할 수 있는 기존 역할이 있으면 해당 역할을 사용할 수 있습니다.다음 예와 같이 역할에 유사한 액세스 정책이 있어야 합니다.사용 가능AWS IAM policy generator tool
    Policies:
          - PolicyName: root
            PolicyDocument:
              Version: '2012-10-17'
              Statement:
              - Effect: Allow
                Action:
                - sns:*
                Resource: arn:aws:sns:*:*:*
    
    IAM 역할이 준비되면 람바다 리소스를 사용할 수 있습니다.lambda를 만들 때, zip을 코드 라이브러리로 사용하거나, 여기에서 언급한 실행 코드를 전달할 수 있습니다.https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-function.html . 나는 여기서 zip을 코드 라이브러리로 사용한다.코드 zip을 만들어 해당 S3 스토리지 통에 업로드합니다.CloudFormation 템플릿을 만들기 전에 코드 라이브러리를 업로드할 S3 bucket을 만들어야 합니다.
      LambdaApiGatewaySNSTest:
        Type: AWS::Lambda::Function
        Properties:
          Description: To test apigateway and SNS on OnFailure
          Handler: index.handler
          Runtime: nodejs12.x
          FunctionName: !Ref FunctionName
          Code:
            S3Bucket: !Ref ArtifactsBucket
            S3Key: !Ref LambdaArtifactsKey
          Role: !GetAtt LambdaIamRole.Arn
          MemorySize: 128
          Timeout: 60
      LambdaIamRole:
        Type: AWS::IAM::Role
        Properties:
          AssumeRolePolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Effect: 'Allow'
                Principal:
                  Service:
                    - 'lambda.amazonaws.com'
                    - 'sns.amazonaws.com'
                Action:
                  - 'sts:AssumeRole'
          Policies:
          - PolicyName: root
            PolicyDocument:
              Version: '2012-10-17'
              Statement:
              - Effect: Allow
                Action:
                - sns:*
                Resource: arn:aws:sns:*:*:*
          Path: '/'
    
    
    4. SNS 테마 및 구독 만들기: SNS 테마에서 FunctionName 아래에 Lambda 노드가 있습니다.!Ref LambdaApiGatewaySNSTest Lambda 함수 요소의 이름을 가리킵니다.문자나 이메일 알림을 받을 수 있는 방법은 무엇이든지 선택할 수 있다.Lambda를 OnFailure 또는 OnSuccess에 연결하여 SNS 알림을 받을 수 있습니다.
      LambdaEmailAlertSNSTopic: 
        Type: AWS::SNS::Topic 
        Properties: 
          TopicName: lambda-apigateway-sns-test-execution
          DisplayName: lambda-apigateway-sns-test-execution 
          Subscription: 
            - Endpoint: "[email protected]" 
              Protocol: "EMAIL-JSON"
      LambdaEventInvokeConfig:
        Type: AWS::Lambda::EventInvokeConfig
        Properties:
            FunctionName: !Ref LambdaApiGatewaySNSTest
            Qualifier: "$LATEST"
            MaximumEventAgeInSeconds: 600
            MaximumRetryAttempts: 0
            DestinationConfig: 
                OnFailure:
                    Destination: !Ref LambdaEmailAlertSNSTopic
    
    5. API 게이트웨이 만들기: AWS 문서에 샘플 템플릿 코드가 제공됩니다.API 게이트웨이의 코드가 너무 길다는 것을 두려워하지 마세요.API 게이트웨이를 만들 때는 API, 리소스, 메서드, 모델(반환 및 응답 데이터 유형), API 단계, 배포 및 IAM 역할(없는 경우) 등의 구성 요소가 필요합니다.
      LambdaApiGatewayRestApi:
        Type: AWS::ApiGateway::RestApi
        Properties:
          ApiKeySourceType: HEADER
          Description: An API Gateway with a Lambda Integration
          EndpointConfiguration:
            Types:
              - EDGE
          Name: lambda-api
      LambdaApiGatewayResource:
        Type: AWS::ApiGateway::Resource
        Properties:
          ParentId: !GetAtt LambdaApiGatewayRestApi.RootResourceId
          PathPart: 'lambda'
          RestApiId: !Ref LambdaApiGatewayRestApi
      LambdaApiGatewayMethod:
        Type: AWS::ApiGateway::Method
        Properties:
          ApiKeyRequired: false
          AuthorizationType: NONE
          HttpMethod: POST
          Integration:
            ConnectionType: INTERNET
            Credentials: !GetAtt LambdaApiGatewayIamRole.Arn
            IntegrationHttpMethod: POST
            PassthroughBehavior: WHEN_NO_MATCH
            TimeoutInMillis: 29000
            Type: AWS_PROXY
            Uri: !Sub 'arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${LambdaApiGatewaySNSTest.Arn}/invocations'
          OperationName: 'lambda'
          ResourceId: !Ref LambdaApiGatewayResource
          RestApiId: !Ref LambdaApiGatewayRestApi
      LambdaApiGatewayModel:
        Type: AWS::ApiGateway::Model
        Properties:
          ContentType: 'application/json'
          RestApiId: !Ref LambdaApiGatewayRestApi
          Schema: {}
      LambdaApiGatewayStage:
        Type: AWS::ApiGateway::Stage
        Properties:
          DeploymentId: !Ref LambdaApiGatewayDeployment
          Description: Lambda API Stage v0
          RestApiId: !Ref LambdaApiGatewayRestApi
          StageName: 'v0'
      LambdaApiGatewayDeployment:
        Type: AWS::ApiGateway::Deployment
        DependsOn: LambdaApiGatewayMethod
        Properties:
          Description: Lambda API Deployment
          RestApiId: !Ref LambdaApiGatewayRestApi
      LambdaApiGatewayIamRole:
        Type: AWS::IAM::Role
        Properties:
          AssumeRolePolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Sid: ''
                Effect: 'Allow'
                Principal:
                  Service:
                    - 'apigateway.amazonaws.com'
                Action:
                  - 'sts:AssumeRole'
          Path: '/'
          Policies:
            - PolicyName: LambdaAccess
              PolicyDocument:
                Version: '2012-10-17'
                Statement:
                  - Effect: 'Allow'
                    Action: 'lambda:*'
                    Resource: !GetAtt LambdaApiGatewaySNSTest.Arn
    
    위의 모든 단계를 완료하면 스택에 CloudFormation 템플릿을 배치할 수 있습니다.검증 과정에서 오류가 발생하면 AWS 콘솔에서 오류가 발생합니다.대부분의 오류는 참고 값을 만들 수 없기 때문입니다.API 게이트웨이에 오류가 발생하면 해석되지 않은 인용 lambda 자원을 표시합니다.CloudFormation 이벤트 콘솔을 확인해야 합니다.다음은 CloudFormation 스택 콘솔의 오류 예입니다.


    CloudFormation을 사용하여 API 게이트웨이 오류 메커니즘을 만드는 것을 이 블로그에서 즐겨보시기 바랍니다.
    읽어주셔서 감사합니다.궁금한 점이나 조언이 있으면 아래 댓글이나 제 트위터 손잡이에 언제든지 연락 주세요.
    .
    참조 자료:
  • Github Example

  • https://aws.amazon.com/cloudformation/faqs/
  • 좋은 웹페이지 즐겨찾기