LoginSignup
0
0

Terraform Cloud+GitHub Actions+AzureのIaCパイプラインを構築する

Posted at

はじめに

Hashicorp公式ドキュメントのチュートリアル(Terraform Cloud+GitHub Actions)の構成を、Azureでやってみた。(ドキュメントではAWSを管理対象としている。)

  • ワークフロー
    1. 各branchへコミットされるとterraform planが走ってCloud上で結果を確認できる
    2. mainブランチが更新されるとterrafrom applyされてリソースが変更される

image.png

構築

GitHubにリポジトリを作成

Terraform Cloudと連携させる用のリポジトリを作成しておく。
今回は面倒なので、providerブロックの中にサービスプリンシパルのシークレットを埋め込んだ。

main.tf
terraform {
  required_version = ">=0.12"

  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = "~>2.0"
    }
  }
}

provider "azurerm" {
  features {}

  subscription_id   = "xxxx"
  tenant_id         = "xxxx"
  client_id         = "xxxx"
  client_secret     = "xxxx"
}

(以下リソース定義)

Terraform Cloudでワークスペースを作成

Projects & workspacesページから新しいワークスペースを作成する。
API-driven workflowを選択し、次のページではワークスペースの名前を付けて作成。
110700 (2).png
110719 (2).png

User Settings>Tokensページでcreate an API tokenをし、適当な名前を付けてGitHubと連携するためのトークンを生成する。
シークレットは生成されたタイミングしか表示できないので、メモ帳にコピーしておく。
112326 (2).png

GitHubでトークン文字列を設定

リポジトリの設定ページから Secrets and variables>actionsに移動し、New repository secretをする。
キーはTF_API_TOKENとして、コピーしておいたシークレットを登録する。

114948 (2).png

GitHub Actionsのワークフローを定義

リポジトリに.github/workflowsフォルダを作成し、中にymlファイルを置いていく。
今回は公式チュートリアルのリポジトリを参考に、terraform-plan.ymlとterraform-apply.ymlを必要なところだけ修正していく。(envブロックとjobsブロックだけ修正すれば動く)

terraform-plan.yml / terraform-apply.yml
(省略)

env:
  TF_CLOUD_ORGANIZATION: "xxxxx" #Terraform CloudのOrganization名
  TF_API_TOKEN: "${{ secrets.TF_API_TOKEN }}"
  TF_WORKSPACE: "avd_example_api-driven" #API-Drivenのワークスペース名
  CONFIG_DIRECTORY: "./"

jobs:
  terraform:
    name: "Terraform Apply"
    runs-on: ubuntu-latest
(省略)

テスト

作業用ブランチを作成して、GitHubにpushする。

$ git checkout -b 'update-tfc-org'
$ git push origin update-tfc-org

GitHub上でupdate-tfc-orgブランチからmainブランチにプルリクエストを作成する。
GitHub ActionsでTerraform planの実行結果が表示される。
123318 (3).png

Terraform Cloud Planのリンクを飛ぶと変更の詳細を確認できる。
image.png

mainブランチにマージするとApplyされ、リソースが作成される。
123446 (2).png

参考

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