1. 코드 작성
코드 작성
provider "aws"{ #Cloud 프로바이더
region = "us-east-2" #AWS 리전
}
resource "aws_instance" "example" {
ami = "ami-0a695f0d95cefc163" #아마존 머신 이미지 명
instance_type = "t2.micro" #인스턴스유형
}1. terraform init
테라폼에 코드를 스캔하여 어느 공급자인지 확인 후 필요한 코드를 다운로드
terrafrom init은 멱등성을 제공
PS C:\terraform_code> terraform init
Initializing the backend...
Initializing provider plugins...
- Finding latest version of hashicorp/aws...
- Installing hashicorp/aws v4.62.0...
- Installed hashicorp/aws v4.62.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!
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.2. terrafrom plan
plan 명령어를 사용하면 무언가를 변경하기 전에 테라폼이 수행할 작업을 확인할 수 있다.
실제 운영 환경에 적용하기 전에 코드의 온전성을 검사할 수 있는 좋은 방법
+가 있는 항목은 추가되고,
-가 있는 항목은 삭제된다는 뜻이다.
~가 있는 항목은 수정된다.
# aws_instance.example will be created
+ resource "aws_instance" "example" {
+ ami = "ami-0a695f0d95cefc163"
+ 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_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_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)
}
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.3. terrafrom apply
apply 명령어의 결과값은 plan과 같다.
이에 더해 apply 명령어는 이 plan을 진행 할 것인지 확인하라는 메시지를 출력한다.
PS C:\terraform_code> 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.example will be created
+ resource "aws_instance" "example" {
+ ami = "ami-0a695f0d95cefc163"
+ 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_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_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)
}
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... [10s elapsed]
aws_instance.example: Still creating... [20s elapsed]
aws_instance.example: Creation complete after 25s [id=i-07d289f80579cc336]
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.인스턴스 수정
provider "aws"{
region = "us-east-2"
}
resource "aws_instance" "example" {
ami = "ami-0a695f0d95cefc163"
instance_type = "t2.micro"
tags = {
Name = "terraform-example"
}
}aws_instance 리소스의 tags에 Name이라는 태그로 이름을 추가 후 terrafrom apply 실행
PS C:\terraform_code> terraform apply
aws_instance.example: Refreshing state... [id=i-07d289f80579cc336]
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-07d289f80579cc336"
~ tags = {
+ "Name" = "terraform-example"
}
~ tags_all = {
+ "Name" = "terraform-example"
}
# (30 unchanged attributes hidden)
# (7 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:테라폼은 구성 파일을 위해 생성된 모든 리소스를 추적하므로 EC2 인스턴스가 이미 존재한다는 것을 알고 있다. 테라폼은 apply 명령어를 실행할 때 'Refreshing state...'라는 메시지를 나타낸다. 그리고 현재 배포되어 있는 인프라의 내용과 테라폼 코드의 내용이 어떻게 다른지도 보여준다.
Enter a value: yes
aws_instance.example: Modifying... [id=i-07d289f80579cc336]
aws_instance.example: Modifications complete after 3s [id=i-07d289f80579cc336]
Apply complete! Resources: 0 added, 1 changed, 0 destroyed.
단일 웹서버 배포
provider "aws"{
region = "us-east-2"
}
resource "aws_instance" "example" {
ami = "ami-0a695f0d95cefc163"
instance_type = "t2.micro"
user_data = <<-EOF
#!/bin/bash
echo "Hello, World" >> index.html
nohup busybox httpd -f -p 8080 &
EOF
tags = {
Name = "terraform-example"
}
}<< -EOF 및 EOF는 테라폼의 히어닥(heredoc) 구문을 이용해 줄 바꿈 문자를 삽입하지 안혹도 여러 줄로 된 코드를 작성할 수 있다.
resource "aws_security_group" "instance"{
name = "terraform-example-instance"
ingress{
from_port = 8080
to_port = 8080
protocol = "tcp"
cidr_blocks = [ "0.0.0.0/0" ]
}
}생성된 EC2 인스턴스가 8080포트에서 트래픿을 수신하려면 보안 그룹을 생성해야 한다. 0.0.0.0/0에서 8080 포트로 들어오는 TCP 요청을 승인하도록 한다.
보안 그룹 생성 후 보안 그룹의 ID를 aws_instance 리소스의 vpc-security_group_ids 인수에 저장해야한다.
[PROVIDER]_[TYPE].[NAME].[ATTRIBUTE]
PROVIDER는 'aws' TYPE은 'security_group'과 같은 리소스의 유형 NAME은 보안 그룹 이름인 'instance'
같은 리소스의 이름 ATTRIBUTE는 'name'과 같은 리소스의 인수 중 하나이거나
리소스가 내보낸 속성 중 하나 보안 그룹은 id라는 속성을 내보낸다.
resource "aws_instance" "example" {
ami = "ami-0a695f0d95cefc163"
instance_type = "t2.micro"
vpc_security_group_ids = [aws_security_group.instance.id]
user_data = <<-EOF
#!/bin/bash
echo "Hello, World" >> index.html
nohup busybox httpd -f -p 8080 &
EOF
tags = {
Name = "terraform-example"
}
} 4. terrafrom graph
하나의 리소스에서 다른 리소스로 참조를 추가하면 내재된 종속성이 작성된다.
테라폼은 이러한 종속성 구문을 분석하여 종속성 그래프를 작성하고
이를 사용하여 리소스를 생성하는 순서를 자동으로 결정한다.
EC2 인스턴스가 보안 그룹의 ID를 참조하므로 코드를 처음 배포하는 경우
테라폼은 EC2 인스턴스를 생성하기 전에 먼저 보안 그룹을 만들어야 한다고 판단한다.
graph 명령을 실행하여 테라폼이 종속성 그래프를 표시할 수 있도록 할 수 있다.
digraph {
compound = "true"
newrank = "true"
subgraph "root" {
"[root] aws_instance.example (expand)" [label = "aws_instance.example", shape = "box"]
"[root] provider[\"registry.terraform.io/hashicorp/aws\"]" [label = "provider[\"registry.terraform.io/hashicorp/aws\"]", shape = "diamond"]
"[root] aws_instance.example (expand)" -> "[root] provider[\"registry.terraform.io/hashicorp/aws\"]"
"[root] provider[\"registry.terraform.io/hashicorp/aws\"] (close)" -> "[root] aws_instance.example (expand)"
"[root] root" -> "[root] provider[\"registry.terraform.io/hashicorp/aws\"] (close)"
}
}테라폼은 종속성 트리를 따라갈 때 가능한 한 많은 리소스를 병렬로 생성하므로 변경 사항을 매우 효율적으로 적용할 수 있다.
terrafrom apply하여 보안그룹 적용
aws_instance 리소스의 인수 중 대다수는 변경 시 대체를 강제 실행하므로,
원래 EC2 인스턴스가 종료되고 완전히 새로운 인스턴스가 생성된다.

Last updated