IaC
모두의 Terraform(테라폼) PART 3 - EC2 만들기
팬도라
2023. 3. 21. 13:50
반응형
EC2 생성하기
위의 설정이 잘 되었는지 확인하기 위해서 EC2 1대를 생성하는 테라폼 코드를 작성하겠습니다.
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 4.16"
}
}
required_version = ">= 1.2.0"
}
provider "aws" {
region = "ap-northeast-2"
}
resource "aws_instance" "app_server" {
ami = "ami-013218fccb68a90d4"
instance_type = "t2.micro"
tags = {
Name = "ExampleAppServerInstance"
}
}
init, plan, apply 순서로 테라폼을 적용합니다. 각 항목에 대한 설명은 다음 챕터에서 진행합니다.
terraform init
Initializing the backend...
Initializing provider plugins...
- Finding hashicorp/aws versions matching "~> 4.16"...
- Installing hashicorp/aws v4.52.0...
- Installed hashicorp/aws v4.52.0 (signed by HashiCorp)
...
Terraform has been successfully initialized!
...
terraform plan
erraform 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:
...
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.
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.app_server will be created
...
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.app_server: Creating...
aws_instance.app_server: Creation complete after 31s [id=i-052eefff0e7fcebd2]
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
AWS EC2에 접속하면 ExampleAppServerInstance 이름의 EC2가 생성된 것을 확인할 수 있습니다.
마지막으로 생성된 EC2 리소스를 삭제해 보겠습니다.
terraform destroy
aws_instance.app_server: Refreshing state... [id=i-052eefff0e7fcebd2]
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.app_server will be destroyed
...
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.app_server: Destroying... [id=i-052eefff0e7fcebd2]
Destroy complete! Resources: 1 destroyed.
위에서 생성한 테라폼 코드가 실행되지 않는다면, AWS 기본 VPC를 삭제했을 가능성이 높습니다. 이에 "AWS -> VPC -> 작업 -> 기본 VPC 생성"을 통해 172.31.0.0/16
범위를 가지는 기본 VPC를 생성하시길 바랍니다.