大地化模块中的常见变量用法



我正在编写地形脚本以在 AWS 上创建 ASG。我尝试使用terraformmodule创建它,以获得更可重用的代码。问题是当我想在模块 tf 文件上使用common-variable.tfvars中的变量时,它一直说它是未定义的,需要声明。这样,模块将 不那么可重用 .

这是一个例子

root
|
|___project 1
|     |_____ main.tf
|     |_____ common-variable.tfvars
|
|___ modules
|
|_____ a-module
|______ main.tf

所以在项目 1 common-variable.tfvars 中,基本上看起来像这样

variable "a" { 
description = "a variable"
default = "a" 
}
variable "b" { 
description = "a variable"
default = "b" 
}

模块内部/main.tf 看起来像这样

variable "name" {}
resource "aws_autoscaling_group" "asg-1" {
name = "${var.a}"
...
}

当我做地形初始化时,它说

resource 'aws_autoscaling_group.asg-1' config: unknown variable 
referenced: 'a'. define it with 'variable' blocks

知道我如何在模块 main .tf 中使用此公共变量吗?


更新

我设法通过重新声明每个模块中的变量来传递terraform init。但是,当我运行terraform plan时,会出现这种错误invalid value "common-variable.tfvars" for flag -var-file: multiple map declarations not supported for variables

错误的 tfvars 格式,应该只是键/值,例如:

a = "a"
b = "b"

其次,检查你如何引用模块,应该是这样的:

source = "../modules/a-module"

您需要在模块中声明模块所需的变量,然后在从项目中实例化模块时传入这些变量。

从哈希公司文档中窃取的示例

在您的项目中:

module "assets_bucket" {
source = "./publish_bucket"
name   = "assets"
}
module "media_bucket" {
source = "./publish_bucket"
name   = "media"
}

在您的模块中

# publish_bucket/bucket-and-cloudfront.tf
variable "name" {} # this is the input parameter of the module
resource "aws_s3_bucket" "the_bucket" {
# ...
}
resource "aws_iam_user" "deploy_user" {
# ...
}

最新更新