我是地形的新手,我试图实现一些可以消除基础设施冗余的东西。基本上,我有一个模块这样调用子模块:
module "jobs" {
source = "./jobs"
environment = var.environment
region = var.region
name = var.name
bucket_id = module.commons.bucket_id
bucket_name = module.commons.bucket_name
}
在jobs文件夹中,我有多个文件,它们做着相同的事情,但具有不同的值,比如:
resource "aws_s3_object" "test" {
bucket = var.bucket_id
key = "scripts/test_samples.sql"
source = "../src/main/resources/test_samples.sql"
}
resource "aws_s3_object" "test_folder" {
bucket = var.bucket_id
key = "raw/test_samples/"
}
resource "aws_glue_job" "test_samples" {
name = "test_samples"
role_arn = var.glue_role_arn
execution_class = "STANDARD"
execution_property {
max_concurrent_runs = 1
}
command {
name = "glueetl"
script_location = "s3://${var.bucket_name}/${aws_s3_object.simple_jdbc_code.key}"
}
connections = [var.databricks_jdbc_connection_name]
max_retries = 0
number_of_workers = 2
worker_type = "G.1X"
timeout = 10 # minutes
glue_version = "3.0"
etc etc.
}
resource "aws_glue_trigger" "test_schedule" {
name = "test_samples"
schedule = "cron(00 02 ? * SUN *)"
type = "SCHEDULED"
actions {
job_name = aws_glue_job.test_samples.name
}
}
基本上,我不想用不同的值运行完全相同的文件,而是想创建一种以前代码的模板,应用相同的参数但使用不同的值(一种在执行过程中读取一些不同参数集的循环(。
有没有一种简单的方法可以实现这一点?我听说过Terragrunt,它可以帮助分解一些地形代码,在这种情况下我可以使用它吗?
提前感谢!
根据评论中的讨论,您可以在模块级别创建一个变量:
variable "something" {
type = list(string)
description = "List of SQL files to be used."
}
然后,在模块本身中,您将使用for_each
[1]和toset
[2]内置函数的组合:
resource "aws_s3_object" "test" {
for_each = toset(var.something)
bucket = var.bucket_id
key = "scripts/${each.key}"
source = "../src/main/resources/${each.key}"
}
调用模块时,您将提供文件名列表:
module "jobs" {
source = "./jobs"
environment = var.environment
region = var.region
name = var.name
bucket_id = module.commons.bucket_id
bucket_name = module.commons.bucket_name
something = ["test_samples1.sql", "test_samples2.sql", "test_samples3.sql"]
}
[1]https://developer.hashicorp.com/terraform/language/meta-arguments/for_each
[2]https://developer.hashicorp.com/terraform/language/functions/toset