LoginSignup
5
3

GitHub Actions から AWS へアクセスする

Last updated at Posted at 2022-09-06

AWS にアップロードしたりデプロイしたりするには、IAM の認証情報が必要になります。GitHub Actions のワークフローで認証情報を設定する方法です。

固定キーを使う

参照) Deploying using GitHub Actions

IAM ユーザーを作成し、アクセスキーを Action secrets の AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY に設定しておきます。ワークフローからは Configure AWS Credentials アクションを使用して、この認証情報を使用します。

steps:
  - uses: aws-actions/configure-aws-credentials@v4
    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 ロールによる一時的な認証情報を使用したい場合、GitHub を IdP プロバイダとして連携します。

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

  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 一覧

Actions から使用したい IAM ロールには、Trusted entities (信頼関係) を以下のように指定しておきます。(管理コンソールから IAM ロール作成する場合は「Trusted entity type」に「Web identity」を選択して必要な項目を入力すれば、下記のように初期設定されます。)

⚠︎Condition ステートメントに記述したリポジトリからのみ、この IAM ロールを使用できます。関係ないリポジトリから使われないよう、注意しましょう。

{
    "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/*"
                }
            }
        }
    ]
}

ワークフローから Configure AWS Credentials アクションを使用して、以下の記述でこの IAM ロールから認証情報を取得することができます。

permissions:
  id-token: write
  contents: read

steps:
  - uses: aws-actions/configure-aws-credentials@v4
    with:
      role-to-assume: (ロールの ARN)
      aws-region: ap-northeast-1
5
3
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
5
3