我想运行以下命令。定位模块时实质上是传递环境变量。
terraform plan -target module.network -var 'env=dev'
terraform apply -target module.network -var 'env=dev'
但是它抱怨该变量没有在根模块中声明,即使它是在模块文件夹本身中声明的。 然后,我尝试了不同的声明变量组合,但是没有运气。
这是我的文件和文件夹结构。
/main.tf
# Network (VPC, Gateway, Subnets, Security Groups)
module "network" {
source = "./modules/network"
}
/modules/network/vars.tf
variable "env" {
default = "dev"
}
variable "region" {
default = "us-east-1"
}
variable "subnet_cidr" {
type = list(string)
default = ["10.0.1.0/24","10.0.2.0/24","10.0.3.0/24"]
}
# Retrieve AZs Dynamically
data "aws_availability_zones" "azs" {}
/modules/network/main.tf
provider "aws" {
profile = "default"
region = var.aws_region
version = "2.26"
}
# Create VPC
resource "aws_vpc" "vpc" {
cidr_block = "10.0.0.0/16"
enable_dns_hostnames = true
enable_dns_support = true
tags = {
Name = "${var.env}-vpc"
}
}
# Create Subnets Dynamically from list
resource "aws_subnet" "subnets" {
count = "${length(var.subnet_cidr)}"
vpc_id = "${aws_vpc.vpc.id}"
cidr_block = "${element(var.subnet_cidr,count.index)}"
availability_zone = "${element(data.aws_availability_zones.azs.names,count.index)}"
tags = {
Name = "${var.env}-subnet-${count.index+1}"
}
}
# Create internet gateway to give our VPC access to the outside world
resource "aws_internet_gateway" "default" {
vpc_id = "${aws_vpc.vpc.id}"
tags = {
Name = "${var.env}-gateway"
}
}
# Grant the VPC internet access on its main route table
resource "aws_route" "internet_access" {
route_table_id = "${aws_vpc.vpc.main_route_table_id}"
destination_cidr_block = "0.0.0.0/0"
gateway_id = "${aws_internet_gateway.default.id}"
}
答案 0 :(得分:0)
使其正常工作。我能够将变量传递到网络模块。
以前,我将根模块和网络模块视为同一个作用域。来自根的变量需要传递到模块中。
variable "env" {
default = "dev"
}
variable "aws_region" {
default = "us-east-1"
}
# Network (VPC, Gateway, Subnets)
module "network" {
source = "./modules/network"
aws_region = var.aws_region
env = var.env
}
然后运行此命令。
terraform plan -target module.network -var 'env=dev'