코드형 인프라(IaC)는 인프라 구성을 소프트웨어를 프로그래밍하는 것처럼 코드를 이용해 구축, 관리, 프로비저닝하는 방식을 말한다.
일관되게 반복되는 과정을 정확하고 잘 짜여진 코드를 통해 자동화하면 빠르게 구성/변경할 수 있고 실수를 줄일 수 있다.
테라폼은 프로그램 코드를 통해 인프라 서버를 구축/운영 할 수 있게 해주는 오픈 소스 소프트웨어 이다. (IaC Tool)
$ brew install terraform
// main.tf
provider "aws" {
region = "ap-northeast-2"
}
resource "aws_instance" "wkwak-terraform-instance" {
ami = "ami-0fd0765afb77bcca7"
instance_type = "t2.micro"
tags = {
Name = "wkwak-terraform-instance"
}
}
$ terraform plan
$ terraform 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.wkwak-terraform-instance: Creating...
aws_instance.wkwak-terraform-instance: Still creating... [10s elapsed]
aws_instance.wkwak-terraform-instance: Still creating... [20s elapsed]
aws_instance.wkwak-terraform-instance: Still creating... [30s elapsed]
aws_instance.wkwak-terraform-instance: Still creating... [40s elapsed]
aws_instance.wkwak-terraform-instance: Creation complete after 42s [id=i-0d651008526c70eae]
.terraform
*.tfstate
*.tfstate.backup
variable "server_port" {
description = "The port the server will use for HTTP requests"
type = number
default = 8081
}
변수를 선언할때 3개의 매개 변수가 포함될 수 있지만, 선택적 매개 변수이다.
-> default가 없다면 server_port
에 값을 입력하라는 메시지를 입력하라는 표시가 나온다.
$ terraform plan
var.server_port
The port the server will use for HTTP requests
Enter a value: 8081
-> 대화식으로 명령어를 처리하지 않으려면 명령줄의 -var 옵션으로 변수 값을 제공할 수 있다.
$ terraform plan -var "server_port=8081"
-> TF_VAR_{변수이름}
이라는 환경 변수를 통해 변수를 설정할 수도 있다.
$ export TF_VAR_server_port=8081
$ terraform plan
변수를 선언한 후 테라폼 코드에서 변수를 사용하려면 변수 참조(variable reference)
라는 표현식을 사용할 수 있다.
var.<VARIABLE_NAME>
ingress {
from_port = var.server_port
protocol = "tcp"
to_port = var.server_port
cidr_blocks = ["0.0.0.0/0"]
}
문자열 리터럴 내에서 변수 참조를 사용하려면 보간(interpolation)
이라는 표현식을 사용해야 한다.
"${...}"
user_data = <<-EOF
#!/bin/bash
echo "Hello, World" > index.html
nohup busybox httpd -f -p ${var.server_port} &
EOF
테라폼은 입력 변수뿐만 아니라 출력 변수도 정의할 수 있다.
output "<NAME>" {
value = <VALUE>
[CONFIG ...]
}
output "public_ip" {
value = aws_instance.wkwak-terraform-instance.public_ip
description = "The public IP address of the web server"
}
$ terraform apply
...
Outputs:
public_ip = "15.164.214.250"
terraform ouput 명령어를 사용하여 변경 사항을 적용하지 않고 결괏값을 나열할 수도 있다.
$ terraform output <OUTPUT_NAME>
or
$ terraform output
public_ip = "15.164.214.250"
terraform apply하고난후
still creating 이 1시간이고 2시간이고 넘게 돕니다. 이유가 뭘까요 ㅠ