コンテンツにスキップ

Terraform

インストール

Install Terraform | Terraform - HashiCorp Learn

apt

$ sudo apt-get update && sudo apt-get install -y gnupg software-properties-common curl
$ curl -fsSL https://apt.releases.hashicorp.com/gpg | sudo apt-key add -
$ sudo apt-add-repository "deb [arch=amd64] https://apt.releases.hashicorp.com $(lsb_release -cs) main"
$ sudo apt-get update && sudo apt-get install terraform

CLI

フォーマッタ

standard styleへ変換する。

terraform fmt -recursive

-recursive無しの場合はカレントディレクトリのみが対象

providerバージョン確認

terraform providers -version

といわれてるけどprovidersが無くても出力は同じ。

providerバージョンアップグレード

tfファイルのprovicersの定義で指定バージョンを変更して、以下コマンド実行。

terraform init -upgrade

リソース一覧

terraform state list

workspace

現在のworkspace

$ terraform workspace show
default

一覧

$ terraform workspace list
  default
* 1
  2

変更

workspace 2 に変更

$ terraform workspace select 2
Switched to workspace "2".

設定値は.terraform/environmentに記録される。

variable

引数

terraform plan -var='enable_wan=false'

backend設定

S3

backendの定義を追加

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

  backend "s3" {
    bucket = "bucket-name"
    key    = "terraform.tfstate"
    region = "ap-northeast-1"
  }
}

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

もともとローカルでtfstate作っていた状態からS3へ移行する場合は、

  1. S3バケット作成
  2. tfstateをS3アップロード
  3. ソースにbackend定義追加 (バケット名・キー(ファイル)名・リージョン指定)

ここまではセットで。
で、

  1. ローカルのtfstateを退避
  2. terraform init実行 (S3設定が反映される)
  3. terraform planで差分がないことを確認

でいける。

S3 + DynamoDBでのロック

DynamoDBでテーブルを作成

  • 名前は任意
  • パーティションキーはLockID
  • その他はデフォルト

あとはバックエンド設定に以下追加

  backend "s3" {
    bucket         = S3バケット名
    key            = "terraform.tfstate"
    region         = リージョン
    dynamodb_table = DynamoDBテーブル名
    encrypt        = true
  }

構文

count

EC2を3つ立てNameタグに連番を振る

resource "aws_instance" "cloud-vm" {
  count           = 3
  instance_type   = "t2.medium"
  :

  tags = {
    Name = "cloud-${count.index}"
  }
}

変数

変数参照

vm_ami_idという変数を定義しているなら以下。

ami = var.vm_ami_id

補完

文字列リテラルの中で参照する場合は「補完」で書式は以下。

tags = {
  Name = "${var.name_prefix}-server"
}

テンプレート

エスケープ

%{...}という文字をそのまま使いたい場合は%%{...}

curl -k https://localhost:6443 -w '%%{http_code}\n' -sS -o /dev/null 2>/dev/null

resource

デフォルトのルートテーブル

VPCのパラメタのdefault_route_table_idを参照する。

route_table_ids = [aws_vpc.my_vpc.default_route_table_id]

docs

terraform-docs
Terraformコードからドキュメント生成するツール。

CLIをインストールできるがコンテナ実行でも生成できる。
Podmanであれば、Terraformコードのあるディレクトリで以下を実行すればREADME.mdが生成される。

podman run --rm -v "$(pwd):/terraform-docs" quay.io/terraform-docs/terraform-docs:0.18.0 markdown /terraform-docs --output-file README.md