2017-08-18 52 views
1

我正在編寫terraform腳本來在AWS上創建ASG。我試圖用terraform module來創建一個更可重用的代碼。問題是當我想在模塊tf文件中使用來自common-variable.tfvars的變量時,它總是說它是未定義的並且需要聲明。通過這種方式,模塊的可重用性會降低。模塊中的Terraform常用變量用法

下面是一個例子

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

所以裏面的項目1共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}" 
    ... 
} 

當我做terraform init時,它說

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

任何想法如何我可以使用這個公共變量從模塊主要.tf?


更新

我管理通過每個模塊中重新聲明的變量傳遞terraform init。然而,當我運行terraform plan,這種錯誤的出現invalid value "common-variable.tfvars" for flag -var-file: multiple map declarations not supported for variables

回答

0

錯誤tfvars格式,應該是鍵/唯一的價值,如:

a = "a" 
b = "b" 

其次,檢查你怎麼參考模塊,應該是如下所示:

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

您好,感謝您的回答。但是,變量a實際上包含的不僅僅是上面編輯的值。一些變量也是一個地圖,我認爲我需要指定'type =「map」'? –

+0

對於地圖,您可以在tfvars文件中將其定義爲'map = {us-east-1 =「image-1234」,us-west-2 =「image-4567」}' – BMW

0

您需要在模塊中聲明模塊所需的變量,然後在從項目中實例化模塊時傳遞它們。

來自實例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" { 
    # ... 
}