언제 쓰나?
versions.tf
terraform {
required_version = "~> 1.9"
required_providers { aws = { source = "hashicorp/aws", version = "~> 5.0" } }
}
provider "aws" { region = "ap-northeast-2" }
main.tf
# (예시) 보안그룹: 22/80 열기
resource "aws_security_group" "web" {
name = "web-sg"
vpc_id = var.vpc_id
ingress { from_port=22 to_port=22 protocol="tcp" cidr_blocks=["0.0.0.0/0"] }
ingress { from_port=80 to_port=80 protocol="tcp" cidr_blocks=["0.0.0.0/0"] }
egress { from_port=0 to_port=0 protocol="-1" cidr_blocks=["0.0.0.0/0"] }
}
# EC2 (퍼블릭 서브넷에 생성)
resource "aws_instance" "web" {
ami = data.aws_ssm_parameter.al2023.value
instance_type = "t3.micro"
subnet_id = var.public_subnet_id # IGW 경로 있는 서브넷
vpc_security_group_ids = [aws_security_group.web.id]
associate_public_ip_address = false # 임시 퍼블릭 IP는 끔 (EIP만 쓸 거라서)
tags = { Name = "web-with-eip" }
}
# 1) EIP "할당"(Allocation) - 리전에 공인 IPv4 확보
resource "aws_eip" "web" {
domain = "vpc" # 반드시 VPC
tags = { Name = "web-eip" }
}
# 2) EIP "연결"(Association) - 인스턴스(혹은 ENI)에 매핑
resource "aws_eip_association" "web" {
allocation_id = aws_eip.web.id
instance_id = aws_instance.web.id
# 대신 network_interface_id를 써서 특정 ENI/프라이빗 IP에 연결할 수도 있음
}
output "eip" { value = aws_eip.web.public_ip }
data&vars.tf (예시 AMI/입력)
data "aws_ssm_parameter" "al2023" {
name = "/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64"
}
variable "vpc_id" { type = string }
variable "public_subnet_id" { type = string }
참고:
aws_eip의instance인자를 직접 쓰는 방법도 있지만, 분리된aws_eip_association리소스를 권장(명확한 의도/변경 추적). (AWS 문서)
terraform init
terraform plan -out=plan.bin
terraform apply plan.bin
terraform output eip
# 브라우저/CLI로 확인
curl http://$(terraform output -raw eip)
추가 확인(AWS CLI):
aws ec2 describe-addresses --public-ips $(terraform output -raw eip)
SSH 접속(예: Amazon Linux)
ssh ec2-user@$(terraform output -raw eip)
통신 안 되면: 서브넷 라우트(0.0.0.0/0 → IGW), SG/NACL 규칙을 우선 점검하세요. (AWS 문서)
associate_public_ip_address=false 추천)EIP 할당은 “리전에 고정 공인 IP 예약”이고, **연결(Association)**은 그 IP를 인스턴스/ENI에 매핑하는 것.
인터넷 접근엔 퍼블릭 서브넷+IGW+보안 규칙이 필수, 2024년부터는 공인 IPv4 자체가 과금되니 꼭 필요한 곳에만 쓰자. (AWS 문서)