terraformで最初にする設定
概要
Terraform を使用して AWS にリソースを新規デプロイするための初期設定についてまとめました。
ツールのインストール
tfenv は Terraform のバージョン管理を行うツールです。Terraform のバージョンをプロジェクトごとに管理しバージョンの切り替えが可能になります。
以下はバージョン管理の例となります。
以下のようにプロジェクト x、y、z があると仮定します。
それぞれ使用している terraform バージョンが違う場合、tfenv を使用することで素早くバージョン切り替えが可能となります。
- x環境(terraform1.10.0)
- y環境 (terraform1.10.1)
- z環境 (terraform1.10.2)
詳細については、以下の公式リポジトリを参照してください。
🔗 tfenv GitHub リポジトリ
https://github.com/tfutils/tfenv
tfenv インストール手順
Homebrew を使用して tfenv をインストールします。
$ brew install tfenv
tfenv インストール確認
以下のコマンドを実行し、tfenv が正しくインストールされているか確認します。
$ tfenv
tfenv 3.0.0
Usage: tfenv <command> [<options>]
Commands:
install Install a specific version of Terraform
use Switch a version to use
uninstall Uninstall a specific version of Terraform
list List all installed versions
list-remote List all installable versions
version-name Print current version
init Update environment to use tfenv correctly.
pin Write the current active version to ./.terraform-version
上記のように tfenv のヘルプが表示されれば、インストールは成功です。
terraform インストール
tfenv list-remote を実行すると、インストール可能な Terraform のバージョン一覧が表示されます。
$ tfenv list-remote
1.11.0-beta2
1.11.0-beta1
1.11.0-alpha20250107
1.11.0-alpha20241218
1.11.0-alpha20241211
1.11.0-alpha20241106
1.10.5
1.10.4
1.10.3
1.10.2
1.10.1
1.10.0
以下略
表示されたリストの中から、必要なバージョンを選択してインストールできます。
$ tfenv install 1.10.0
Installing Terraform v1.10.0
Downloading release tarball from https://releases.hashicorp.com/terraform/1.10.0/terraform_1.10.0_darwin_arm64.zip
######################################################################################################################################################################################################################################################### 100.0%
Downloading SHA hash file from https://releases.hashicorp.com/terraform/1.10.0/terraform_1.10.0_SHA256SUMS
Not instructed to use Local PGP (/opt/homebrew/Cellar/tfenv/3.0.0/use-{gpgv,gnupg}) & No keybase install found, skipping OpenPGP signature verification
Archive: /var/folders/jn/k32h41nx6096ccrnp73rss8h6p8c_0/T/tfenv_download.XXXXXX.mWq4qHcXE5/terraform_1.10.0_darwin_arm64.zip
inflating: /opt/homebrew/Cellar/tfenv/3.0.0/versions/1.10.0/LICENSE.txt
inflating: /opt/homebrew/Cellar/tfenv/3.0.0/versions/1.10.0/terraform
Installation of terraform v1.10.0 successful. To make this your default version, run 'tfenv use 1.10.0'
インストールしただけでは、Terraform はまだ使用できません。
tfenv use を実行することで、指定したバージョンを有効化し、初めて使用できるようになります。
$ tfenv use 1.10.0
Switching default version to v1.10.0
Default version (when not overridden by .terraform-version or TFENV_TERRAFORM_VERSION) is now: 1.10.0
このコマンドを実行すると、Terraform のバージョンが 1.10.0 に切り替わり、使用可能になります。
$ terraform --version //--versionでバージョン情報が見れます
Terraform v1.10.0
on darwin_arm64
Your version of Terraform is out of date! The latest version
is 1.10.5. You can update by downloading from https://www.terraform.io/downloads.html
最新バージョンがリリースされている場合は、上記のようにアップデートの案内が表示されることがあります。
tfenv list を実行すると、インストール済みの Terraform のバージョンを確認できます。
$ tfenv list
* 1.10.0 (set by /opt/homebrew/Cellar/tfenv/3.0.0/version)
これで Terraform が使用可能になりました。
ここからは、頻繁に使用する Terraform のコマンドについて見ていきます。
$ terraform init # Terraform の初期化
$ terraform plan # 実行前の変更内容を確認
$ terraform apply # リソースをデプロイ
以上で Terraform のインストールと基本的なセットアップは完了です。
次は、実際に AWS のリソースを構築してみます。
AWS 認証情報の設定
Terraform を実行するには、AWS の認証情報が必要になります。(AWS CLI で使用するものと同じです)
ここでは、認証情報がすでに発行されている前提で設定を進めます。
環境変数に access_key と secret_access_key を設定します。
export AWS_ACCESS_KEY_ID="your-access-key"
export AWS_SECRET_ACCESS_KEY="your-secret-key"
terraform の各種ファイル作成
terraform では、拡張子が .tf であれば、どのようなファイル名でも設定を読み込むことができます。
つまり terraform から見るとファイル名は関係なく、.tf ファイルであれば良いのです。
しかしそれでは管理者から見るとどこのファイルに何が記載されているのかわからなくなるので
一般的には以下のようなファイル名をつけることで役割毎にファイルを分割します。
#main.tf
main となるファイルです。ここで構築するリソース記載します。
#provider.tf
プロバイダー情報を記載するファイルです。
$ touch main.tf provider.tf
まずは プロバイダーの設定 を行います。
今回は AWS を使用しますが、Terraform では GCP や Azure などのクラウドプロバイダー も利用可能です。
provider.tf
provider "aws" {
region = "ap-northeast-1"
}
それでは、EC2 インスタンスを作成してみましょう。
main.tf
resource "aws_instance" "main" { # "プロバイダー*リソースタイプ" "リソース名"
ami = "ami-0a6fd4c92fc6ed7d5" # AMI ID(適切なものを指定)
instance_type = "t2.micro" # インスタンスタイプ
}
補足
-
リソース名は意味のある名前にするのが推奨
例: aws_instance "web_server" など -
AMI ID はリージョンごとに異なるため、適切なものを確認
aws ec2 describe-images --owners amazon --filters "Name=name,Values=al2023-ami-2023*" --query 'Images[*].[ImageId,Name]' --output table
リソース作成
まず、init コマンドを実行して Terraform の初期化を行います。
successfully のメッセージが表示されれば、初期化は成功です。
terraform init
$ terraform init
terraform init
Initializing the backend...
Initializing provider plugins...
- Reusing previous version of hashicorp/aws from the dependency lock file
- Using previously-installed hashicorp/aws v5.86.1
Terraform has been successfully initialized!
You may now begin working with Terraform. Try running "terraform plan" to see
any changes that are required for your infrastructure. All Terraform commands
should now work.
If you ever set or change modules or backend configuration for Terraform,
rerun this command to reinitialize your working directory. If you forget, other
commands will detect it and remind you to do so if necessary.
terraform init の主な処理内容:
• バックエンドの初期化(Initializing the backend...)
• プロバイダーのダウンロード & 設定(Initializing provider plugins...)
• 成功メッセージ(Terraform has been successfully initialized!)
このステップが完了したら、terraform plan を実行し、適用前の変更を確認できます。
terraform plan
terraform plan を実行すると、適用予定の変更内容が表示されます。
$ terraform plan
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.main will be created
- resource "aws_instance" "main" {
- ami = "ami-0a6fd4c92fc6ed7d5"
- arn = (known after apply)
- associate_public_ip_address = (known after apply)
- availability_zone = (known after apply)
- cpu_core_count = (known after apply)
- cpu_threads_per_core = (known after apply)
- disable_api_stop = (known after apply)
- disable_api_termination = (known after apply)
- ebs_optimized = (known after apply)
- enable_primary_ipv6 = (known after apply)
- get_password_data = false
- host_id = (known after apply)
- host_resource_group_arn = (known after apply)
- iam_instance_profile = (known after apply)
- id = (known after apply)
- instance_initiated_shutdown_behavior = (known after apply)
- instance_lifecycle = (known after apply)
- instance_state = (known after apply)
- instance_type = "t2.micro"
- ipv6_address_count = (known after apply)
- ipv6_addresses = (known after apply)
- key_name = (known after apply)
- monitoring = (known after apply)
- outpost_arn = (known after apply)
- password_data = (known after apply)
- placement_group = (known after apply)
- placement_partition_number = (known after apply)
- primary_network_interface_id = (known after apply)
- private_dns = (known after apply)
- private_ip = (known after apply)
- public_dns = (known after apply)
- public_ip = (known after apply)
- secondary_private_ips = (known after apply)
- security_groups = (known after apply)
- source_dest_check = true
- spot_instance_request_id = (known after apply)
- subnet_id = (known after apply)
- tags_all = (known after apply)
- tenancy = (known after apply)
- user_data = (known after apply)
- user_data_base64 = (known after apply)
- user_data_replace_on_change = false
- vpc_security_group_ids = (known after apply)
- capacity_reservation_specification (known after apply)
- cpu_options (known after apply)
- ebs_block_device (known after apply)
- enclave_options (known after apply)
- ephemeral_block_device (known after apply)
- instance_market_options (known after apply)
- maintenance_options (known after apply)
- metadata_options (known after apply)
- network_interface (known after apply)
- private_dns_name_options (known after apply)
- root_block_device (known after apply)
}
Plan: 1 to add, 0 to change, 0 to destroy.
────────────────────────────────────────────────────────────────────────────────────
Note: You didn't use the -out option to save this plan, so Terraform can't guarantee
to take exactly these actions if you run "terraform apply" now.
ポイント:
- + create:新規作成されるリソース
- Plan: 1 to add, 0 to change, 0 to destroy.
- 1 to add → 追加されるリソースが 1 つ
- 0 to change → 変更されるリソースなし
- 0 to destroy → 削除されるリソースなし
terraform apply
terraform apply を実行すると、上記の plan の結果に基づいてリソースが作成されます。
$ terraform apply
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.main will be created
- resource "aws_instance" "main" {
- ami = "ami-0a6fd4c92fc6ed7d5"
- arn = (known after apply)
- associate_public_ip_address = (known after apply)
- availability_zone = (known after apply)
- cpu_core_count = (known after apply)
- cpu_threads_per_core = (known after apply)
- disable_api_stop = (known after apply)
- disable_api_termination = (known after apply)
- ebs_optimized = (known after apply)
- enable_primary_ipv6 = (known after apply)
- get_password_data = false
- host_id = (known after apply)
- host_resource_group_arn = (known after apply)
- iam_instance_profile = (known after apply)
- id = (known after apply)
- instance_initiated_shutdown_behavior = (known after apply)
- instance_lifecycle = (known after apply)
- instance_state = (known after apply)
- instance_type = "t2.micro"
- ipv6_address_count = (known after apply)
- ipv6_addresses = (known after apply)
- key_name = (known after apply)
- monitoring = (known after apply)
- outpost_arn = (known after apply)
- password_data = (known after apply)
- placement_group = (known after apply)
- placement_partition_number = (known after apply)
- primary_network_interface_id = (known after apply)
- private_dns = (known after apply)
- private_ip = (known after apply)
- public_dns = (known after apply)
- public_ip = (known after apply)
- secondary_private_ips = (known after apply)
- security_groups = (known after apply)
- source_dest_check = true
- spot_instance_request_id = (known after apply)
- subnet_id = (known after apply)
- tags_all = (known after apply)
- tenancy = (known after apply)
- user_data = (known after apply)
- user_data_base64 = (known after apply)
- user_data_replace_on_change = false
- vpc_security_group_ids = (known after apply)
- capacity_reservation_specification (known after apply)
- cpu_options (known after apply)
- ebs_block_device (known after apply)
- enclave_options (known after apply)
- ephemeral_block_device (known after apply)
- instance_market_options (known after apply)
- maintenance_options (known after apply)
- metadata_options (known after apply)
- network_interface (known after apply)
- private_dns_name_options (known after apply)
- root_block_device (known after apply)
}
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 //ここで yes と入力しないとリソースは作成されません
aws_instance.main: Creating...
aws_instance.main: Still creating... [10s elapsed]
aws_instance.main: Still creating... [20s elapsed]
aws_instance.main: Still creating... [30s elapsed]
aws_instance.main: Creation complete after 35s [id=i-0123456789abcdef0]
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
Outputs:
出力の解説
- aws_instance.main: Creating...
• Terraform が EC2 インスタンスの作成を開始 - Still creating... [XXs elapsed]
• AWS にリクエストが送られ、インスタンスが作成されている状態(XX 秒経過) - Creation complete after 35s [id=i-0123456789abcdef0]
• 作成が完了し、EC2 インスタンスの ID (i-0123456789abcdef0) が表示される - Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
• Terraform の適用が完了し、リソースが 1 つ追加された ことを示す
最後までお読みいただき、ありがとうございました。
少しでも Terraform について理解を深めていただけたなら幸いです。
Discussion