这是我的目录结构:
├── main.tf
├── modules
│ ├── subnets
│ │ ├── main.tf
│ │ ├── outputs.tf
│ │ └── variables.tf
│ ├── variables.tf
│ └── vpc
│ ├── main.tf
│ ├── outputs.tf
│ └── variables.tf
├── outputs.tf
└── variables.tf
和我的modules/vpc/main.tf
resource "aws_vpc" "env_vpc" {
cidr_block = "${var.vpc_cidr_block}"
enable_dns_support = "${var.vpc_enable_dns_support}"
enable_dns_hostnames = "${var.vpc_enable_dns_hostnames}"
tags = {
Name = "${var.env_name}-vpc"
Provisioner = "Terraform"
}
lifecycle {
create_before_destroy = true
}
}
和我的modules/vpc/variables.tf
variable "env_name" {
description = "The name of the env the VPC will belong to"
# no default provided
}
当我执行terraform plan
➢ terraform plan
Error: Missing required argument
on main.tf line 1, in module "vpc":
1: module "vpc" {
The argument "env_name" is required, but no definition was found.
当我在cmd中传递var时:
➢ terraform plan -var 'env_name=ffff'
Error: Value for undeclared variable
A variable named "env_name" was assigned on the command line, but the root
module does not declare a variable of that name. To use this value, add a
"variable" block to the configuration.
即使我在根variables.tf
中声明变量,问题也不会消失
如
➢ cat variables.tf
variable "env_name" {}
有什么建议吗?
编辑:当我为该变量提供一个default
值时,plan
起作用了。它是否交互地问我一个env_name
的值,但是plan
的输出却是default
的值。为什么会这样?
edit2 :对variables.tf
文件内容的说明:
➢ ls
main.tf modules outputs.tf variables.tf
➢ cat variables.tf
variable "env_name" {}
在modules/vpc
目录中:
➢ ls
main.tf outputs.tf variables.tf
aws_vpc/modules/vpc stand_alone_vpc ✗
➢ cat variables.tf
variable "env_name" {
description = "The name of the environment/microservice the VPC will belong to"
default = "wbl"
}
我要求输入env_name
值,但它忽略,并使用{{ 1}}。这是default
:
modules/vpc/variables.tf
答案 0 :(得分:1)
看来,解决该问题的方法(即能够覆盖子模块default
中设置的variable.tf
值)如下:
1 ),在顶级(根)variables.tf
中声明变量,如
> $ cat variables.tf
variable "env_name" {
default = "top-level"
}
2 )在调用子模块的root模块main.tf
的部分中声明变量,如:
module "vpc" {
source = "./modules/vpc"
# variables
env_name = "${var.env_name}"
}
这样,最终将在子模块中传递的变量是在父模块的variables.tf
中声明的变量