Search
Duplicate
📒

[Terraform] 03-x. Module

상태
완료
수업
Terraform
주제
기본개념
4 more properties
참고

Terraform Module

NOTE
모듈은 함꼐 사용되는 여러 리소스의 컨테이너다.
모듈 예시 이미지
모듈은 관련 있는 요소끼리 모아 하나의 패키지를 만든다.
ex) VPC 모듈의 경우 서브넷, netmask 등의 리소스를 하나의 패키징을 한다.

모듈의 장점

NOTE
중복되는 코드를 모듈화시킴!
캡슐화
서로 관련이 있는 요소들 끼리만 캡슐화를 하여 의도치 않은 문제 발생을 예방할 수 있다.
재사용성
모듈을 사용하여 리소스를 정의하면 다른 환경에서도 해당 리소스를 쉽게 재사용할 수 있다.
일관성
매번 새로 작성하게 되면 사람에 따라 리소스의 옵션이 빠지는 부분이 생길수도 있고, 매번 같을 수 없기에 모듈을 재 사용시 일관성을 가지게 된다.

모듈의 기본 구문 예시

NOTE
module "<NAME>" { source = "<SOURCE>" [CONFIG...] }
Ruby
복사
위와 같은 구문을 사용하여 경로를 지정하여 참조
provider "google" { credentials = file("key.json") project = "terraform-348208" region = "asia-northeast3" } module "webserver_cluster" { source = "../../../modules/services/webserver-cluster" }
Ruby
복사
source 경로로 module참조

모듈 입력

NOTE
테라폼의 모듈에서도 입력 매개 변수를 만들어 사용할 수 있다.
variable "cluster_name" { description = "The name to use for all the cluster resources" type = string } # var로 사용 (${}쓴 이유는 ""내부라서) resource "aws_security_group" "instance" { name = "${var.cluster_name}-instance" }
Ruby
복사
module내에서 변수를 받아서 사용
module "webserver_cluster" { source = "../modules/webserver-cluster" cluster_name = "webserver-prod" }
Ruby
복사
cluster_name에 관해 변수삽입

모듈 지역 변수

NOTE
변수를 입력받는 대신 공통적으로 사용하고 있는 값들은 지역변수로 정의하여 사용할 수 있다.
local.<NAME>
Ruby
복사
locals { http_port = 80 any_port = 0 any_protocol = "-1" tcp_protocol = "tcp" all_ips = ["0.0.0.0/0"] } # loclas에 정의된 변수사용 resource "aws_security_group_rule" "allow_http_inbound" { type = "ingress" security_group_id = aws_security_group.alb.id from_port = local.http_port to_port = local.http_port protocol = local.tcp_protocol cidr_blocks = local.all_ips }
Ruby
복사

모듈 출력 변수

NOTE
테라폼에서 모듈 값을 참조하여 사용할 수 있다!
output "asg_name" { value = aws_autoscaling_group.example.name description = "The name of the Auto Scaling Group" }
Ruby
복사
모듈에서 ouput 선언
module.<MODULE_NAME>.<OUTPUT_NAME>
Ruby
복사
module "webserver_cluster" { source = "../../../modules/services/webserver-cluster" } resource "aws_autoscaling_schedule" "scale_out_during_business_hours" { scheduled_action_name = "scale-out-during-business-hours" min_size = 2 max_size = 10 desired_capacity = 10 recurrence = "0 9 * * *" autoscaling_group_name = module.webserver_cluster.asg_name }
Ruby
복사
webserver_cluster에서 asg_name을 output으로 내보낸걸 사용