본문 바로가기
공부/IaC

[Terraform on AWS] Routing Module Example

by haejang 2021. 10. 3.
728x90
728x90

 

21.11.5 수정

 

https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/route

 

https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/route

 

registry.terraform.io

 

Terraform AWS Routing은 대상의 종류에 따라 들어가야 할 옵션이 다르다

옵션 자체가 다르다 보니 삼항 구문을 이용한 조건문을 생성해 case처럼 사용할 수 있게 만들어야 했다

 

modules/main.tf

variable "routings" {}
variable "rt_id" {}
variable "gateway" {
  default = ["igw", "vgw"]
}


resource "aws_route" "routing" {
  for_each       = var.routings  
  route_table_id = var.rt_id

  destination_cidr_block     = length(regexall("[a-z]",each.value.dst_cidr)) == 0 ? each.value.dst_cidr : null
  destination_prefix_list_id = substr(each.value.dst_cidr,0,2) == "pl" ? each.value.dst_cidr : null

  gateway_id                = contains(var.gateway, substr(each.value.dst_id,0,3)) ? each.value.dst_id : null
  instance_id               = substr(each.value.dst_id,0,2) == "i-" ? each.value.dst_id : null
  nat_gateway_id            = substr(each.value.dst_id,0,3) == "nat" ? each.value.dst_id : null
  vpc_endpoint_id           = substr(each.value.dst_id,0,4) == "vpce" ? each.value.dst_id : null
  transit_gateway_id        = substr(each.value.dst_id,0,3) == "tgw" ? each.value.dst_id : null
  vpc_peering_connection_id = substr(each.value.dst_id,0,3) == "pcx" ? each.value.dst_id : null
}

 

regexall : https://www.terraform.io/docs/language/functions/regexall.html

substr : https://www.terraform.io/docs/language/functions/substr.html

contains : https://www.terraform.io/docs/language/functions/contains.html

 

routing.tf

module "pub_routing" {
    source = "./modules/route"
    rt_id = module.pub_subnet.rt_id
    routings = {
        igw = {
            dst_cidr = "0.0.0.0/0",
            dst_id = module.igw.id
        },
        s3 = {
            dst_cidr = "pl-78a54011",
            dst_id = module.vpce.s3.id
        },
    }
}

module "pri_routing" {
    source = "./modules/route"
    rt_id = module.pub_subnet.rt_id
    routings = {
        igw = {
            dst_cidr = "0.0.0.0/0",
            dst_id = module.nat.nat_id
        },
        s3 = {
            dst_cidr = "pl-78a54011",
            dst_id = module.vpce.s3.id
        },
    }
}

 

 

 

 

728x90
728x90

댓글