Terraform:需要参数,但未找到

时间:2019-09-30 18:23:27

标签: terraform

这是我的目录结构:

├── 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文件内容的说明:

  • root 目录上:
➢  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

1 个答案:

答案 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中声明的变量