공부하기싫어
article thumbnail

목차

     

    테스트 목적

    • CodeCommit, CodeBuild, AWS-CLI 를 활용해 Lambda 함수의 이미지 업데이트

    1. 테스트 준비

    1.1 CodeCommit Repository

    demo.txt 를 생성해 main branch 활성화

    1.2 ECR

    초기 람다 생성을 위해 이미지를 하나 빌드해서 올려줌

    # lambda_function.py
    import boto3
    
    def handler(event, context):
        return "image version : 1"
    
    # Dockerfile
    FROM public.ecr.aws/lambda/python:3.9
    
    # Copy function code
    COPY ./* ${LAMBDA_TASK_ROOT}
    
    # Set the CMD to your handler (could also be done as a parameter override outside of the Dockerfile)
    CMD [ "lambda_function.handler" ]
    
    # build and push commands
    aws ecr get-login-password --region ap-northeast-2 | docker login --username AWS --password-stdin 501587125031.dkr.ecr.ap-northeast-2.amazonaws.com
    
    version_info=v.0
    
    docker build -t test-awscli-update-lambda-image:${version_info} .
    
    docker tag test-awscli-update-lambda-image:${version_info} 501587125031.dkr.ecr.ap-northeast-2.amazonaws.com/test-awscli-update-lambda-image:${version_info}
    
    docker push 501587125031.dkr.ecr.ap-northeast-2.amazonaws.com/test-awscli-update-lambda-image:${version_info}
    

    1.3 Lambda

    수동 생성해준 초기 이미지를 사용하는 lambda 함수 생성

     

    테스트 시 handler return 을 확인할 수 있음

    1.4 awscli 테스트

    $ aws lambda update-function-code --function-name test-target-lambda --image-uri 501587125031.dkr.ecr.ap-northeast-2.amazonaws.com/test-awscli-update-lambda-image:v.1 --publish
    {
        "FunctionName": "test-target-lambda",
        "FunctionArn": "arn:aws:lambda:ap-northeast-2:501587125031:function:test-target-lambda:1",
        "Role": "arn:aws:iam::501587125031:role/service-role/test-target-lambda-role-335pv0f3",
        "CodeSize": 0,
        "Description": "",
        "Timeout": 3,
        "MemorySize": 128,
        "LastModified": "2023-08-15T15:32:54.000+0000",
        "CodeSha256": "fc2c8882735b2ffa9f4a917b4b06647f7e6da437a276caf593328bf3788a1ad3",
        "Version": "1",
        "TracingConfig": {
            "Mode": "PassThrough"
        },
        "RevisionId": "9771660f-c451-4d84-a026-e4e06fd13388",
        "State": "Pending",
        "StateReason": "The function is being created.",
        "StateReasonCode": "Creating",
        "PackageType": "Image",
        "ImageConfigResponse": {},
        "Architectures": [
            "x86_64"
        ],
        "EphemeralStorage": {
            "Size": 512
        },
        "SnapStart": {
            "ApplyOn": "None",
            "OptimizationStatus": "Off"
        }
    }
    

    2. CodeBuild

    2.1 dir tree

    ~/test-awscli$ tree
    .
    ├── buildspec.yml
    └── container
        ├── build-commands.sh
        ├── Dockerfile
        └── lambda_function.py
    

    2.2 buildspec.yml

    version: 0.2
    
    env:
      variables:
        AWS_DEFAULT_REGION: ap-northeast-2
        AWS_ACCOUNT_ID: 501587125031
        IMAGE_REPO_NAME: test-awscli-update-lambda-image
        IMAGE_TAG: v.3
        LAMBDA_NAME: test-target-lambda
    
    phases:
      install:
        commands:
          - apt update && apt-get update
      pre_build:
        commands:
          - echo $AWS_DEFAULT_REGION
          - echo $AWS_ACCOUNT_ID
          - echo $IMAGE_REPO_NAME
          - echo $IMAGE_TAG
          - echo $LAMBDA_NAME
      build:
        commands:
          - cd container
          - aws ecr get-login-password --region $AWS_DEFAULT_REGION | docker login --username AWS --password-stdin $AWS_ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com
          - docker build -t $IMAGE_REPO_NAME:$IMAGE_TAG .
          - docker tag $IMAGE_REPO_NAME:$IMAGE_TAG $AWS_ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com/$IMAGE_REPO_NAME:$IMAGE_TAG
          - docker push $AWS_ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com/$IMAGE_REPO_NAME:$IMAGE_TAG
          - cd ..
          #- echo skip build section
      post_build:
        commands:
          - aws lambda update-function-code --function-name $LAMBDA_NAME --image-uri $AWS_ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com/$IMAGE_REPO_NAME:$IMAGE_TAG --publish
    

    만약 v.3 로 업데이트한다고 할 때 이미지 빌드 후 ECR에 푸시되고 aws cli 를 통해 이미지 uri 로 접근하여 publish 하게 됨

    2.3 codebuild project

    # service role
    {
    	"Version": "2012-10-17",
    	"Statement": [
    		{
    			"Sid": "VisualEditor0",
    			"Effect": "Allow",
    			"Action": [
    				"lambda:*",
    				"ecr:BatchGetImage",
    				"ecr:CompleteLayerUpload",
    				"ecr:UploadLayerPart",
    				"ecr:InitiateLayerUpload",
    				"ecr:BatchCheckLayerAvailability",
    				"ecr:PutImage"
    			],
    			"Resource": [
    				"arn:aws:lambda:ap-northeast-2:501587125031:function:test-target-lambda",
    				"arn:aws:ecr:ap-northeast-2:501587125031:repository/test-awscli-update-lambda-image"
    			]
    		},
    		{
    			"Sid": "VisualEditor1",
    			"Effect": "Allow",
    			"Action": [
    				"lambda:ListFunctions",
    				"lambda:ListEventSourceMappings",
    				"ecr:GetAuthorizationToken",
    				"lambda:ListLayerVersions",
    				"lambda:ListLayers",
    				"lambda:GetAccountSettings",
    				"lambda:CreateEventSourceMapping",
    				"lambda:ListCodeSigningConfigs",
    				"lambda:CreateCodeSigningConfig"
    			],
    			"Resource": "*"
    		}
    	]
    }
    

     

    3. 확인

    # codecommit push
    $ git add .
    $ git commit -m "deploy new version"
    [main 165aa33] deploy new version
     5 files changed, 54 insertions(+), 1 deletion(-)
     create mode 100644 buildspec.yml
     create mode 100644 container/Dockerfile
     create mode 100644 container/build-commands.sh
     create mode 100644 container/lambda_function.py
     delete mode 100644 demo.txt
    $ git push
    Enumerating objects: 8, done.
    Counting objects: 100% (8/8), done.
    Delta compression using up to 4 threads
    Compressing objects: 100% (7/7), done.
    Writing objects: 100% (7/7), 1.30 KiB | 221.00 KiB/s, done.
    Total 7 (delta 0), reused 0 (delta 0), pack-reused 0
    remote: Validating objects: 100%
    To <https://git-codecommit.ap-northeast-2.amazonaws.com/v1/repos/test-awscli>
       14787c1..165aa33  main -> main
    

     

    build 결과
    ECR 생성 확인
    버전 변경 확인
    테스트 결과 확인

    참고

    https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/update-function-code.html

     

    update-function-code — AWS CLI 2.13.9 Command Reference

    The size of the function’s /tmp directory in MB. The default value is 512, but it can be any whole number between 512 and 10,240 MB. Size -> (integer) The size of the function’s /tmp directory.

    awscli.amazonaws.com

     

    'AWS > CI CD' 카테고리의 다른 글

    AWS CodeBuild - DOWNLOAD_SOURCE 단계 dial tcp i/o timeout Error  (0) 2024.07.13
    AWS CodeBuild - push to Github  (0) 2023.08.10
    AWS CodeBuild demo with ECR  (0) 2023.08.10
    AWS CodeCommit demo  (0) 2023.08.09