使用Terraform在AWS上构建Web服务器 #3 〜尝试使用Terraform启动EC2服务器〜
为了什么而做
使用Terraform构建EC2上安装Nginx并能够从浏览器上确认访问默认页面的状态是我们的目标。
通过将基础设施构建用Terraform编码,相比手动操作,我们能够获得更高的可复制性、可重用性和速度。
GitHub链接
操作步骤
-
- 将Terraform配置为可以操作AWS资源
-
- 安装Terraform
-
- 尝试使用Terraform启动EC2服务器
-
- 准备网络环境(VPC、子网、路由表、互联网网关)
-
- 设置安全组(防火墙)
-
- 启动Web服务器的EC2实例
- 在启动Web服务器时设置安装Web服务器软件的配置
本次的目標達成
让我们试着使用 Terraform 来启动 EC2 服务器。
第0步:创建工作目录
在用户目录下的任意位置创建terraform目录。(因为如果不在用户目录下会发生权限问题)
C:\Users[用户名]\Documents\MyProject\terraform
第一步:创建tf文件
文件名:main.tf(文件名可随意更改,其他名称也可以使用)
请按照以下方式创建文件。
provider "aws" {
profile = "terraform"
region = "ap-northeast-1"
}
resource "aws_instance" "web_server" {
ami = "ami-0cfc97bf81f2eadc4"
instance_type = "t2.micro"
tags = {
Name = "terraform-web-server"
}
步骤2. 初始化Terraform
执行该命令将会创建各种配置文件等等。
在中途需要输入”yes”。
$ terraform init
Initializing the backend...
Initializing provider plugins...
- Finding latest version of hashicorp/aws...
- Installing hashicorp/aws v5.5.0...
- Installed hashicorp/aws v5.5.0 (self-signed, key ID 34365D9472D7468F)
Partner and community providers are signed by their developers.
If you'd like to know more about provider signing, you can read about it here:
https://www.terraform.io/docs/cli/plugins/signing.html
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.
第三步:tf文件的格式。
建议您在编辑文件时,利用一个能够自动对齐缩进的便利命令,以便在适当的时机进行格式化,使其更加整洁。
$ terraform fmt
main.tf
可以看出,主.tf文件已经被格式化了。
第四步,检查执行tf文件时的更改内容。
当执行 Terraform 时,会对 AWS 资源进行更改,但有一种命令可仅确认更改内容而不应用更改本身。由于 AWS 使用费用高且拥有重要资产,因此应养成在执行前先确认 Terraform 内容是否可以安全应用的习惯。
$ terraform plan
An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
+ create
Terraform will perform the following actions:
# aws_instance.web_server will be created
+ resource "aws_instance" "web_server" {
+ ami = "ami-0cfc97bf81f2eadc4"
+ 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)
+ 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 = {
+ "Name" = "terraform-web-server"
}
+ tags_all = {
+ "Name" = "terraform-web-server"
}
+ 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 {
+ capacity_reservation_preference = (known after apply)
+ capacity_reservation_target {
+ capacity_reservation_id = (known after apply)
+ capacity_reservation_resource_group_arn = (known after apply)
}
}
+ cpu_options {
+ amd_sev_snp = (known after apply)
+ core_count = (known after apply)
+ threads_per_core = (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)
}
+ instance_market_options {
+ market_type = (known after apply)
+ spot_options {
+ instance_interruption_behavior = (known after apply)
+ max_price = (known after apply)
+ spot_instance_type = (known after apply)
+ valid_until = (known after apply)
}
}
+ maintenance_options {
+ auto_recovery = (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_card_index = (known after apply)
+ network_interface_id = (known after apply)
}
+ private_dns_name_options {
+ enable_resource_name_dns_a_record = (known after apply)
+ enable_resource_name_dns_aaaa_record = (known after apply)
+ hostname_type = (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.
------------------------------------------------------------------------
Note: You didn't specify an "-out" parameter to save this plan, so Terraform
can't guarantee that exactly these actions will be performed if
"terraform apply" is subsequently run.
详细的信息中写着要用名为terraform-web-server的名称创建EC2服务器!
步骤5. 尝试执行tf文件(create部分)。

通过在 “terraform apply” 命令后添加 “-auto-approve” 选项,无需输入 “yes”。
(如果担心的话,请不要添加 “-auto-approve” 选项)
$ terraform apply -auto-approve
aws_instance.web_server: Creating...
aws_instance.web_server: Still creating... [10s elapsed]
aws_instance.web_server: Still creating... [20s elapsed]
aws_instance.web_server: Still creating... [30s elapsed]
aws_instance.web_server: Creation complete after 32s [id=i-032d287a9619a06fe]
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
稍等一下,会显示一条消息,上面写着添加了一个资源(这次是EC2实例)!

第六步:尝试执行tf文件(销毁部分)
由于启动EC2服务器会花费金钱,所以最好将其删除。
删除也很容易,只需一个命令即可。
虽然在过程中需要输入”yes”,但通过添加”-auto-approve”选项,就不再需要输入”yes”了。
$ terraform destroy
An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
- destroy
Terraform will perform the following actions:
# aws_instance.web_server will be destroyed
- resource "aws_instance" "web_server" {
- ami = "ami-0cfc97bf81f2eadc4" -> null
- arn = "arn:aws:ec2:ap-northeast-1:146193870787:instance/i-032d287a9619a06fe" -> null
- associate_public_ip_address = true -> null
- availability_zone = "ap-northeast-1a" -> null
- cpu_core_count = 1 -> null
- cpu_threads_per_core = 1 -> null
- disable_api_stop = false -> null
- disable_api_termination = false -> null
- ebs_optimized = false -> null
- get_password_data = false -> null
- hibernation = false -> null
- id = "i-032d287a9619a06fe" -> 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
- placement_partition_number = 0 -> null
- primary_network_interface_id = "eni-09c10b073115e15d8" -> null
- private_dns = "ip-172-31-46-191.ap-northeast-1.compute.internal" -> null
- private_ip = "172.31.46.191" -> null
- public_dns = "ec2-13-113-106-156.ap-northeast-1.compute.amazonaws.com" -> null
- public_ip = "13.113.106.156" -> null
- secondary_private_ips = [] -> null
- security_groups = [
- "default",
] -> null
- source_dest_check = true -> null
- subnet_id = "subnet-0bf5fa8ca16b2b02e" -> null
- tags = {
- "Name" = "terraform-web-server"
} -> null
- tags_all = {
- "Name" = "terraform-web-server"
} -> null
- tenancy = "default" -> null
- user_data_replace_on_change = false -> null
- vpc_security_group_ids = [
- "sg-01a0b7a001e3c013e",
] -> null
- capacity_reservation_specification {
- capacity_reservation_preference = "open" -> null
}
- cpu_options {
- core_count = 1 -> null
- threads_per_core = 1 -> null
}
- credit_specification {
- cpu_credits = "standard" -> null
}
- enclave_options {
- enabled = false -> null
}
- maintenance_options {
- auto_recovery = "default" -> null
}
- metadata_options {
- http_endpoint = "enabled" -> null
- http_put_response_hop_limit = 2 -> null
- http_tokens = "required" -> null
- instance_metadata_tags = "disabled" -> null
}
- private_dns_name_options {
- enable_resource_name_dns_a_record = false -> null
- enable_resource_name_dns_aaaa_record = false -> null
- hostname_type = "ip-name" -> null
}
- root_block_device {
- delete_on_termination = true -> null
- device_name = "/dev/xvda" -> null
- encrypted = false -> null
- iops = 3000 -> null
- tags = {} -> null
- throughput = 125 -> null
- volume_id = "vol-07d3c71387a48c176" -> null
- volume_size = 8 -> null
- volume_type = "gp3" -> 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.web_server: Destroying... [id=i-032d287a9619a06fe]
aws_instance.web_server: Still destroying... [id=i-032d287a9619a06fe, 10s elapsed]
aws_instance.web_server: Still destroying... [id=i-032d287a9619a06fe, 20s elapsed]
aws_instance.web_server: Destruction complete after 30s
Destroy complete! Resources: 1 destroyed.
已经写明了详细信息,删除了名为terraform-web-server的EC2服务器!
