Git : https://github.com/idealistchanu/study-T101Study/tree/main/CHAPTER2
[GitHub - idealistchanu/study-T101Study
Contribute to idealistchanu/study-T101Study development by creating an account on GitHub.
github.com](https://github.com/idealistchanu/study-T101Study/tree/main/CHAPTER2)
# Terraform 배포 List 확인
terraform state list
# VPC 확인
export AWS_PAGER=""
aws ec2 describe-vpcs | jq
aws ec2 describe-vpcs --output yaml
# 서브넷 확인
aws ec2 describe-subnets --output text
# 참고 : aws ec2 describe-subnets --filters "Name=vpc-id,Values=vpc-<자신의 VPC ID>"
VPCID=vpc-0b288d2d8ba619df9
aws ec2 describe-subnets --filters "Name=vpc-id,Values=$VPCID" | jq
# 라우팅 테이블 확인
#aws ec2 describe-route-tables --filters 'Name=tag:Name,Values=t101-rt' --query 'RouteTables[].Associations[].SubnetId'
aws ec2 describe-route-tables --filters 'Name=tag:Name,Values=t101-rt' --output table
# ASG 시작 구성, AS 그룹 정보 확인
aws autoscaling describe-auto-scaling-groups --auto-scaling-group-names | jq
aws autoscaling describe-auto-scaling-groups --auto-scaling-group-names --output table
aws autoscaling describe-auto-scaling-groups --auto-scaling-group-names myasg| jq
aws autoscaling describe-scaling-activities --auto-scaling-group-name myasg | jq
# ALB 정보 확인
aws elbv2 describe-load-balancers --output table
aws elbv2 describe-load-balancers | jq
# [터미널1] EC2 생성 모니터링
# macOS
export AWS_PAGER=""
while true; do aws ec2 describe-instances --query "Reservations[*].Instances[*].{PublicIPAdd:PublicIpAddress,InstanceName:Tags[?Key=='Name']|[0].Value,Status:State.Name}" --filters Name=instance-state-name,Values=running --output text ; echo "------------------------------" ; sleep 1; done
#해당 DNS 주소로 지속 요청
ALBDNS=$(terraform output -raw myalb_dns)
while true; do curl --connect-timeout 1 http://$ALBDNS/ ; echo; echo "------------------------------"; date; sleep 1; done
# ALB DNS주소로 curl 접속 확인
ALBDNS=$(terraform output -raw myalb_dns)
for i in {1..100}; do curl -s http://$ALBDNS/ ; done | sort | uniq -c | sort -nr
# EC2 최소 2대 => 3대로 증가 수정
sed -i -e 's/min_size = 2/min_size = 3/g' asg.tf데이터 소스 Data
data “<PROVIDER>_<TYPE>” “<NAME>” {
[CONFIG …]
}
- PROVIDER : aws 같은 공급자의 이름
- TYPE : vpc 같은 사용하려는 데이터 소스의 유형
- NAME : 테라폼 코드에서 이 데이터 소스를 참조하는 데 사용할 수 있는 식별자
- CONFIG : 해당 데이터 소스에 고유한 하나 이상의 인수로 구성됨
# 예시
data “aws_vpc” “default” {
default = true
}
데이터 소스에서 데이터를 가져오려면 다음과 같은 속성 참조 구문
data.<PROVIDER>_<TYPE>.<NAME>.<ATTRIBUTE>
# 예시
data.aws_vpc.default.id
# ASG와 Subnet 설정에 대한 예시
data "aws_subnets" "default" {
filter {
name = "vpc-id"
values = [data.aws_vpc.default.id]
}
}
resource "aws_autoscaling_group" "example" {
launch_configuration = aws_launch_configuration.example.name
vpc_zone_identifier = data.aws_subnets.default.ids
min_size = 2
max_size = 10
tag {
key = "Name"
value = "terraform-asg-example"
propagate_at_launch = true
}
}일반적으로 리소스 교체 시, 삭제 -> 업데이트 이지만 Auto scaling group 의 경우엔 Subnet ID에 대한 참조가 있어서 Terraform은 해당 리소스를 삭제할 수 없다.
이 문제 해결을 위해, 수명주기(Lifecycle을 사용한다.)

create_before_destroy 를 true 로 설정하면 테라폼은 리소스를 교체하는 순서를 반대로 하여 교체 리소스를 먼저 생성하고(이전 리소스가 가리키고 있던 참조를 업데이트하여 교체한 리소스를 가리킴) 기존 리소스를 삭제합니다.
resource "aws_launch_configuration" "example" {
image_id = "ami-0e9bfdb247cc8de84"
instance_type = "t2.micro"
security_groups = [aws_security_group.instance.id]
user_data = <<-EOF
#!/bin/bash
echo "Hello, World" > index.html
nohup busybox httpd -f -p ${var.server_port} &
EOF
# Required when using a launch configuration with an auto scaling group.
lifecycle {
create_before_destroy = true
}
}소스 코드에 ALB + ASG 로 aws_autoscaling_group에 health_check_type을 ELB로 주었기 때문에
EC2불량 시, 자동으로 인스턴스가 교체된다.
다룬 리소스
VPC(aws_vpc)
Subnets (aws_subnet)
Internet Gateway (aws_internet_gateway)
Route Table (aws_route_table)
Route Table Association (aws_route_table_association)
Route (aws_route)
Security Group (aws_security_group)
Security Group Rule (aws_security_group_rule)
Lunch Configuration (aws_launch_configuration)
Autoscaling Group (aws_autoscaling_group)
Load Balancer (aws_lb)
Load Balancer Listener (aws_lb_listener)
Load Balancer Target Group (aws_lb_target_group)
Load Balancer Listener Rule (aws_lb_listener_rule)
추가로 다뤄볼 리소스
ACM(aws_acm_certificate)
NLB(aws_lb)
NLB 추가하다보면 이런 이슈들을 만나는데,

creating ELBv2 Listener (arn:aws:elasticloadbalancing:ap-northeast-2:310600283911:loadbalancer/net/t101-nlb/8ff3f17a24dc2187): IncompatibleProtocols: The listener and the following target groups have incompatible protocols
aws_lb_listener_rule 없고 protocol과 healthcheck의 protocol 등을 일치 시켜줘야한다. (ALB를 위함)
# nlb.tf
resource "aws_lb" "mynlb" {
name = "t101-nlb"
internal = false
load_balancer_type = "network"
subnets = [aws_subnet.mysubnet1.id, aws_subnet.mysubnet2.id]
#security_groups = [aws_security_group.mysg.id]
tags = {
Environment = "test"
}
}
resource "aws_lb_target_group" "mynlbtg" {
name = "t101-nlb-tg"
port = 443
protocol = "TLS"
vpc_id = aws_vpc.myvpc.id
health_check {
path = "/"
protocol = "HTTPS"
matcher = "200-299"
interval = 5
timeout = 3
healthy_threshold = 2
unhealthy_threshold = 2
}
}
resource "aws_lb_listener" "myhttps" {
load_balancer_arn = aws_lb.mynlb.arn
port = "443"
protocol = "TLS"
certificate_arn = "arn:aws:acm:ap-northeast-2:310600283911:certificate/90b32e4b-fd19-440a-b9d2-e02e3b3e9ab9"
alpn_policy = "HTTP2Preferred"
default_action {
type = "forward"
target_group_arn = aws_lb_target_group.mynlbtg.arn
}
}
# resource "aws_lb_listener_rule" "mynlbrule" {
# listener_arn = aws_lb_listener.myhttps.arn
# priority = 100
# condition {
# path_pattern {
# values = ["*"]
# }
# }
# action {
# type = "forward"
# target_group_arn = aws_lb_target_group.mynlbtg.arn
# }
# }
output "mynlb_dns" {
value = aws_lb.mynlb.dns_name
description = "The DNS Address of the NLB"
}'Infrastructure as Code > Terraform' 카테고리의 다른 글
| [T101 Study 3주차] 상태 파일 격리 방안 (2) | 2022.11.22 |
|---|---|
| [T101 Study 3주차] 상태 관리 (0) | 2022.11.21 |
| [T101 Study 중간 과제] Terraforming (0) | 2022.11.12 |
| [T101 Study 1주차 도전 과제] 기본 틀 배포 (0) | 2022.11.07 |
| [T101 Study 1주차] Terraform 용어 정리 및 기초 및 설치 (1) | 2022.11.07 |