Open1

Automate AWS Lambda deployment with GitHub Actions

nyancatnyancat

https://dev.classmethod.jp/articles/lambda-github-actions/
https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/configuring-openid-connect-in-amazon-web-services
https://github.com/aws-actions/configure-aws-credentials

  • IAM > Identity providers
    • OpenID Connect
    • Provider URL https://token.actions.githubusercontent.com
    • Audience sts.amazonaws.com
  • IAM Policy
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "lambda:UpdateFunctionCode",
            "Resource": "[lambda arn]"
        }
    ]
}
  • IAM Role
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "Federated": "[token.actions.githubusercontent.com path]"
            },
            "Action": "sts:AssumeRoleWithWebIdentity",
            "Condition": {
                "StringEquals": {
                    "token.actions.githubusercontent.com:sub": "repo:[organization name]/[repository name]:ref:refs/heads/[branch name]",
                    "token.actions.githubusercontent.com:aud": "sts.amazonaws.com"
                }
            }
        }
    ]
}
  • GitHub Actions secrets

    • AWS_ROLE_ARN
  • GitHub Actions

name: Deploy AWS Lambda

on:
  push:
    branches:
      - main
    paths:
      - '[app code directory path]/**.py'

jobs:
  deploy:
    runs-on: ubuntu-latest
    permissions:
      id-token: write
      contents: read

    steps:
    - name: Checkout repository
      uses: actions/checkout@v4

    - name: Configure aws credentials
      uses: aws-actions/configure-aws-credentials@v4
      with:
        aws-region: [AWS region]
        role-to-assume: ${{ secrets.AWS_ROLE_ARN }}
        role-session-name: GitHubActions

    - name: get-caller-identity is allowed to run on role.
      run: aws sts get-caller-identity

    - name: Set up Python
      uses: actions/setup-python@v5
      with:
        python-version: 3.12

    - name: Create a zip package
      run: |
        python -m pip install --upgrade pip
        cd [app code directory path]
        mkdir package
        pip install --target ./package [libraries]
        cd package
        zip -r ../package.zip .
        cd ..
        zip package.zip *.py

    - name: Deploy to AWS Lambda
      run: |
        aws lambda update-function-code --function-name [AWS lambda name] --zip-file fileb://[app code directory path]/package.zip --publish