From bc6c6aa3ad982064f35e7d4d194685a475eb80a7 Mon Sep 17 00:00:00 2001 From: Kouji Takao Date: Sat, 20 Sep 2025 18:16:39 +0900 Subject: [PATCH 1/2] feat: enable automatic deployment in CI/CD pipeline MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Enable automatic deployment to production when changes are pushed to main branch. Manual deployment testing has been completed successfully, so it's safe to enable automated deployment in GitHub Actions. Changes: - Uncomment and activate deploy job in GitHub Actions workflow - Add sam build step before deployment for clean builds - Add deployment outputs display for visibility - Configure production environment protection - Use --resolve-s3 flag for automatic S3 bucket management Deployment will trigger on: - Push to main branch - After successful lint, test, and SAM template validation - Requires AWS credentials configured in GitHub secrets 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude --- .github/workflows/ci-cd.yml | 78 ++++++++++++++++++++++--------------- 1 file changed, 46 insertions(+), 32 deletions(-) diff --git a/.github/workflows/ci-cd.yml b/.github/workflows/ci-cd.yml index 6ca9b7b..cd5c681 100644 --- a/.github/workflows/ci-cd.yml +++ b/.github/workflows/ci-cd.yml @@ -69,35 +69,49 @@ jobs: path: .aws-sam/ retention-days: 7 - # Deploy job is temporarily disabled for initial testing - # Will be enabled after manual deployment verification - # deploy: - # runs-on: ubuntu-latest - # needs: [lint-and-test, validate-sam-template] - # if: github.ref == 'refs/heads/main' && github.event_name == 'push' - # environment: production - # steps: - # - name: Checkout code - # uses: actions/checkout@v4 - # - name: Set up Ruby - # uses: ruby/setup-ruby@v1 - # with: - # ruby-version: '3.3' - # bundler-cache: true - # - name: Set up AWS SAM CLI - # uses: aws-actions/setup-sam@v2 - # - name: Configure AWS credentials - # 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 - # - name: Deploy to AWS - # run: | - # sam deploy \ - # --template-file .aws-sam/build/template.yaml \ - # --stack-name smalruby-infra-prod \ - # --parameter-overrides Stage=prod \ - # --capabilities CAPABILITY_IAM \ - # --no-confirm-changeset \ - # --no-fail-on-empty-changeset \ No newline at end of file + deploy: + runs-on: ubuntu-latest + needs: [lint-and-test, validate-sam-template] + if: github.ref == 'refs/heads/main' && github.event_name == 'push' + environment: production + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Set up Ruby + uses: ruby/setup-ruby@v1 + with: + ruby-version: '3.3' + bundler-cache: true + + - name: Set up AWS SAM CLI + uses: aws-actions/setup-sam@v2 + + - name: Configure AWS credentials + 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 + + - name: Build SAM application + run: sam build --template template.yaml + + - name: Deploy to AWS + run: | + sam deploy \ + --template-file .aws-sam/build/template.yaml \ + --stack-name smalruby-infra-prod \ + --parameter-overrides Stage=prod \ + --capabilities CAPABILITY_IAM \ + --resolve-s3 \ + --no-confirm-changeset \ + --no-fail-on-empty-changeset + + - name: Get deployment outputs + run: | + echo "=== Deployment Outputs ===" + aws cloudformation describe-stacks \ + --stack-name smalruby-infra-prod \ + --query 'Stacks[0].Outputs[*].{Key:OutputKey,Value:OutputValue}' \ + --output table \ No newline at end of file From 9974c404ca948cae77bfeb52a34b464931063e6d Mon Sep 17 00:00:00 2001 From: Kouji Takao Date: Sat, 20 Sep 2025 18:20:17 +0900 Subject: [PATCH 2/2] feat: migrate to OIDC authentication for GitHub Actions MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Replace long-lived AWS credentials with OIDC (OpenID Connect) for enhanced security. This eliminates the need to store AWS access keys in GitHub secrets and provides short-lived, automatically rotated tokens. Changes: - Update ci-cd.yml to use role-to-assume instead of access keys - Add required permissions (id-token: write, contents: read) - Create comprehensive OIDC setup documentation in Japanese - Configure role session name for better CloudTrail logging Security improvements: - No long-lived credentials stored in GitHub - Automatic token rotation - Access restricted to specific repository and branch - Enhanced audit logging with session names Setup required: 1. Create AWS OIDC Identity Provider 2. Create IAM role with appropriate permissions 3. Add AWS_ROLE_ARN to GitHub secrets See OIDC_SETUP.md for detailed setup instructions. 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude --- .github/workflows/ci-cd.yml | 7 +- OIDC_SETUP.md | 231 ++++++++++++++++++++++++++++++++++++ 2 files changed, 236 insertions(+), 2 deletions(-) create mode 100644 OIDC_SETUP.md diff --git a/.github/workflows/ci-cd.yml b/.github/workflows/ci-cd.yml index cd5c681..b091ce4 100644 --- a/.github/workflows/ci-cd.yml +++ b/.github/workflows/ci-cd.yml @@ -74,6 +74,9 @@ jobs: needs: [lint-and-test, validate-sam-template] if: github.ref == 'refs/heads/main' && github.event_name == 'push' environment: production + permissions: + id-token: write + contents: read steps: - name: Checkout code uses: actions/checkout@v4 @@ -90,8 +93,8 @@ jobs: - name: Configure AWS credentials 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 }} + role-to-assume: ${{ secrets.AWS_ROLE_ARN }} + role-session-name: GitHubActions-smalruby-infra-deploy aws-region: ap-northeast-1 - name: Build SAM application diff --git a/OIDC_SETUP.md b/OIDC_SETUP.md new file mode 100644 index 0000000..625ccf9 --- /dev/null +++ b/OIDC_SETUP.md @@ -0,0 +1,231 @@ +# GitHub Actions用AWS OIDC設定手順 + +## 概要 + +GitHub ActionsからAWSリソースにアクセスする際、従来のIAMユーザーのアクセスキー・シークレットキーの代わりに、OIDC(OpenID Connect)を使用した一時的な認証を行う設定手順です。 + +これにより以下の利点があります: +- **セキュリティ向上**: 長期間有効なクレデンシャルを保存する必要がない +- **自動ローテーション**: トークンは短期間で自動的に無効化される +- **最小権限原則**: 特定のリポジトリ・ブランチからのみアクセス可能 + +## 手順1: AWS Identity Provider(OIDC)の作成 + +### 1.1 AWSマネジメントコンソールにログイン +- IAM サービスに移動 + +### 1.2 Identity Provider作成 +1. **左メニュー「Identity providers」をクリック** +2. **「Add provider」ボタンをクリック** +3. **Provider type**: 「OpenID Connect」を選択 +4. **Provider URL**: `https://token.actions.githubusercontent.com` を入力 +5. **Audience**: `sts.amazonaws.com` を入力 +6. **「Get thumbprint」をクリック**して証明書のサムプリントを取得 +7. **「Add provider」をクリック** + +## 手順2: IAMロールの作成 + +### 2.1 新しいロール作成 +1. **IAM → Roles → 「Create role」** +2. **Trusted entity type**: 「Web identity」を選択 +3. **Identity provider**: 先ほど作成したGitHub OIDCプロバイダーを選択 +4. **Audience**: `sts.amazonaws.com` を選択 + +### 2.2 信頼関係の設定 +**「Next」をクリック後、信頼関係を以下のように設定:** + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Principal": { + "Federated": "arn:aws:iam::007325983811:oidc-provider/token.actions.githubusercontent.com" + }, + "Action": "sts:AssumeRole", + "Condition": { + "StringEquals": { + "token.actions.githubusercontent.com:aud": "sts.amazonaws.com" + }, + "StringLike": { + "token.actions.githubusercontent.com:sub": "repo:smalruby/smalruby-infra:ref:refs/heads/main" + } + } + } + ] +} +``` + +**重要**: `007325983811` は実際のAWSアカウントIDに置き換えてください。 + +### 2.3 権限ポリシーの追加 +デプロイに必要な権限を持つポリシーを添付します: + +#### 2.3.1 Lambda関数管理権限 +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": [ + "lambda:CreateFunction", + "lambda:UpdateFunctionCode", + "lambda:UpdateFunctionConfiguration", + "lambda:DeleteFunction", + "lambda:GetFunction", + "lambda:ListFunctions", + "lambda:AddPermission", + "lambda:RemovePermission" + ], + "Resource": "*" + } + ] +} +``` + +#### 2.3.2 API Gateway管理権限 +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": [ + "apigateway:*" + ], + "Resource": "*" + } + ] +} +``` + +#### 2.3.3 CloudFormation管理権限 +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": [ + "cloudformation:CreateStack", + "cloudformation:UpdateStack", + "cloudformation:DeleteStack", + "cloudformation:DescribeStacks", + "cloudformation:DescribeStackEvents", + "cloudformation:DescribeStackResources", + "cloudformation:GetTemplate", + "cloudformation:ValidateTemplate", + "cloudformation:CreateChangeSet", + "cloudformation:DescribeChangeSet", + "cloudformation:ExecuteChangeSet", + "cloudformation:DeleteChangeSet" + ], + "Resource": "*" + } + ] +} +``` + +#### 2.3.4 S3とIAM権限 +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": [ + "s3:CreateBucket", + "s3:DeleteBucket", + "s3:GetObject", + "s3:PutObject", + "s3:DeleteObject", + "s3:ListBucket", + "s3:GetBucketLocation", + "s3:GetBucketVersioning", + "s3:PutBucketVersioning" + ], + "Resource": [ + "arn:aws:s3:::aws-sam-cli-managed-default-samclisourcebucket-*", + "arn:aws:s3:::aws-sam-cli-managed-default-samclisourcebucket-*/*" + ] + }, + { + "Effect": "Allow", + "Action": [ + "iam:CreateRole", + "iam:DeleteRole", + "iam:GetRole", + "iam:PassRole", + "iam:AttachRolePolicy", + "iam:DetachRolePolicy", + "iam:CreatePolicy", + "iam:DeletePolicy", + "iam:GetPolicy" + ], + "Resource": "*" + } + ] +} +``` + +### 2.4 ロール名設定 +- **Role name**: `GitHubActions-smalruby-infra-deploy` (推奨) +- **Description**: `Role for GitHub Actions to deploy smalruby infrastructure` + +### 2.5 ロール作成完了 +「Create role」をクリックしてロールを作成します。 + +## 手順3: GitHub Secretsの設定 + +### 3.1 リポジトリのSecrets設定 +1. **GitHubリポジトリ「smalruby/smalruby-infra」に移動** +2. **Settings → Secrets and variables → Actions** +3. **「New repository secret」をクリック** + +### 3.2 必要なSecret +以下のSecretを追加: + +| Secret名 | 値 | 説明 | +|----------|---|------| +| `AWS_ROLE_ARN` | `arn:aws:iam::007325983811:role/GitHubActions-smalruby-infra-deploy` | 作成したIAMロールのARN | + +**注意**: `007325983811` は実際のAWSアカウントIDに置き換えてください。 + +### 3.3 従来のSecretsの削除(推奨) +OIDCが正常に動作することを確認後、以下の従来のSecretsは削除できます: +- `AWS_ACCESS_KEY_ID` +- `AWS_SECRET_ACCESS_KEY` + +## 手順4: デプロイテスト + +### 4.1 GitHub Actionsの実行 +mainブランチにpushしてGitHub Actionsが正常に実行されることを確認します。 + +### 4.2 ログの確認 +GitHub Actions実行ログで以下を確認: +- OIDC認証が成功している +- AWS CLIコマンドが正常に実行されている +- デプロイが完了している + +## 設定完了後の利点 + +✅ **セキュリティ向上**: 長期クレデンシャルの漏洩リスクなし +✅ **自動管理**: トークンの自動ローテーション +✅ **アクセス制御**: 特定リポジトリ・ブランチからのみアクセス可能 +✅ **監査**: CloudTrailでアクセスログが記録される + +## トラブルシューティング + +### エラー例1: "AssumeRoleFailure" +**原因**: 信頼関係の設定が正しくない +**対処**: ロールの信頼関係でリポジトリ名・ブランチ名を確認 + +### エラー例2: "Access Denied" +**原因**: ロールに必要な権限がない +**対処**: ロールに適切なポリシーが添付されているか確認 + +### エラー例3: "Invalid identity token" +**原因**: GitHub Actionsの設定が正しくない +**対処**: `permissions`セクションに`id-token: write`があるか確認 \ No newline at end of file