10
3

More than 1 year has passed since last update.

GitHub ActionsでTerraformのplanなどを検証する

Last updated at Posted at 2023-03-26

terraform plan などをGitHub Actionsで実行する方法を紹介します。
AWSリソースを扱う場合、stepを追加する必要もあるので、そちらを併せて紹介できたらと思います。

はじめに

筆者のTerraform のリポジトリのディレクトリ構造は下記のようになっています。

.
├── .github
│   └── workflows
│       └── test_terraform.yml # これを扱います
├── .gitignore
├── docker-compose.yml
└── src
    ├── .terraform/
    ├── .terraform.lock.hcl
    ├── module_aws.tf
    ├── modules
    │   └── aws/ # この配下にresource などを記載したファイルを置いている
    └── providers.tf

GitHub Actionsのworlflow を作成する

.github/workflows/test_terraform.yml
name: Terraform test

on:
  pull_request:
    types: [opened, synchronize, reopened, ready_for_review]

jobs:
  terraform_test:
    runs-on: ubuntu-latest
    timeout-minutes: 10
    steps:
      - uses: actions/checkout@v3
      - name: configure AWS credentials
        uses: aws-actions/configure-aws-credentials@v2
        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: terraform setup
        uses: hashicorp/setup-terraform@v2
        with:
          terraform_version: 1.4.2
      - name: Terraform fmt
        id: fmt
        run: terraform fmt -check
        continue-on-error: true
        working-directory: ./src
      - name: Terraform Init
        id: init
        run: terraform init
        working-directory: ./src
      - name: Terraform Validate
        id: validate
        run: terraform validate -no-color
        working-directory: ./src
      - name: Terraform Plan
        id: plan
        run: terraform plan -no-color
        continue-on-error: true
        working-directory: ./src

workflowは、terraformのfmtvalidateplan、そしてそれらを実行するためのinit を実行しています。
.ymlファイルを簡単に解説します。

  • on
    • workflowを実行するタイミングを設定しています。
    • 今回の場合、Pull Requestの作成、更新、reopen、DraftからReady for reviewに変更された時にworkflowが実行されます。
on:
  pull_request:
    types: [opened, synchronize, reopened, ready_for_review]
  • uses: actions/checkout@v3
    • GitHub公式に提供されているActionになります。
    • check outを実施して、workflowでアクセスすることができるようになります
  • uses: aws-actions/configure-aws-credentials@v2
    • 筆者の環境では、AWSのリソースを利用しているため、credential設定が必要でした
    • こちらはAWSよりActionが提供されています
      • これにより、AWSの認証情報とリージョン環境変数を設定し、他のアクションでを利用することができます。
      • (今回はsecretsでAWSのアクセスキーを渡していますが、外部にキーを渡しているため、role-to-assumeなどを利用する方がよさそうです。参考)
  • uses: hashicorp/setup-terraform@v2
    • Action内でTerraform 利用に必要な設定を行なっています。
      • 引数でterraform_version を渡します。自分の使っているTerraform のバージョンと合わせましょう。

公式で提供しているActionを組み合わせることで、手軽に作ることができました。
次は、planの結果の出力などをやってみたいと思います。

10
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
10
3