在 Terraform 中的多个文件夹之间共享变量定义

问题描述 投票:0回答:1

我的项目结构如下:

.
├── modules/
│   ├── application/
│   │   ├── main.tf
│   │   └── variables.tf
│   ├── db/
│   │   ├── main.tf
│   │   └── variables.tf
│   └── cdn/
│       ├── main.tf
│       └── variables.tf
└── proj/
    ├── website_1/
    │   ├── main.tf
    │   ├── variables.tf
    │   ├── dev.tfvars
    │   └── prod.tfvars
    └── website_2/
        ├── main.tf
        ├── variables.tf
        ├── dev.tfvars
        └── prod.tfvars

----


### application/main.tf

resource "my_resource_type" "application" {
  description = var.app_description
  name        = var.app_name
  env         = var.env_name
}

# lots more resources....

-----

### application/variables.tf

variable "app_name" {
    type = string
    description = "Name of the application."
}

variable "app_description" {
    type = string
    description = "Description for the application."
}

variable "env_name" {
    type = string
    description = "Name of the environment."
}

# lots more variable definitions...

db/main.tf
cdn/main.tf
遵循类似的结构。

然后我的

proj/
文件夹中就有我想要应用的实际资源的文件。

### proj/website_1/main.tf

# shared resource configuration

module "application" {
  source = "../../modules/application"
  app_description = var.app_description
  app_name        = var.app_name
  env_name        = var.env_name
}

module "db" {
  source = "../../modules/db"
  # paramaters
}

module "cdn" {
  source = "../../modules/cdn"
  # paramaters
}

# unique website_1 config...

--------

### proj/website_2/main.tf

# shared resource configuration

module "application" {
  source = "../../modules/application"
  app_description = var.app_description
  app_name        = var.app_name
  env_name        = var.env_name
}


module "db" {
  source = "../../modules/db"
  # paramaters
}

module "cdn" {
  source = "../../modules/cdn"
  # paramaters
}

# unique website_2 config...

网站 1 和网站 2 以可重用的方式组合多个 AWS 资源,因此具有单独的模块。问题是必须进入

project/website_1/
project/website_2/
并重新输入我在模块中使用的相同变量定义。

我知道这是 Terraform 中的一个常见问题,但如果可以的话,我仍然希望避免重复我的变量定义。似乎符号链接一个常见的

variables.tf
文件是一种不好的做法,那么实现我想要在 Terraform 中实现的目标的“正确”/最佳实践方法(如果有的话)是什么(不使用 Terragrunt 等单独的工具) )?我也愿意更改我的文件夹和文件结构。

terraform dry infrastructure-as-code
1个回答
0
投票

如果它们都遵循相同的结构,我将在名为

variables_template.tf 
的目录中创建一个单一事实来源
templates
文件,并在主目录或子目录中创建一个 shell 脚本到
cp
rsync
variables_template.tf

然后,每当您需要更改所有变量时,只需更新模板并运行

update-variables.sh
脚本即可。

我还会

.gitignore
子目录中的变量,因为运行脚本一次就会填充它们。

© www.soinside.com 2019 - 2024. All rights reserved.