コンテンツにスキップ

GitHub Actions: AWS へアクセスする

GitHub Actions から AWS にアップロードしたりデプロイしたり。

固定キー

参照) Deploying using GitHub Actions

Configure AWS Credentials アクションでアクセスキーを設定します。

steps:
  - uses: aws-actions/configure-aws-credentials@v1
    with:
      aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
      aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
      aws-region: ap-northeast-1

IAM Roles for Service Accounts

固定のアクセスキーではなく、IAM ロールに AssumeRole したい場合。

参考) https://dev.classmethod.jp/articles/github-actions-aws-sts-credentials-iamrole/

permissions:
  id-token: write
  contents: read

steps:
  - uses: aws-actions/configure-aws-credentials@v1
    with:
      role-to-assume: (ロールの ARN)
      aws-region: ap-northeast-1

GitHub Actions から AssumeRole するには、以下の手順で GitHub を IdP として登録し、IAM ロールにそこから AssumeRole できるよう許可を与えておく必要があります。

GitHub を IdP として登録

  1. IAM > Identity providers > Add provider
  2. 以下指定して Add provider - Provider type: OpenID Connect - Provider URL: https://token.actions.githubusercontent.com (*1) ※入力して Get thumbprint を押す - Audience: sts.amazonaws.com

(*1) GitHub Enterprise Server の場合は、https://HOSTNAME/_services/token と入力します。

Identity providers 一覧

IAM ロールの Trusted entities

IAM ロール作成時、「Trusted entity type」に「Web identity > 作成した Identity provider」を選択して作成すると、Trusted entities は以下のようになります。

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "Federated": "arn:aws:iam::(アカウントID):oidc-provider/token.actions.githubusercontent.com"
            },
            "Action": "sts:AssumeRoleWithWebIdentity",
            "Condition": {
                "StringEquals": {
                    "token.actions.githubusercontent.com:aud": "sts.amazonaws.com"
                }
            }
        }
    ]
}

このままだと全リポジトリに対して許可してしまうので、Condition に特定のリポジトリだけを許可する形にします。

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "Federated": "arn:aws:iam::(アカウントID):oidc-provider/token.actions.githubusercontent.com"
            },
            "Action": "sts:AssumeRoleWithWebIdentity",
            "Condition": {
                "StringEquals": {
                    "token.actions.githubusercontent.com:aud": "sts.amazonaws.com"
                },
                "StringLike": {
                    "token.actions.githubusercontent.com:sub": "repo:yh1224/*:*"
                }
            }
        }
    ]
}