IT/Terraform

[Terraform] 모듈에 있는 자원을 outputs으로 설정하는 방법 (feat. elb module과 asg)

반응형

Intro

Terraform에서 제공하는 모듈을 사용하게 되면 해당 경로의 .terraform/modules/모듈이름 으로 생성이 됩니다. 이 모듈안에서 생성한 리소스를 root의 output으로 정의하여 외부에서 사용할 수 있게 하는 방법을 알아 보도록 하겠습니다.

Layout 예시

my-workspace
├──elb
│  ├──.terraform
│  │  └──module
│  │  │     └──elb
│  │  │       ├──main.tf
│  │  │       ├──outputs.tf   ### 1. ELB 모듈의 ouptput
│  ├──main.tf
│  ├──outputs.tf              ### 2. ELB 루트의 ouptput
└──asg
    ├──data.tf                 ### 3. ASG 의 data
    ├──main.tf        ### 4. ASG 의 main

module 위치

terraform 에서 제공하는 module을 사용하면 일반적으로 /my-workspace/.terraform/module 에 위치해있습니다. module안에는 outputs.tf 이 기본적으로 포함되어있습니다.

  • 모듈 예시
module "aws_nlb" {
  source  = "terraform-aws-modules/alb/aws"
  version = "~> 6.0"
  internal = true

  name = "aws-nlb-example"

  load_balancer_type = "network"

....(생략)

}

ELB module의 outputs

elb 모듈로 targetgroup도 쉽게 생성할 수 있는데요. autoscling group 같은 리소스에서 targetgroup의 arn값을 가져와야 할 수도 있습니다. 이 경우 모듈안에 있는 outputs에 설정한 변수 target_group_arns 를 루트의 outputs에서 정의해 주어야 합니다.

## module에 있는 outputs
output "target_group_arns" {
  description = "ARNs of the target groups. Useful for passing to your Auto Scaling group."
  value       = aws_lb_target_group.main.*.arn
}

ELB 루트의 outputs

위에서 모듈안에 outputs을 정의 했다면 메인 outputs에서도 아래와 같이 정의해주어야 외부에서 사용이 가능합니다. 참고로 여기서 targetgroup이 여러개일 경우 리스트의 숫자를 정의해줘야 합니다.

output "nlb_target_group_arn" {
    value = module.aws_nlb.target_group_arns[0]
}

ASG의 data.tf

외부 폴더인 ASG(autoscaling group)에서 elb의 target group arn정보를 가져오기 위해서 data.tf를 아래와 같이 정의 합니다.

data "terraform_remote_state" "elb" {
    backend = "s3"
    config = {
        bucket = var.remote_state_bucket_name
        key = "elb/terraform.tfstate"
        region = var.region
    }   
}

ASG의 main.tf

그러면 최종적으로 ASG(autoscaling group) main.tf 파일에서 아래와 같이 data를 사용할 수 있습니다.

resource "aws_autoscaling_attachment" "asg_example_attach" {
  autoscaling_group_name = aws_autoscaling_group.asg_example.id
  alb_target_group_arn   = data.terraform_remote_state.elb.outputs.nlb_target_group_arn
}
반응형