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?

More than 1 year has passed since last update.

AWS CLIでGitHub ActionsのIAMロールを作成しよう

Last updated at Posted at 2023-06-21

はじめに

AWS CLIを利用して、GitHub ActionsのOIDCプロバイダとIAMロールを構築する。

スクリプト

  1. OIDCプロバイダを作成する

    # OIDC Provider 作成
    OIDC_NAME=token.actions.githubusercontent.com
    THUMBPRINT=6938fd4d98bab03faadb97b34396831e3780aea1
    
    aws iam create-open-id-connect-provider \
      --url https://${OIDC_NAME} \
      --client-id-list sts.amazonaws.com \
      --thumbprint-list ${THUMBPRINT}
    
  2. IAMロールを作成する

    # GitHub Actions Role 作成
    REPOGITORY_NAME=${リポジトリ名}
    ROLE_NAME=role-github-actions-infra
    
    OIDC_ARN=$(aws iam list-open-id-connect-providers \
        --query "OpenIDConnectProviderList[*].Arn" \
        --output text | grep ${OIDC_NAME}
    )
    
    ROLE_POLICY=$(echo -n '{
        "Version": "2012-10-17",
        "Statement": [
            {
                "Effect": "Allow",
                "Principal": {
                    "Federated": "'; echo -n "${OIDC_ARN}"; echo -n '"
                },
                "Action": "sts:AssumeRoleWithWebIdentity",
                "Condition": {
                    "StringEquals": {
                        "'; echo -n "${OIDC_NAME}"; echo -n ':aud": "sts.amazonaws.com"
                    },
                    "StringLike": {
                        "'; echo -n "${OIDC_NAME}"; echo -n ':sub": "repo:'; echo -n "${REPOGITORY_NAME}"; echo -n '*"
                    }
                }
            }
        ]
    }')
    
    aws iam create-role \
      --role-name ${ROLE_NAME} \
      --assume-role-policy-document "${ROLE_POLICY}"
    
    aws iam attach-role-policy \
      --role-name ${ROLE_NAME} \
      --policy-arn arn:aws:iam::aws:policy/AdministratorAccess
    

クリーンアップ

  1. ポリシーをロールからデタッチする

    ROLE_NAME=role-github-actions-infra
    
    aws iam detach-role-policy \
      --role-name ${ROLE_NAME} \
      --policy-arn arn:aws:iam::aws:policy/AdministratorAccess
    
  2. IAMロールを削除する

    ROLE_NAME=role-github-actions-infra
    
    aws iam delete-role \
      --role-name ${ROLE_NAME}
    
  3. OIDCプロバイダを削除する

    OIDC_ARN=$(aws iam list-open-id-connect-providers \
        --query "OpenIDConnectProviderList[*].Arn" \
        --output text | grep ${OIDC_NAME}
    )
    
    aws iam delete-open-id-connect-provider \
      --open-id-connect-provider-arne ${OIDC_ARN}
    
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?