Terratest使う

TerraformのテストコードをGo言語で書けるものらしい
面白そうなので使ってみる
terratest.gruntwork.io



main.tf

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 4.16"
    }
  }

  required_version = ">= 1.2.0"
}

provider "aws" {
  region  = "ap-northeast-1"
}

resource "aws_s3_bucket" "b" {
  bucket = "usualmoon3700-terratest"

  tags = {
    Name        = "My bucket"
    Environment = "Dev"
  }
}

terraform_test.go

package test

import (
	"testing"

	"github.com/gruntwork-io/terratest/modules/aws"
	"github.com/gruntwork-io/terratest/modules/terraform"
)

func TestTerraform(t *testing.T) {
	terraformOptions := terraform.WithDefaultRetryableErrors(t, &terraform.Options{TerraformDir: "../examples"})
	defer terraform.Destroy(t, terraformOptions)
	terraform.InitAndApply(t, terraformOptions)
	aws.AssertS3BucketExists(t, "ap-northeast-1", "usualmoon3700-terratest")
}

usualmoon3700-terratestというS3バケットを作成し、それが存在するか確認するだけ
実行してみる

$ go test
TestTerraform 2022-11-27T07:54:24+09:00 retry.go:91: terraform [init -upgrade=false]                           
~~なんかいっぱいでる~~
PASS
ok      github.com/usualmoon3700/terratest      8.093s

モジュールが充実してて結構簡単に書ける

github.com