Ssoon

[T101-4주차] 04 테라폼 모듈로 재사용 가능한 인프라 생성하기 - (5) 모듈주의사항 본문

Terraform 101 Study

[T101-4주차] 04 테라폼 모듈로 재사용 가능한 인프라 생성하기 - (5) 모듈주의사항

구구달스 2022. 11. 13. 13:36
CloudNet@ 팀의 가시다님이 진행하는 Terraform 101 Study 03주차 정리입니다.
 

GitHub - kschoi728/T101: Terraform 101 Study

Terraform 101 Study. Contribute to kschoi728/T101 development by creating an account on GitHub.

github.com

1️⃣ File Paths

 ✅ 기본적으로 테라폼은 현재 작업 중인 디렉터리를 기준으로 경로를 해석합니다.

 ✅ terraform apply 를 실행하는 디렉터리와 동일한 루트 module 에서 함수를 사용하는 것은 가능하지만, 별도의 폴더에 정의된 module 에서 함수를 사용할 수 없습니다.

 

📌 경로 참조 표현식 을 사용하여 해결할 수 있습니다.

path.<TYPE> 

path.module

표현식이 정의된 module 의 파일 시스템 경로를 반환합니다.

path.root

루트 module 의 파일 시스템 경로를 반환합니다.

path.cwd

현재 작업중인 디렉터리의 파일 시스템 경로를 반환합니다.

 

💠 user data script 의 경우 module 자체에 상대 경로가 필요합니다.

 modules/services/webserver-cluster/main.tf

   👉 templatefile 데이터 소스에서 path.module 사용을 사용합니다.

${path.module}/user-data.sh

user_data = templatefile("${path.module}/user-data.sh",

 

 

 

 

2️⃣ Inline Blocks

  ✅ module 을 만들 때는 항상 별도의 리소스를 사용하는 것이 좋습니다.

 modules/services/webserver-cluster/main.tf

   👉 "aws_security_group_rule" 리소스를 사용하여 수신 및 송신 규칙을 분리합니다.  

resource "aws_security_group" "ssoon_sg" {
  vpc_id = aws_vpc.ssoon_vpc.id
  name   = "${var.cluster_name}-SG"
}

resource "aws_security_group_rule" "ssoon_sginbound" {
  type              = "ingress"
  from_port         = local.http_port
  to_port           = local.http_port
  protocol          = local.tcp_protocol
  cidr_blocks       = local.all_ips
  security_group_id = aws_security_group.ssoon_sg.id
}

resource "aws_security_group_rule" "ssoon_sgoutbound" {
  type              = "egress"
  from_port         = local.any_port
  to_port           = local.any_port
  protocol          = local.any_protocol
  cidr_blocks       = local.all_ips
  security_group_id = aws_security_group.ssoon_sg.id
}

 

 modules/services/webserver-cluster/outputs.tf

   👉 aws_security_group 의 ID 를 출력 변수 (output vatiables) 로 정의합니다.

output "alb_security_group_id"

output "alb_security_group_id" {
    value = aws_security_group.ssoon_sg.id
    description = "the id of the sg attached to the lb"  
}

 stage/services/webserver-cluster/main.tf

   👉 aws_security_group_rule 리소스를 추가합니다.

module "webserver_cluster"

module "webserver_cluster" {
  source = "../../../modules/services/webserver-cluster"

security_group_id = module.webserver_cluster.alb_security_group_id

#! # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
#! aws_security_group_rule 추가설정
#! # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
resource "aws_security_group_rule" "ssoon_sginbound" {
  type              = "ingress"
  security_group_id = module.webserver_cluster.alb_security_group_id

  from_port         = 1234
  to_port           = 1234
  protocol          = "TCP"
  cidr_blocks       = ["1.2.3.4/32"]
}

 

🚩 Console 확인

Comments