首页 文章

Terraform模块中的常见变量用法

提问于
浏览
2

我正在编写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

2 回答

  • 0

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

    a = "a"
    b = "b"
    

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

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

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

    hashicorp documentation偷来的例子

    In your project:

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

    In your module

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

相关问题