0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Code Pipeline向けバケットファイル削除用Lambda関数(python)

Last updated at Posted at 2025-06-08

「S3+API Gateway+Lambdaを利用した簡易Webアプリケーション自動化」の内容について、
静的ウェブサイトホスティングを設定したバケットにlambda用のpythonファイルが残っていた

なので以下lambda関数を作成して、Code Pipelineの最後にlambdaを呼び出すことで対応

import boto3

def lambda_handler(event, context):
    s3 = boto3.client('s3')
    codepipeline = boto3.client('codepipeline')

    bucket_name = 'cc-source-bucket-0531'
    key_to_delete = 'lambda_function.py'

    try:
        s3.delete_object(Bucket=bucket_name, Key=key_to_delete)

        # Pipeline に成功を通知
        job_id = event['CodePipeline.job']['id']
        codepipeline.put_job_success_result(jobId=job_id)

    except Exception as e:
        # 失敗時は明示的にエラー通知
        job_id = event['CodePipeline.job']['id']
        codepipeline.put_job_failure_result(
            jobId=job_id,
            failureDetails={
                'message': str(e),
                'type': 'JobFailed',
                'externalExecutionId': context.aws_request_id
            }
        )
        raise

image.png

関数は単に削除処理をするだけだと、Code Pipeline側の処理がいつまで待っても完了にならないので
上記のようにCode Pipelineの処理に対してjobの成功を通知する必要がある。

Code Pipeline側に通知をする必要がある関係上、関数のIAMに以下の許可も必要
今回はAWS管理ポリシーのAWSCodePipelineCustomActionAccessをアタッチして対応した

                "codepipeline:PutJobFailureResult",
                "codepipeline:PutJobSuccessResult"

なお、codebuildのbuildspec.ymlに以下のようにsecondary-artifactsを設定すれば
アーティファクトを複数出力させられる

secondary-artifacts:
  LambdaArtifact:
    files:
      - lambda_function.py
  S3Artifact:
    files:
      - index.html

そのため、S3用とlambda用でアーティファクトを分ければ削除処理は不要ではと思い検証したが、
2つ目に設定した出力アーティファクトのみうまく出力されず

※ 以下の様にするとLambdaArtifactの分だけがパイプラインが作成するバケットに出力されない

image.png

設定不足があったのか調べたがすぐには特定できなさそうなので一旦削除用のlambdaを作成して対応

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?