繁体   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