Terraform模块-输出变量作为另一个模块的输入

时间:2020-09-25 13:54:37

标签: amazon-web-services terraform amazon-vpc terraform-modules

我是不熟悉terraform的人,正在尝试构建具有两个子网和VPC的基础架构。我已经创建了两个模块

  • VPC
  • 子网

VPC模块将创建一个VPC,并将返回vpc_id作为输出,与我试图在子网模块中使用的返回vpc_id相同,但是当我运行Terraform计划时,它要求我输入enter vpc_id输入。

我想从VPC模块的输出值中获取vpc_id,有人可以帮我吗?

下面是代码,

root tf文件,

 provider "aws" {
  shared_credentials_file = var.shared_cred
  profile                 = "default" 
  region                  = var.aws_region
}

module "vpc" {
  source = "./vpc"
  name   = "terraformVPC"
  cidr   = "10.50.40.0/27"
}

module "private_subnet" {
  source      = "./subnet"
  subnet_name = "private_subnet"
  subnet_cidr = "10.50.40.16/28"
  #VPC_id = aws_vpc.moduleVPC.id
  VPCid = module.vpc.outvpc_id # this is the issue
}

module "public_subnet" {
  source      = "./subnet"
  subnet_name = "public_subnet"
  subnet_cidr = "10.50.40.0/28"
  VPCid      = module.vpc.outvpc_id
}

子网资源

resource "aws_subnet" "module_subnet" {
  cidr_block = var.subnet_cidr
  vpc_id     = var.VPCid

  tags = {
    Name = var.subnet_name
  }
}

子网模块变量声明

variable "subnet_name" {
  description = " define th subnet name"
}

variable "subnet_cidr" {
  description = "define th subnet cidr block"
}

variable "VPCid" {
  description = "Assign VPC id to subnet"
}

VPC输出

output "outvpc_id" {
  value = "${aws_vpc.moduleVPC.id}"
}

3 个答案:

答案 0 :(得分:1)

当我将Terraform用于AWS时...我的模块名称是“ network.ts”,我认为您不需要两个tf文件来管理您的vpc和该VPC的子网。

network.tf

resource "aws_vpc" "vpc" {
  cidr_block           = "10.50.40.0/27"
  enable_dns_hostnames = true // only if you need
  tags                 = {
    Name = "desa-vpc-spotify" //Use your own name
  }
}

resource "aws_subnet" "private_subnet" {
  vpc_id            = aws_vpc.vpc.id
  availability_zone = "us-east-1a" //your own region
  cidr_block        = "10.50.40.16/28"
  tags = {
    Name = "desa-subnet-private-spotify"
  }
}

resource "aws_subnet" "public_subnet" {
  vpc_id            = aws_vpc.vpc.id
  availability_zone = "us-east-1a"//your own region
  cidr_block        = "10.50.40.0/28"
  tags = {
    Name = "desa-subnet-public-spotify"
  }
}

如果要在另一个tf上使用vpc

(如果您要拥有两个文件,请仅这样调用vpc)

another.tf

data "aws_vpc" "vpcs" {
  tags = {
    Name = "desa-vpc-spotify" //only put the name of the vpc of the network tf
  }
}


答案 1 :(得分:1)

这称为“Module Composition”。要记住的重要一点是您引用了另一个模块的输出

格式为:module.<object-name>.<output-name>

module "network" {
  source = "./modules/aws-network"

  base_cidr_block = "10.0.0.0/8"
}

module "consul_cluster" {
  source = "./modules/aws-consul-cluster"

  vpc_id     = module.network.vpc_id       # < output of module.network
  subnet_ids = module.network.subnet_ids   # < output of module.network
}

答案 2 :(得分:0)

我注意到您已列出“ VPCid =“。当您运行terraform validate时会引发错误吗?我会尝试将其更改为“ vpc_id”,看看是否可行。