もがき系プログラマの日常

もがき系エンジニアの勉強したこと、日常のこと、気になっている技術、備忘録などを紹介するブログです。

# 実践 Terraformを読んでTerraform勉強中 Vol.2

はじめに

こんばんは。

今回は以下の本を読んで勉強中です。

前回の記事はこちら

kojirooooocks.hatenablog.com

今回は第3章です。

バージョンは以下です。

$ terraform --version
Terraform v1.0.3

本題

第3章

variable

# 定義方法
variable "region" {
  default = "us-east-1"
}

# 使用方法
provider "aws" {
    region = var.region
}

variableは実行時に環境変数-ver オプションで値を上書きできます。

locals

# 定義方法
locals {
  ami = "ami-0c2b8ca1dad447f8a"
}

# 使用方法
resource "aws_instance" "example" {
    ami = local.ami
}

variableと違ってlocalsは実行時や環境変数で上書きできません。

出力値(output)

cli上に出力してくれます。

output "public_dns" {
  value = module.web_server.public_dns
}


$ terraform apply
.
..
...
Apply complete! Resources: 2 added, 0 changed, 0 destroyed.

Outputs:
public_dns = "xxxxxxxxxxxxxxxxxxxxx.amazonaws.com"

データソース

本書では Amazon Linux2の最新のAMIのimage_idを取得してました。

実運用では、どんな場面で使用するんだろう? その辺りが想像できなかったので、一旦ここは読み飛ばす。

参照(セキュリティグループ作成)

本のままやろうとすると、以下のエラーが出ます。

 Inappropriate value for attribute "egress": element 0: attributes "description", "ipv6_cidr_blocks", "prefix_list_ids", "security_groups", and "self" are required.

必要項目が増えてるって感じですかね。

自分の場合以下のようにしました。

  ingress = [ {
    from_port        = 80
    to_port          = 80
    protocol         = "tcp"
    description      = ""
    cidr_blocks      = [ "0.0.0.0/0" ]
    ipv6_cidr_blocks = []
    prefix_list_ids  = []
    security_groups  = []
    self             = null
  } ]

  egress = [ {
    from_port        = 0
    to_port          = 0
    protocol         = "-1"
    description      = ""
    cidr_blocks      = [ "0.0.0.0/0" ]
    ipv6_cidr_blocks = []
    prefix_list_ids  = []
    security_groups  = []
    self             = null
  } ]

組み込み関数

第3章で紹介してくれているのは file() だけだったけど、調べてみたら結構ありました。

www.terraform.io

モジュール

ダラーッと書いていくのそろそろ辛くなったなと思ったら登場しました。

本書と同じくweb_serverを立ち上げるコードをmodule化してみました。

 tree
.
├── main.tf
└── web_server
    ├── main.tf
    └── user_data.sh

rootとなる main.tf はスッキリ

module "web_server" {
  source       = "./web_server"
  instanceType = "t3.nano"
  region       = "us-east-1"
  tagName      = "WebServer01"
}

output "public_dns" {
  value = module.web_server.public_dns
}

moduleを使用する場合は terraform getterraform init を実行しておく必要あり。

$ terraform get
- web_server in web_server

終わりに

第4章も行こうと思ったのですが、第4章からが本当の始まりだったので、次回に持ち越しました。

そういえば、フォーマッターとかないのかなーとか思ってたら terraform fmt でフォーマットしてくれるのを知りました。

現場からは以上です。