I would like to run the following commands. Essentially passing an environment variable when targeting a module.
terraform plan -target module.network -var 'env=dev'
terraform apply -target module.network -var 'env=dev'
However it complains the variable is not declared in the root module even though it is declared in the module folder itself. I then tried different combinations of declaring variables with no luck.
- Declaring the variable within /main.tf
- Setting the variables within /terraform.tfvars
Here is my file and folder structure.
/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}"
}