Terraform module 의 output 값을 리소스 생성에 사용하는 법

LEE EUI JOO·2023년 3월 14일
0

terraform

목록 보기
1/2

시나리오

  • VPC module 사용해 리소스를 생성하고, 리소스 내의 요소들을 가져와 Security Group(보안그룹)을 생성하고 EC2 인스턴스를 생성하는 시나리오

플로우

  1. module 에서 여러 요소들이 들어간 리소스 생성

  2. 사용하고자 하는 요소들을 output 함수로 정의

  3. 다른 리소스를 생성하는 과정에서 output 의 value를 명시


VPC module

가져오고자 하는 요소

  • cidr
  • vpc 내의 public_subets
vpc.tf
*****
module "vpc" {
  source  = "terraform-aws-modules/vpc/aws"
  version = "3.19.0"

  name = "terraform-vpc"

  cidr = "10.10.0.0/16"
  azs  = ["ap-northeast-2a","ap-northeast-2c"]

  private_subnets = ["10.10.1.0/24", "10.10.2.0/24"]
  public_subnets  = ["10.10.11.0/24", "10.10.12.0/24"]

  enable_nat_gateway   = true
  one_nat_gateway_per_az = true
  enable_dns_hostnames = true

  public_subnet_tags = {
    "kubernetes.io/cluster/${local.cluster_name}" = "shared"
    "kubernetes.io/role/elb"                      = 1
  }

  private_subnet_tags = {
    "kubernetes.io/cluster/${local.cluster_name}" = "shared"
    "kubernetes.io/role/internal-elb"             = 1
  }
}

output 을 정의

output.tf
***
output "vpc_cidr_block" {
    description = "vpc_cider_block"
    value = module.vpc.vpc_cidr_block
}

output "public_subnets_ids" {
    description = "public_subnets"
    value = module.vpc.public_subnets
}

Security Group 에 사용

  • cidr_blocks 부분
security.tf
***
resource "aws_security_group" "bastion_sg" {
    name = "bastion_sg"
    description = "allow all"
    vpc_id = module.vpc.vpc_id

    ingress {
        description = "allow all !! eks"
        from_port = 0
        to_port = 0
        protocol = "-1"
        cidr_blocks = [module.vpc.vpc_cidr_block] ## [] 안에 명시
    }
    

    egress = [

        {
            description = "allow all"
            from_port = 0
            to_port = 0
            protocol = "-1"
            cidr_blocks = ["0.0.0.0/0"]
            ipv6_cidr_blocks = []
            aws_security_groups = []
            prefix_list_ids = []
            self = false
            security_groups = []
        }
    ]
    tags = {
        Name = "allow all"
    }
}

EC2 인스턴스 (Bastion Host) 에 사용

  • subnet_id 부분
resource "aws_instance" "bastion" {

  ami = "ami-0ff56409a6e8ea2a0"
  availability_zone = "ap-northeast-2a"
  instance_type = "t2.micro"
  key_name = "rapa"
  vpc_security_group_ids = [aws_security_group.bastion_sg.id]
  subnet_id = module.vpc.public_subnets[0]
  ## 첫번째 인덱스(퍼블릭서브넷들의 첫번째) 를 가져오기 위해 [0] 명시
  associate_public_ip_address = true

  tags = {
      Name = "bastion"
  }
}
profile
무럭무럭 자라볼까

0개의 댓글