從 Terraform 初學者到專家(初始配置)的完全指南
简介
本次,我想向那些还没有接触过的人简单介绍一下作为基础设施即代码的代表性工具Terraform的特点和使用方法。
我们将使用Terraform来构建、编辑、删除AWS资源。
前提条件 (Qiantí
・MAC : 苹果电脑
・VS code : Visual Studio Code
・具备创建AWS资源所需权限设置的IAM用户访问密钥
本地环境
% sw_vers
ProductName: macOS
ProductVersion: 12.4
BuildVersion: 21F79
安装Terraform
brew tap hashicorp/tap
brew install hashicorp/tap/terraform
检查Terraform的状态
% terraform -version
Terraform v1.2.4
on darwin_arm64
Terraform文档
这次,我参考了下面的链接。
为了启动Ec2,需要准备代码,使用Terraform。
使用VSCode创建main.tf文件。
在main.tf文件中写入以下代码。
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 3.0"
}
}
}
# Configure the AWS Provider
provider "aws" {
region = "ap-northeast-1"
access_key = "xxxxxxxxxxx"
secret_key = "xxxxxxxxxxxxx"
}
resource "aws_instance" "my-first-terraform-ec2" {
ami = "ami-0b7546e839d7ace12"
instance_type = "t2.micro"
tags = {
Name = "my-first-terraform-ec2"
}
}
进行terraform初期化
从互联网上获取执行Terraform所需的插件。
% terraform init
Initializing the backend...
Initializing provider plugins...
- Finding hashicorp/aws versions matching "~> 3.0"...
- Installing hashicorp/aws v3.75.2...
- Installed hashicorp/aws v3.75.2 (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!
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 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.my-first-terraform-ec2 will be created
+ resource "aws_instance" "my-first-terraform-ec2" {
+ ami = "ami-0b7546e839d7ace12"
+ 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_termination = (known after apply)
+ ebs_optimized = (known after apply)
+ get_password_data = false
+ host_id = (known after apply)
+ id = (known after apply)
+ instance_initiated_shutdown_behavior = (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
+ subnet_id = (known after apply)
+ tags = {
+ "Name" = "my-first-terraform-ec2"
}
+ tags_all = {
+ "Name" = "my-first-terraform-ec2"
}
+ tenancy = (known after apply)
+ user_data = (known after apply)
+ user_data_base64 = (known after apply)
+ vpc_security_group_ids = (known after apply)
+ capacity_reservation_specification {
+ capacity_reservation_preference = (known after apply)
+ capacity_reservation_target {
+ capacity_reservation_id = (known after apply)
}
}
+ ebs_block_device {
+ delete_on_termination = (known after apply)
+ device_name = (known after apply)
+ encrypted = (known after apply)
+ iops = (known after apply)
+ kms_key_id = (known after apply)
+ snapshot_id = (known after apply)
+ tags = (known after apply)
+ throughput = (known after apply)
+ volume_id = (known after apply)
+ volume_size = (known after apply)
+ volume_type = (known after apply)
}
+ enclave_options {
+ enabled = (known after apply)
}
+ ephemeral_block_device {
+ device_name = (known after apply)
+ no_device = (known after apply)
+ virtual_name = (known after apply)
}
+ metadata_options {
+ http_endpoint = (known after apply)
+ http_put_response_hop_limit = (known after apply)
+ http_tokens = (known after apply)
+ instance_metadata_tags = (known after apply)
}
+ network_interface {
+ delete_on_termination = (known after apply)
+ device_index = (known after apply)
+ network_interface_id = (known after apply)
}
+ root_block_device {
+ delete_on_termination = (known after apply)
+ device_name = (known after apply)
+ encrypted = (known after apply)
+ iops = (known after apply)
+ kms_key_id = (known after apply)
+ tags = (known after apply)
+ throughput = (known after apply)
+ volume_id = (known after apply)
+ volume_size = (known after apply)
+ volume_type = (known after apply)
}
}
Plan: 1 to add, 0 to change, 0 to destroy.
启动EC2
terraform apply命令将应用定义。
% 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.my-first-terraform-ec2 will be created
+ resource "aws_instance" "my-first-terraform-ec2" {
+ ami = "ami-0b7546e839d7ace12"
+ 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_termination = (known after apply)
+ ebs_optimized = (known after apply)
+ get_password_data = false
+ host_id = (known after apply)
+ id = (known after apply)
+ instance_initiated_shutdown_behavior = (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
+ subnet_id = (known after apply)
+ tags = {
+ "Name" = "HelloWorld"
}
+ tags_all = {
+ "Name" = "HelloWorld"
}
+ tenancy = (known after apply)
+ user_data = (known after apply)
+ user_data_base64 = (known after apply)
+ vpc_security_group_ids = (known after apply)
+ capacity_reservation_specification {
+ capacity_reservation_preference = (known after apply)
+ capacity_reservation_target {
+ capacity_reservation_id = (known after apply)
}
}
+ ebs_block_device {
+ delete_on_termination = (known after apply)
+ device_name = (known after apply)
+ encrypted = (known after apply)
+ iops = (known after apply)
+ kms_key_id = (known after apply)
+ snapshot_id = (known after apply)
+ tags = (known after apply)
+ throughput = (known after apply)
+ volume_id = (known after apply)
+ volume_size = (known after apply)
+ volume_type = (known after apply)
}
+ enclave_options {
+ enabled = (known after apply)
}
+ ephemeral_block_device {
+ device_name = (known after apply)
+ no_device = (known after apply)
+ virtual_name = (known after apply)
}
+ metadata_options {
+ http_endpoint = (known after apply)
+ http_put_response_hop_limit = (known after apply)
+ http_tokens = (known after apply)
+ instance_metadata_tags = (known after apply)
}
+ network_interface {
+ delete_on_termination = (known after apply)
+ device_index = (known after apply)
+ network_interface_id = (known after apply)
}
+ root_block_device {
+ delete_on_termination = (known after apply)
+ device_name = (known after apply)
+ encrypted = (known after apply)
+ iops = (known after apply)
+ kms_key_id = (known after apply)
+ tags = (known after apply)
+ throughput = (known after apply)
+ volume_id = (known after apply)
+ volume_size = (known after apply)
+ volume_type = (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
aws_instance.my-first-terraform-ec2: Creating...
aws_instance.my-first-terraform-ec2: Still creating... [10s elapsed]
aws_instance.my-first-terraform-ec2: Still creating... [20s elapsed]
aws_instance.my-first-terraform-ec2: Still creating... [30s elapsed]
aws_instance.my-first-terraform-ec2: Creation complete after 33s [id=i-054b5babd53a5a942]
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
确认EC2实例的启动状态
登录AWS控制台,查看EC2的情况。

我确认了 EC2 已经启动。
使用Terraform更改资源。
刚刚启动的EC2标签内容将被更改。
my-first-terraform-ec2
↓
modify-first-terraform-ec2-tags-name
将在main.tf文件中更改EC2标签的名称。
resource "aws_instance" "my-first-terraform-ec2" {
ami = "ami-0b7546e839d7ace12"
instance_type = "t2.micro"
tags = {
Name = "modify-first-terraform-ec2-tags-name"
}
}
确认更改的内容
% terraform plan
aws_instance.my-first-terraform-ec2: Refreshing state... [id=i-0041e996aac4e5b4b]
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.my-first-terraform-ec2 will be updated in-place
~ resource "aws_instance" "my-first-terraform-ec2" {
id = "i-0041e996aac4e5b4b"
~ tags = {
~ "Name" = "my-first-terraform-ec2" -> "modify-first-terraform-ec2-tags-name"
}
~ tags_all = {
~ "Name" = "my-first-terraform-ec2" -> "modify-first-terraform-ec2-tags-name"
}
# (27 unchanged attributes hidden)
# (5 unchanged blocks hidden)
}
Plan: 0 to add, 1 to change, 0 to destroy.
执行更改内容
% terraform apply
aws_instance.my-first-terraform-ec2: Refreshing state... [id=i-0041e996aac4e5b4b]
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.my-first-terraform-ec2 will be updated in-place
~ resource "aws_instance" "my-first-terraform-ec2" {
id = "i-0041e996aac4e5b4b"
~ tags = {
~ "Name" = "my-first-terraform-ec2" -> "modify-first-terraform-ec2-tags-name"
}
~ tags_all = {
~ "Name" = "my-first-terraform-ec2" -> "modify-first-terraform-ec2-tags-name"
}
# (27 unchanged attributes hidden)
# (5 unchanged blocks hidden)
}
Plan: 0 to add, 1 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.my-first-terraform-ec2: Modifying... [id=i-0041e996aac4e5b4b]
aws_instance.my-first-terraform-ec2: Modifications complete after 1s [id=i-0041e996aac4e5b4b]
Apply complete! Resources: 0 added, 1 changed, 0 destroyed.
确认变更结果

EC2的标签名称已更改为modify-first-terraform-ec2-tags-name。
使用Terraform删除资源。
使用terraform destroy命令将删除在main.tf文件中启动的EC2实例。
% terraform destroy
aws_instance.my-first-terraform-ec2: Refreshing state... [id=i-0041e996aac4e5b4b]
Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
- destroy
Terraform will perform the following actions:
# aws_instance.my-first-terraform-ec2 will be destroyed
- resource "aws_instance" "my-first-terraform-ec2" {
- ami = "ami-0b7546e839d7ace12" -> null
- arn = "arn:aws:ec2:ap-northeast-1:694047010837:instance/i-0041e996aac4e5b4b" -> null
- associate_public_ip_address = true -> null
- availability_zone = "ap-northeast-1c" -> null
- cpu_core_count = 1 -> null
- cpu_threads_per_core = 1 -> null
- disable_api_termination = false -> null
- ebs_optimized = false -> null
- get_password_data = false -> null
- hibernation = false -> null
- id = "i-0041e996aac4e5b4b" -> null
- instance_initiated_shutdown_behavior = "stop" -> null
- instance_state = "running" -> null
- instance_type = "t2.micro" -> null
- ipv6_address_count = 0 -> null
- ipv6_addresses = [] -> null
- monitoring = false -> null
- primary_network_interface_id = "eni-05060a5c79730093c" -> null
- private_dns = "ip-172-31-2-192.ap-northeast-1.compute.internal" -> null
- private_ip = "172.31.2.192" -> null
- public_dns = "ec2-54-95-7-235.ap-northeast-1.compute.amazonaws.com" -> null
- public_ip = "54.95.7.235" -> null
- secondary_private_ips = [] -> null
- security_groups = [
- "default",
] -> null
- source_dest_check = true -> null
- subnet_id = "subnet-78a35122" -> null
- tags = {
- "Name" = "modify-first-terraform-ec2-tags-name"
} -> null
- tags_all = {
- "Name" = "modify-first-terraform-ec2-tags-name"
} -> null
- tenancy = "default" -> null
- vpc_security_group_ids = [
- "sg-33dac977",
] -> null
- capacity_reservation_specification {
- capacity_reservation_preference = "open" -> null
}
- credit_specification {
- cpu_credits = "standard" -> null
}
- enclave_options {
- enabled = false -> null
}
- metadata_options {
- http_endpoint = "enabled" -> null
- http_put_response_hop_limit = 1 -> null
- http_tokens = "optional" -> null
- instance_metadata_tags = "disabled" -> null
}
- root_block_device {
- delete_on_termination = true -> null
- device_name = "/dev/xvda" -> null
- encrypted = false -> null
- iops = 100 -> null
- tags = {} -> null
- throughput = 0 -> null
- volume_id = "vol-0a35c335542aefab0" -> null
- volume_size = 8 -> null
- volume_type = "gp2" -> null
}
}
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.my-first-terraform-ec2: Destroying... [id=i-0041e996aac4e5b4b]
aws_instance.my-first-terraform-ec2: Still destroying... [id=i-0041e996aac4e5b4b, 10s elapsed]
aws_instance.my-first-terraform-ec2: Still destroying... [id=i-0041e996aac4e5b4b, 20s elapsed]
aws_instance.my-first-terraform-ec2: Still destroying... [id=i-0041e996aac4e5b4b, 30s elapsed]
aws_instance.my-first-terraform-ec2: Destruction complete after 30s
Destroy complete! Resources: 1 destroyed.
请查看删除的结果

总结
这次,我使用Terraform实施了AWS EC2的搭建、编辑和删除。
就这样。