実践Terraform ch19 高度な構文

Terraform勉強メモ

出典: 


三項演算子

variable "env" {}

resource "aws_instance" "example" {
  ami = "ami-0c3fd0f5d33134a76"
  instance_type = var.env == "prod" ? "m5.large" : "t3.micro"
}
terraform plan -var 'env=dev'
...
      + instance_state               = (known after apply)
      + instance_type                = "t3.micro"
      + ipv6_address_count           = (known after apply)
...
terraform plan -var 'env=prod'
...
      + instance_state               = (known after apply)
      + instance_type                = "m5.large"
      + ipv6_address_count           = (known after apply)
...

複数リソース作成

  • 【補】CloudFormationでできないやつ
variable "cnt" {}

resource "aws_instance" "example" {
  count = var.cnt
  ami = "ami-0c3fd0f5d33134a76"
  instance_type = "t3.micro"
}
terraform plan -var 'cnt=3'
An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  # aws_instance.example[0] will be created
  + resource "aws_instance" "example" {
...

  # aws_instance.example[1] will be created
  + resource "aws_instance" "example" {
...

  # aws_instance.example[2] will be created
  + resource "aws_instance" "example" {
...

リソース作成制御

  • 三項演算子と0 or 1のcountを組み合わせて、リソースの作成する/しないを制御できる

データソース

  • ハードコードを減らす

    • 例: ELBのサービスアカウント

主要な組み込み関数

  • Numeric Functions

    • maxとか
  • String Functions

    • substrとか
  • Collection Functions

    • flatten, concatとか
  • Filesystem Functions

    • file,templatefileとか

ランダム文字列

  • RDBのパスワードなどはterraformで管理できない

    • tfファイルに直接記述するわけにはいかない

      • 当然
    • 変数で流し込むわけにもいかない

      • tfstateファイル内に平文で残ってしまうため
  • ので、仮の値を入れておいて、terraform管理外でAWS CLIを用いて置換する
  • 置換前の仮の値を入れるには、ランダム文字列が好適
provider "random" {}

resource "random_string" "password" {
  length = 32
  special = false
}

output "random" {
  value = random_string.password.result
}
Outputs:

random = yRmTvgceZPydDn9h1tkFDaiyp9T1Muaf
  • 変更がないと同じ値になるっぽい
Outputs:

random = yRmTvgceZPydDn9h1tkFDaiyp9T1Muaf

Multipleプロバイダ

  • 複数リージョンにリソースを配置したいようなケース
provider "aws" {
  alias = "virginia"
  region = "us-east-1"
}

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

resource "aws_vpc" "virginia" {
  provider = aws.virginia
  cidr_block = "192.168.0.0/16"
}

resource "aws_vpc" "tokyo" {
  cidr_block = "192.168.0.0/16"
}

output "virginia_vpc" {
  value = aws_vpc.virginia.arn
}

output "tokyo_vpc" {
  value = aws_vpc.tokyo.arn
}
Outputs:

tokyo_vpc = arn:aws:ec2:ap-northeast-1:646279979860:vpc/vpc-0492ae8d52d9a0fcc
virginia_vpc = arn:aws:ec2:us-east-1:646279979860:vpc/vpc-091ff39d370ce0bba

Dynamic blocks

  • ブロックを動的に作るやつ

    • sgのingressとか
  • 慎ましく使おう

    • リフレクションの類と似ている
    • 使いすぎると独自DSLの様相を呈してきてメンテが辛くなる