Terraform 설치

Visial Studio 실행 => Extensions => hashicop terraform 검색 및 설치

Terraform의 버전 확인

terraform version
erraform v0.13.4
Your version of Terraform is out of date! The latest version
is 0.14.7. You can update by downloading from https://www.terraform.io/downloads.html

Terraform 코드 파일 확인

root@workstation:~/hashicat-aws# ls *.tf
main.tf outputs.tf variables.tf

Terraform Work Space

테라폼 작업 공간은 단순히 테라폼 코드가 포함된 폴더 또는 디렉토리 입니다.

main.tf- 대부분의 Terraform 코드가 저장되는 위치입니다. 이것은 자원을 구축하는 부분입니다.
variables.tf- 이 파일을 사용하여 사용자가 사용할 수있는 변수를 정의합니다.
outputs.tf- Terraform 실행이 끝날 때 표시되는 내용을 정의합니다.

Terraform init

Terraform은 필요한 공급자와 모듈을 가져와 .terrform 디렉토리에 저장합니다.
모듈 또는 공급자를 추가, 변경 또는 업데이트 하는 경우 init를 다시 실행해야 합니다.

ls .terraform/plugins
.terraform 숨겨진 디렉토리는 모든 모듈과 플러그인이 저장되는 곳입니다.

Terraform main.tf 구성

Terraform 코드 유효성 검사

root@workstation:~/hashicat-aws# terraform validate
Success! The configuration is valid.

Terraform Plan – Dry Run Mode

변경 사항을 적용하기 전에 Terraform plan으로 미리볼 수 있습니다.

root@workstation:~/hashicat-aws# terraform plan
var.prefix
This prefix will be included in the name of most resources.

Enter a value: comtec

Refreshing Terraform state in-memory prior to plan...
The refreshed state will be used to calculate this plan, but will not be
persisted to local or remote state storage.


------------------------------------------------------------------------

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_vpc.hashicat will be created
+ resource "aws_vpc" "hashicat" {
+ arn = (known after apply)
+ assign_generated_ipv6_cidr_block = false
+ cidr_block = "10.0.0.0/16"
+ default_network_acl_id = (known after apply)
+ default_route_table_id = (known after apply)
+ default_security_group_id = (known after apply)
+ dhcp_options_id = (known after apply)
+ enable_classiclink = (known after apply)
+ enable_classiclink_dns_support = (known after apply)
+ enable_dns_hostnames = true
+ enable_dns_support = true
+ id = (known after apply)
+ instance_tenancy = "default"
+ ipv6_association_id = (known after apply)
+ ipv6_cidr_block = (known after apply)
+ main_route_table_id = (known after apply)
+ owner_id = (known after apply)
+ tags = {
+ "name" = "comtec-vpc-us-east-1"
}
}

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 변수 작업

Terraform에서는 사용하기 전에 모든 변수를 선언해야합니다.
변수는 다른 "* .tf"파일에서도 선언 할 수 있지만 일반적으로 "variables.tf"파일에서 선언됩니다.

[ 다양한 변수 설정 지원 : 변수 우선순위. 1번이 우선순위 제일 높음 ]
1. Command Line - 명령 줄 스위치로 실행
2. Configuration File - Terraform.tfvars 구성 파일에 설정
3. Environment variable - 쉘 환경의 일부로 설정
4. Default Config - variables.tf의 기본값으로 설정
5. User manual entry - 지정되지 않은 경우 사용자에게 입력을 요청합니다.

Terraform.tfvars 작성

이제 terraform plan다시 실행 하면, 접두사를 수동으로 입력 할 필요가 없습니다.

Variables.tf 작성

Terraform.tfvars파일에 리전 변수 사용

“variables.tf”파일에 선언 된 모든 변수에 대한 값을 설정할 수 있습니다. terraform plan 실행

Terraform Graph 사용 하기(참고) : https://dreampuf.github.io/GraphvizOnline/

terraform graph
blast-radius --serve .
인프라에 대한 Terraform 그래프를 살펴보세요. 종속성이 자동으로 매핑됩니다.  이 그래프는 무료 Blast Radius 도구를 사용하여 생성되었습니다.

Terraform 설정 적용(Apply)

root@workstation:~/hashicat-aws# terraform apply

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_vpc.hashicat will be created
+ resource "aws_vpc" "hashicat" {
+ arn = (known after apply)
+ assign_generated_ipv6_cidr_block = false
+ cidr_block = "10.0.0.0/16"
+ default_network_acl_id = (known after apply)
+ default_route_table_id = (known after apply)
+ default_security_group_id = (known after apply)
+ dhcp_options_id = (known after apply)
+ enable_classiclink = (known after apply)
+ enable_classiclink_dns_support = (known after apply)
+ enable_dns_hostnames = true
+ enable_dns_support = true
+ id = (known after apply)
+ instance_tenancy = "default"
+ ipv6_association_id = (known after apply)
+ ipv6_cidr_block = (known after apply)
+ main_route_table_id = (known after apply)
+ owner_id = (known after apply)
+ tags = {
+ "name" = "comtec-vpc-eu-west-2"
}
}

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_vpc.hashicat: Creating...
aws_vpc.hashicat: Still creating... [10s elapsed]
aws_vpc.hashicat: Creation complete after 12s [id=vpc-0d769ecf78d4a3e6b]

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

이제, Terraform을 통해 AWS VPC(10.0.0.0/16) 생성이 완료 되었습니다.

설정 변경 없이 Terraform 설정 적용 하면?

root@workstation:~/hashicat-aws# terraform plan
Refreshing Terraform state in-memory prior to plan...
The refreshed state will be used to calculate this plan, but will not be
persisted to local or remote state storage.

aws_vpc.hashicat: Refreshing state... [id=vpc-0d769ecf78d4a3e6b]

------------------------------------------------------------------------

No changes. Infrastructure is up-to-date.

This means that Terraform did not detect any differences between your
configuration and real physical resources that exist. As a result, no
actions need to be performed.

VPC가 이미 빌드되었으므로 Terraform은 변경이 필요하지 않다고보고합니다.

root@workstation:~/hashicat-aws# terraform apply
aws_vpc.hashicat: Refreshing state... [id=vpc-0d769ecf78d4a3e6b]

Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

Terraform은 각 리소스가 적절한 상태인지 확인합니다.
이미 올바르게 프로비저닝 된 경우 VPC를 다시 생성하지 않습니다.

VPC Tag 추가 하기

main.tf 파일을 열어 tags 밑에 enviroment = “Prodution” 태그를 추가합니다.
terraform apply
~ tags = {
+ "environment" = "Production"
"name" = "0-vpc-eu-west-2"

Apply complete! Resources: 0 added, 1 changed, 0 destroyed.

Hashicat 어플리케이션 배포

main.tf 파일 내용 추가
terraform plan
terraform apply -auto-approve
Apply complete! Resources: 1 added, 0 changed, 1 destroyed.
Outputs:
catapp_url = http://ec2-18-135-230-22.eu-west-2.compute.amazonaws.com

Terraform Graph를 통한 변경 내역 확인(옵션)

main.tf 코드 편집(2줄 추가)

  provisioner "remote-exec" {
   inline = [
     "sudo add-apt-repository universe",
     "sudo apt -y update",
     "sudo apt -y install apache2",
     "sudo systemctl start apache2",
     "sudo chown -R ubuntu:ubuntu /var/www/html",
     "chmod +x *.sh",
     "PLACEHOLDER=${var.placeholder} WIDTH=${var.width} HEIGHT=${var.height} PREFIX=${var.prefix} ./deploy_app.sh",
 "sudo apt -y install cowsay",
 "cowsay Mooooooooooo!",
    ]

일반적으로 위처럼 추가 시 띄어쓰기 오류가 발생하겠지만,
terraform에서는 terraform fmt명령을 사용하여 자동 정렬 시키 수 있습니다.

Terraform fmt 자동 정렬

root@workstation:~/hashicat-aws# terraform fmt
main.tf

 provisioner "remote-exec" {
   inline = [
     "sudo add-apt-repository universe",
     "sudo apt -y update",
     "sudo apt -y install apache2",
     "sudo systemctl start apache2",
     "sudo chown -R ubuntu:ubuntu /var/www/html",
     "chmod +x *.sh",
     "PLACEHOLDER=${var.placeholder} WIDTH=${var.width} HEIGHT=${var.height} PREFIX=${var.prefix} ./deploy_app.sh",
     "sudo apt -y install cowsay",
     "cowsay Mooooooooooo!",
   ]

명령 실행 시 자동으로 정렬된것을 확인할 수 있다.
변경사항 적용
terraform apply -auto-approve

Terraform refresh 명령을 통한 새 출력 확인

outputs.tf 를 열어 수정
# Outputs file
output "catapp_url" {
value = "http://${aws_eip.hashicat.public_ip}"
}

root@workstation:~/hashicat-aws# terraform refresh

Outputs:
catapp_url = http://18.135.230.22

root@workstation:~/hashicat-aws# terraform output
catapp_url = http://18.135.230.22