Closed5

Terraform を GitHub Actions から OIDC で認証して利用する

snakasnaka

AWS 側: 信頼(Trust)の設定

OIDC Identity Provider

https://docs.aws.amazon.com/ja_jp/IAM/latest/UserGuide/id_roles_providers_create_oidc.html

  • provider URL: https://app.terraform.io
  • audience: aws.workload.identity <- TFC_AWS_WORKLOAD_IDENTITY_AUDIENCE と合わせる ( default が左記の値となっているので変更なければそのまま )

Role and Trust Policy

https://docs.aws.amazon.com/ja_jp/IAM/latest/UserGuide/id_roles_create_for-idp_oidc.html

Trust Policy: Role の利用を許可する Terraform Cloud 側の情報を登録する

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "Federated": "<OIDC_PROVIDER_ARN>"
            },
            "Action": "sts:AssumeRoleWithWebIdentity",
            "Condition": {
                "StringEquals": {
                    "app.terraform.io:aud": "aws.workload.identity"
                },
                "StringLike": {
                    "app.terraform.io:sub": "organization:<ORG_NAME>:project:<PROJECT_NAME>:workspace:<WORKSPACE_NAME>:run_phase:*"
                }
            }
        }
    ]
}

Permission Policy: Role に許可するアクションを設定する

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "s3:ListBucket"
            ],
            "Resource": "*"
        }
    ]
}
snakasnaka

サンプルの Permission Policy

{
    "Statement": [
        {
            "Action": [
                "ec2:*",
                "elasticloadbalancing:*",
                "ecs:*",
                "logs:*",
                "iam:CreateRole",
                "iam:GetRole",
                "iam:TagRole",
                "iam:ListRolePolicies",
                "iam:ListAttachedRolePolicies",
                "iam:ListInstanceProfilesForRole",
                "iam:DeleteRole",
                "iam:AttachRolePolicy",
                "iam:PutRolePolicy",
                "iam:DeleteRolePolicy",
                "iam:DetachRolePolicy",
                "iam:GetRolePolicy"
            ],
            "Effect": "Allow",
            "Resource": "*"
        }
    ],
    "Version": "2012-10-17"
}
snakasnaka

Terraform Cloud 側の設定

Workspace の設定 > Variables で環境変数を設定する

  • TFC_AWS_PROVIDER_AUTH : true
  • TFC_AWS_RUN_ROLE_ARN : ( 上で追加した IAM Role の ARN )

Terraform Cloud > Workspace > Settings > Variables:

このスクラップは2023/11/29にクローズされました