はじめまして。流通・サービスソリューション事業本部 アドバンストテクノロジー部の磯部 凌(いそべ りょう)です。私は普段、お客様のAmazon Web Services(以下、AWS)環境の開発・運用・保守業務を担当しているのですが、日々の業務を通じて得た知見や気づきを、このNSSOLブログを通じて皆さまにお伝えできればと思います。これからよろしくお願いします。
さて、以前掲載されたNSSOLブログ「「IaCって何から始めればいい?」初心者のための学習ステップ」では、IaCツールの選び方や環境準備、Terraformでリソースを作って消すまでの流れが紹介されていました。
今回はそのブログの中で紹介されていた代表的なIaCツール「Terraform」を取り上げ、コード構成やコマンド設定、気を付けたいポイントについて、もう一歩踏み込んだ内容を書いていきます。
Terraformについては、これから何回かに分けてブログを連載する予定なので、今後の掲載を楽しみにしておいてください。
TerraformはHashiCorp社が開発したIaCツールです。AWSのほか、Google CloudやMicrosoft Azureなど、多くのクラウドに対応しています。
Terraformでは「どんな構成にしたいか」をコードに書きます。手順を書くのではなく、最終的な状態を書くので、宣言的なツールと呼ばれます。
Terraformで管理しているリソースについては、コードを見れば、どんなリソースがどんな設定で存在しているかがわかります。ただし、この原則には例外もありますので注意が必要です。例外については第3回で取り上げます。
このブログで紹介するコマンドは次の環境で実行しています。Terraformもプロバイダーも更新が速いので、バージョンによっては出力の見た目が変わることがあります。
環境準備の手順は冒頭でご紹介したブログの「環境準備」のパートを参考にしてください。
今回はAWS上にEC2インスタンスを1台作るコードを使います。main.tfという名前で保存してください。こちらが実際のコードです。
main.tf
※これから紹介するコード内で「xxxxxxxx」と伏字になっている箇所には、ユーザーごとのIDなど固有の情報が入ります。コピペする時は注意してください。
xxxxxxxx
terraform { required_providers { aws = { source = "hashicorp/aws" version = "~> 6.0" } } } provider "aws" { region = "ap-northeast-1" # 東京リージョン } # デフォルトVPCの、ap-northeast-1a のサブネットを取得する data "aws_subnet" "default" { availability_zone = "ap-northeast-1a" default_for_az = true } resource "aws_instance" "example" { ami = "ami-0a940816f3c484aa0" # Amazon Linux 2023 instance_type = "t3.micro" subnet_id = data.aws_subnet.default.id associate_public_ip_address = false # パブリックIPを付けない tags = { Name = "terraform-basic-example" } }
このコードは4つのブロックでできています。
~> 6.0
aws_instance
example
リソースごとにどんな設定が書けるかは、Terraform Registryのドキュメントにまとまっています。私も業務でTerraformを書くときは、だいたいこのドキュメントを見ながら書いています。リソースごとに引数の説明や実装例が詳しく載っているので、ぜひ参考にしてみてください。
※AMI IDは時期によって変わります。このブログのAMI IDをそのまま使うのではなく、実行する時点で最新のAmazon Linux 2023のAMI IDに置き換えてください。
※このコードはデフォルトVPCがある前提で書いています。デフォルトVPCを削除しているアカウントでは、dataブロックでサブネットが見つからずエラーになります。
リソースを作って消すまでの流れは、冒頭のブログでもご紹介されているので、ここでは出力の要点だけ確認します。
作業ディレクトリを初期化し、プロバイダーをダウンロードします。最初に1回、またはプロバイダーの設定を変えたときに実行します。
% terraform init Initializing the backend... Initializing provider plugins... - Finding hashicorp/aws versions matching "~> 6.0"... - Installing hashicorp/aws v6.70.0... - Installed hashicorp/aws v6.70.0 (signed by HashiCorp) Terraform has created a lock file .terraform.lock.hcl to record the provider selections it made above. Include this file in your version control repository so that Terraform can guarantee to make the same selections by default when you run "terraform init" in the future. Terraform has been successfully initialized! (以下省略)
~> 6.0の指定に合う中で最新の、v6.70.0がインストールされました。
実行すると、.terraform.lock.hclというファイルができます。使ったプロバイダーのバージョンを記録するファイルで、Gitで管理しておくと、チームの全員が同じバージョンを使えます。
.terraform.lock.hcl
実は恥ずかしい話なのですが、以前は私もこのファイルが何のためにあるのかよくわからないまま業務で使っていました。今回このブログを書くにあたって調べてみたところ、バージョンを記録するファイルだったのかと知りました。init をしたら出てくるよくわからないファイル、と思っている方もこの機会にぜひ一緒に役割を覚えてしまいましょう。
実際に変更する前に、何が起きるかを確認します。
% terraform plan data.aws_subnet.default: Reading... data.aws_subnet.default: Read complete after 0s [id=subnet-xxxxxxxxxxxxxxxxx] Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols: + create Terraform will perform the following actions: # aws_instance.example will be created + resource "aws_instance" "example" { + ami = "ami-0a940816f3c484aa0" + arn = (known after apply) + associate_public_ip_address = false (中略) + id = (known after apply) (中略) + instance_type = "t3.micro" (中略) + private_ip = (known after apply) (中略) + subnet_id = "subnet-xxxxxxxxxxxxxxxxx" (中略) + tags = { + "Name" = "terraform-basic-example" } (以下省略) } Plan: 1 to add, 0 to change, 0 to destroy.
planの読み方は次のパートで詳しく見ていきます。
planの内容を実際の環境に反映します。もう一度変更内容が表示され、yesと入力すると実行されます。
yes
% terraform apply (planと同じ内容が表示される) Plan: 1 to add, 0 to change, 0 to destroy. Do you want to perform these actions? Terraform will perform the actions described above. Only 'yes' will be accepted to approve. Enter a value: yes aws_instance.example: Creating... aws_instance.example: Still creating... [00m10s elapsed] aws_instance.example: Creation complete after 13s [id=i-xxxxxxxxxxxxxxxxx] Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
マネジメントコンソールで確認すると、EC2インスタンスが作られていることがわかります。Nameタグを付けておいたので、一覧でも見つけやすくなっています。
Terraformで作ったリソースをまとめて削除します。試し終わったら、課金が続かないよう、忘れずに実行してください。なお、destroyはブログの最後で実行します。
ではここから、先ほど飛ばしたplanの読み方についてご紹介していきます。
個人的には、Terraformを使っていていちばん時間をかけているのがplanの出力を読むことかもしれません。applyする前に「何が起きるのか」を正しく読み取れれば、思わぬ削除や作り直しを防げます。
業務でplanをレビューするとき、私がまず見るのは最後のPlan:の行です。特にchangeとdestroyの数を見て、想定外のリソースが含まれていないかを注意深く確認しています。すでに動いているリソースが変更されたり削除されたりすると、システムが動かなくなるなど、業務に影響が出てしまうからです。
Plan:
planの出力では行頭の記号で、そのリソースに何が起きるかを表しています。
出力の最後には、作る数・変更する数・削除する数がまとめて表示されます。
Plan: 1 to add, 0 to change, 0 to destroy.
この行は毎回確認するようにしてください。destroyが0でないときは、どのリソースが消えるのかを必ず確かめることが重要です。
ここからは、先ほど作ったEC2のコードを少しずつ変えて、planの出力がどう変わるかを実際に試してみます。
まずはタグを1つ追加してみます。
tags = { Name = "terraform-basic-example" Env = "dev" }
% terraform plan data.aws_subnet.default: Reading... data.aws_subnet.default: Read complete after 1s [id=subnet-xxxxxxxxxxxxxxxxx] aws_instance.example: Refreshing state... [id=i-xxxxxxxxxxxxxxxxx] Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols: ~ update in-place Terraform will perform the following actions: # aws_instance.example will be updated in-place ~ resource "aws_instance" "example" { id = "i-xxxxxxxxxxxxxxxxx" ~ tags = { + "Env" = "dev" "Name" = "terraform-basic-example" } ~ tags_all = { + "Env" = "dev" # (1 unchanged element hidden) } # (39 unchanged attributes hidden) # (9 unchanged blocks hidden) } Plan: 0 to add, 1 to change, 0 to destroy.
行頭の~は今あるEC2をそのまま変更することを表しています。中を見ると、tagsに~が付き、その中のEnvの行に+が付いています。「タグの一覧が変わり、その中でEnvが増える」という意味です。
~
tags
Env
+
変わらない属性は# (39 unchanged attributes hidden)のようにまとめて省略されるので、変わるところだけを追えます。
# (39 unchanged attributes hidden)
tags_allはコードに書いたタグに、providerブロックのdefault_tagsで指定したタグを合わせた一覧です。今回はdefault_tagsを使っていないので、tagsと同じ内容が増えています。
tags_all
default_tags
次に、インスタンスタイプをt3.microからt3.smallに変えてみます。
t3.micro
t3.small
% terraform plan data.aws_subnet.default: Reading... data.aws_subnet.default: Read complete after 1s [id=subnet-xxxxxxxxxxxxxxxxx] aws_instance.example: Refreshing state... [id=i-xxxxxxxxxxxxxxxxx] Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols: ~ update in-place Terraform will perform the following actions: # aws_instance.example will be updated in-place ~ resource "aws_instance" "example" { id = "i-xxxxxxxxxxxxxxxxx" ~ instance_type = "t3.micro" -> "t3.small" tags = { "Name" = "terraform-basic-example" } # (39 unchanged attributes hidden) # (9 unchanged blocks hidden) } Plan: 0 to add, 1 to change, 0 to destroy.
これも~なので、EC2は作り直されません。->の左が今の値、右が変更後の値です。変わるのはinstance_typeの1行だけで、タグを足したときと同じくらい小さな変更に見えます。
->
instance_type
ところが、EC2のインスタンスタイプはインスタンスを止めないと変えられません。Terraformはapplyの中でインスタンスを停止し、タイプを変えてから起動し直します。planには、そのことは何も表示されていません。
実際にapplyしてみます。
% terraform apply (中略) aws_instance.example: Modifying... [id=i-xxxxxxxxxxxxxxxxx] aws_instance.example: Still modifying... [id=i-xxxxxxxxxxxxxxxxx, 00m10s elapsed] aws_instance.example: Still modifying... [id=i-xxxxxxxxxxxxxxxxx, 00m20s elapsed] aws_instance.example: Still modifying... [id=i-xxxxxxxxxxxxxxxxx, 00m30s elapsed] aws_instance.example: Modifications complete after 33s [id=i-xxxxxxxxxxxxxxxxx] Apply complete! Resources: 0 added, 1 changed, 0 destroyed.
タグの追加は一瞬で終わったのに対して、こちらは33秒かかりました。インスタンスIDは同じままです。
気になったのでAWS CloudTrailのイベント履歴を見てみると、Terraformが裏でよしなにStopInstances(停止)、ModifyInstanceAttribute(タイプの変更)、StartInstances(起動)を順に呼んでいたことがわかりました。停止から起動まで、約20秒かかっていました。
planの記号だけを見ると「その場で変更」ですが、実際にはサーバーが一度止まっています。
つまり、~だから影響がない、とは限らないということです。本番環境のEC2でインスタンスタイプを変えるときは、planが小さく見えても、止めて問題ない時間帯にapplyするのが安全です。
最後に、AMIを別のもの(Amazon Linux 2023のminimal版)に変えてみます。インスタンスタイプはt3.microに戻した状態から試しています。
% terraform plan data.aws_subnet.default: Reading... data.aws_subnet.default: Read complete after 1s [id=subnet-xxxxxxxxxxxxxxxxx] aws_instance.example: Refreshing state... [id=i-xxxxxxxxxxxxxxxxx] Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols: -/+ destroy and then create replacement Terraform will perform the following actions: # aws_instance.example must be replaced -/+ resource "aws_instance" "example" { ~ ami = "ami-0a940816f3c484aa0" -> "ami-06ea6b93ee08196df" # forces replacement ~ arn = "arn:aws:ec2:ap-northeast-1:123456789012:instance/i-xxxxxxxxxxxxxxxxx" -> (known after apply) (中略) ~ id = "i-xxxxxxxxxxxxxxxxx" -> (known after apply) (中略) ~ private_ip = "172.31.42.135" -> (known after apply) (中略) - root_block_device { - delete_on_termination = true -> null - device_name = "/dev/xvda" -> null (中略) - volume_id = "vol-054a51c249602c02d" -> null - volume_size = 8 -> null - volume_type = "gp3" -> null } (以下省略) }
行頭が-/+になり、amiの行に# forces replacementと表示されています。これは「この属性を変えるには、リソースを作り直すしかない」という意味です。
-/+
ami
# forces replacement
EC2の場合、作り直すとインスタンスIDが変わり、中のデータも消えます。planでも、インスタンスIDやプライベートIPが(known after apply)になり、今のルートボリューム(root_block_device)の行には-が付いて、削除されることがわかります。forces replacementが出ていたら、どの属性が原因なのかを必ず確認してください。
(known after apply)
-
forces replacement
AMIを1行変えただけなのに、タイプの変更よりはるかに大きな変更になりました。実際、今回のplanは100行を超えましたが、forces replacementが付くのはamiの1行だけです。長いplanの中から、この1行を見落とさないことが大事です。
最後の行も見てみます。
Plan: 1 to add, 0 to change, 1 to destroy.
変更したのは1行だけでも、作り直しの場合は「1つ作って、1つ消す」と数えられます。
planの出力には、(known after apply)と書かれた値がたくさん出てきます。
+ arn = (known after apply) + availability_zone = (known after apply) + id = (known after apply) + private_ip = (known after apply)
これは「applyしてみないと決まらない値」です。新しく作るときは、インスタンスIDやIPアドレスがAWS側で作られて初めて決まるので、planの時点では表示できません。
一方で、すでにあるリソースの値が"今の値" -> (known after apply)になっているときは、「今の値から変わるかもしれない」という意味です。AMIの変更では、インスタンスIDやプライベートIPがこの形で表示されていました。IPアドレスやインスタンスIDをほかの設定やシステムに登録している場合は、影響がないか確認が必要です。
"今の値" -> (known after apply)
試し終わったら、terraform destroyでリソースを削除します。
% terraform destroy (中略) # aws_instance.example will be destroyed - resource "aws_instance" "example" { (中略) Plan: 0 to add, 0 to change, 1 to destroy. Do you really want to destroy all resources? Terraform will destroy all your managed infrastructure, as shown above. There is no undo. Only 'yes' will be accepted to confirm. Enter a value: yes aws_instance.example: Destroying... [id=i-xxxxxxxxxxxxxxxxx] aws_instance.example: Still destroying... [id=i-xxxxxxxxxxxxxxxxx, 00m10s elapsed] aws_instance.example: Still destroying... [id=i-xxxxxxxxxxxxxxxxx, 00m20s elapsed] aws_instance.example: Still destroying... [id=i-xxxxxxxxxxxxxxxxx, 00m30s elapsed] aws_instance.example: Destruction complete after 30s Destroy complete! Resources: 1 destroyed.
destroyでもplanと同じ形で削除されるリソースが表示されます。ここでも最後の行を見て、消えるのが想定したリソースだけかを確かめてからyesを入力してください。
今回はTerraformのコードの構成と、terraform planの出力の読み方を紹介しました。重要なポイントをまとめると、
の3点です。
個人的には、planでは~と表示されていてもサーバーが止まることを、実際に手を動かして確認できたのがよかったです。
次回は、Terraformが「今の状態」を覚えておくためのstateファイルと、知っておくと便利なコマンドや設定を紹介します。
ちなみにNSSOLではAWS包括的技術支援サービスを提供しています。私のように、AWSの開発・運用・保守に携わるAWSの専門家がお客様のAWSに関するお悩みの解決に向けてご支援いたします。その他、AWSをはじめマルチクラウド化に関するご相談全般もお気軽にお声がけください。
また、マルチクラウド領域に関する各種ダウンロード資料も豊富にご用意していますので、ご興味があればぜひあわせてご覧ください。
このブログをご覧になった皆さまのお役に立ったなら嬉しいです。それでは、また次回もお楽しみに!