是否可以通过命令行为 Terraform 目标模块传递变量?

Is it possible to pass in variables for Terraform target modules via command line?

我想运行执行以下命令。本质上是在以模块为目标时传递环境变量。

terraform plan -target module.network -var 'env=dev'

terraform apply -target module.network -var 'env=dev'

但是它抱怨变量没有在根模块中声明,即使它是在模块文件夹本身中声明的。 然后我尝试了不同的声明变量组合,但没有成功。

  1. 在 /main.tf
  2. 中声明变量
  3. 在/terraform.tfvars
  4. 中设置变量

这是我的文件和文件夹结构。

/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}"
}

成功了。我能够将变量传递给网络模块。

以前,我将根模块和网络模块视为同一范围。来自根的变量需要传递到模块中。

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'