【问题标题】:Terraform common variable usage in modulesTerraform 模块中常用变量的使用
【发布时间】:2018-01-26 14:22:46
【问题描述】:

我正在编写 terraform 脚本以在 AWS 上创建 ASG。我尝试使用 terraform module 创建它,以获得更可重用的代码。问题是当我想在模块 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" 
}

a-module/main.tf里面是这样的

variable "name" {}

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

当我做 terraform init 时,它说

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

【问题讨论】:

    标签: terraform


    【解决方案1】:

    错误的tfvars格式,应该是key/value而已,如:

    a = "a"
    b = "b"
    

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

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

    【讨论】:

    • 嗨,感谢您的回答。但variable a 实际上包含的不仅仅是值,如上面编辑的那样。一些变量也是一个映射,我想我需要指定type = "map"?
    • 对于map,可以在tfvars文件中定义为map = { us-east-1 = "image-1234", us-west-2 = "image-4567"}
    【解决方案2】:

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

    从hashicorp documentation盗取的例子

    在您的项目中:

    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" {
      # ...
    }
    

    【讨论】:

      猜你喜欢
      • 2019-10-06
      • 2021-04-01
      • 2021-08-08
      • 2017-04-23
      • 2019-01-21
      • 1970-01-01
      • 1970-01-01
      • 2021-06-26
      • 1970-01-01
      相关资源
      最近更新 更多