概要
GitHub ActionsからAWS CodeBuildをキックする方法を示す。
背景
- すでにCodeBuildプロジェクトの資産がある
- GitHubと連携しており、CodeBuildの結果をAWSコンソールを開いて確認するのが手間
結論
下記のようにして実装した。
RoleとCodeBuildプロジェクトをinputsとして渡すことで汎用的にした。
使っている技術
hoge/.github/workflows/my-workflow.yml
name: my workflow
on:
pull_request:
jobs:
call-workflow-run-code-build:
permissions:
id-token: write
contents: read
uses: tom-256/my-workflow/.github/workflows/run-codebuild.yml@main
with:
roleToAssume: arn:aws:iam::<ACCOUNT_ID>:role/aws-codebuild-run-build-role
codeBuildProjectName: my-codebuild-project
Roleは用途に合わせ適宜権限を絞る。
my-workflow/.github/workflows/run-codebuild.yml@main
name: run codebuild
on:
workflow_call:
inputs:
codeBuildProjectName:
required: true
type: string
roleToAssume:
required: true
type: string
jobs:
run-code-build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Configure AWS credentials
uses: aws-actions/configure-aws-credentials@v1
with:
role-to-assume: ${{ inputs.roleToAssume }}
aws-region: ap-northeast-1
- name: Run CodeBuild
uses: aws-actions/aws-codebuild-run-build@v1
with:
project-name: ${{ inputs.codeBuildProjectName }}
aws-codebuild-run-build-roleのポリシー
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "",
"Effect": "Allow",
"Action": [
"codebuild:StartBuild",
"codebuild:BatchGetBuilds"
],
"Resource": "arn:aws:codebuild:ap-northeast-1:<ACCOUNT_ID>:project/<CODEBUILD_PROJECT_NAME>"
},
{
"Sid": "",
"Effect": "Allow",
"Action": "logs:GetLogEvents",
"Resource": "arn:aws:logs:ap-northeast-1:<ACCOUNT_ID>:log-group:/aws/codebuild/<LOG_GROUP_NAME>/:log-stream:<LOG_STREAM_NAME>/*"
}
]
}
aws-codebuild-run-build-roleのTrusted entities
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "",
"Effect": "Allow",
"Principal": {
"Federated": "arn:aws:iam::<ACCOUNT_ID>:oidc-provider/token.actions.githubusercontent.com"
},
"Action": "sts:AssumeRoleWithWebIdentity",
"Condition": {
"StringLike": {
"token.actions.githubusercontent.com:sub": "repo:<ORG>/*:*"
}
}
}
]
}
"repo:<ORG>/*:*"
の箇所はreusable workflowを使ったのでワイルドカードを指定することで特定のリポジトリによらず利用できる。
GitHub ActionsのTips
これらを書くときに知ったGitHub ActionsのTips
- permissionはreusable workflowの呼び出し先にも適用される
https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#permissions
下記のようなエラーが出る
invalid value workflow reference: workflows must be defined at the top level of the .github/workflows/ directory
まとめ