Terraformの基本的な構文

variable

変数を定義することができる。

variable "example_instancetype" {
    default = "t3.micro"
}

resource "aws_instance" "example" {
    ami           = "ami-0c3fd0f5d33134a76"
    instance_type = var.example_instancetype
}

variableで定義した変数は実行する際に上書きすることが可能。

$ terraform plan -var 'example_instancetype=t3.nano'

locals

ローカル変数を定義することができる。 variableと違いコマンド実行時に上書きすることができない。

locals {
    example_instancetype = "t3.micro"
}
resource "aws_instance" "example" {
    ami           = "ami-0c3fd0f5d33134a76"
    instance_type = local.example_instancetype
}

データソース

外部データの参照することができる。 以下のように定義すると最新のAmazonLinux2のAMIを参照することが可能。

data "aws_ami" "recent_amazon_linux_2" {
    most_recent = true
    owners= ["amazon"]

    filter {
        name = "name"
        values = ["amzn2-ami-hvm-2.0.????????-x86_64-gp2"]
    }
    filter {
        name = "state"
        values = ["available"]
    }
}
resource "aws_instance" "example" {
    ami           = data.aws_ami.recent_amazon_linux_2.image_id
    instance_type = "t3.micro"
}

プロバイダ

AWSGCPなど各プラットフォームの違いを吸収してくれる。

AWS

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

GCP

provider "google" {
  credentials = file("account.json")
  project     = "my-project-id"
  region      = "us-central1"
}

その他のプロバイダの設定は以下を参照

Providers - Terraform by HashiCorp

他のリソースの参照

TYPE.NAME.ATTRIBUTE形式で記載すると、他のリソースの値を参照できる。

resource "aws_security_group" "example_ec2" {
    name = "example-ec2"

    ingress {
        from_port = 80
        to_port = 80
        protocol = "tcp"
        cidr_blocks = ["0.0.0.0/0"]
    }

    egress {
        from_port = 0
        to_port = 0
        protocol = "-1"
        cidr_blocks = ["0.0.0.0/0"]
    }

}

resource "aws_instance" "example" {
    ami           = "ami-0c3fd0f5d33134a76"
    instance_type = local.example_instancetype
    # 上で作ったVPCを参照
    vpc_security_group_ids = [aws_security_group.example_ec2.id]
}

おわり!