nextpublishing.jp
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)
...
複数リソース作成
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を組み合わせて、リソースの作成する/しないを制御できる
データソース
主要な組み込み関数
- Numeric Functions
- String Functions
- Collection Functions
- Filesystem Functions
ランダム文字列
- RDBのパスワードなどはterraformで管理できない
- tfファイルに直接記述するわけにはいかない
- 変数で流し込むわけにもいかない
- ので、仮の値を入れておいて、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
- ブロックを動的に作るやつ
- 慎ましく使おう
- リフレクションの類と似ている
- 使いすぎると独自DSLの様相を呈してきてメンテが辛くなる