簡體   English   中英

Terraform 命令未使用隨 --var-file 提供的 tfvars 文件中的值

[英]Terraform command is not using the values from the tfvars file provide with --var-file

我在 Terraform 中很新,試圖在我的應用程序的每個環境(dev、stg、prod)下為每個 AWS 區域創建單獨的后端。 因此,我使用單獨的.config文件來配置單獨的后端,並使用單獨.tfvars文件在相關環境/區域上創建資源。

我正在詳細說明以下所有內容:

文件夾結構:

.
├── config
│   ├── stg-useast1.config
│   ├── stg-uswest2.config
│   ├── prod-useast1.config
│   └── prod-uswest2.config
├── vars
│   ├── stg-useast1.tfvars
│   ├── stg-uswest2.tfvars
│   ├── prod-useast1.tfvars
│   └── prod-useast1.tfvars
└── modules
    ├── backend.tf
    ├── main.tf
    ├── variables.tf
    └── module-ecs
        ├── main.tf
        └── variables.tf

此問題所需的文件內容如下所示(僅一個區域):

./config/stg-useast1.config

profile        = "myapp-stg"
region         = "us-east-1"
bucket         = "myapp-tfstate-stg-useast1"
key            = "myapp-stg-useast1.tfstate"
dynamodb_table = "myapp-tfstate-stg-useast1-lock"

./vars/stg-useast1.tfvars

environment = "stg"
app_name    = "myapp-ecs"
aws_region  = "us-east-1"
aws_profile = "myapp-stg"

./modules/backend.tf

terraform {
  backend "s3" {
  }
}

./modules/main.tf

provider "aws" {
  region                   = var.aws_region
  shared_credentials_files = ["~/.aws/credentials"]
  profile                  = var.aws_profile
}

module "aws-ecr" {
  source = "./ecs"
}

./modules/variables.tf

variable "app_name" {}
variable "environment" {}
variable "aws_region" {}
variable "aws_profile" {}

./modules/module-ecs/main.tf

resource "aws_ecr_repository" "aws-ecr" {
  name = "${var.app_name}-${var.environment}-ecr"
  tags = {
    Name        = "${var.app_name}-ecr"
    Environment = var.environment
  }
}

./modules/module-ecs/variables.tf

variable "app_name" {
    default = "myapp-ecs"
}
variable "environment" {
    default = "stg"
}
variable "aws_region" {
    default = "us-east-1"
}
variable "aws_profile" {
    default = "myapp-stg"
}

terraform init進展順利。

$ terraform init --backend-config=../config/stg-useast1.config
Initializing modules...

Initializing the backend...

Initializing provider plugins...
- Reusing previous version of hashicorp/aws from the dependency lock file
- Using previously-installed hashicorp/aws v4.31.0

Terraform has been successfully initialized!

我運行terraform plan如下:

terraform plan --var-file=../vars/stg-useast1.tfvars

但它沒有使用此.tfvars文件中的值。 我必須在./modules/module-ecs/variables.tf中為每個變量提供它們作為default = <value>

如何使用帶有terraform plan命令的.tfvars文件?

歡迎任何重組建議。

您創建的本地模塊不繼承變量。 您需要將它們傳遞進來。例如:

module "aws-ecr" {
  source = "./ecs" # in your example it looks like the folder is ecs-module?
  app_name = var.app_name
  environment = var.environment
  aws_region = var.region
  aws_profile = var.profile
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM