如何使用地形循环创建模板



我想通过基于列表变量(email_addresss(的loping,使用terraform template_file创建CFT。以下是我试图生成的变量和模板。

variables:-
emails_addresses = ["sample-1@gmail.com", "sample-2@gmail.com"]
sns_arn = "arn:aws:sns:us-east-1:xxxxxx:xxxx"
protocol = "email"

需要模板:

{
"AWSTemplateFormatVersion": "2010-09-09",
"Resources": {
"sample-1": {
"Type": "AWS::SNS::Subscription",
"Properties": {
"Endpoint": "sample-1@gmail.com",
"Protocol": "email",
"TopicArn": "arn:aws:sns:us-east-1:xxxx:xxxxx"
}
},
"sample-2": {
"Type": "AWS::SNS::Subscription",
"Properties": {
"Endpoint": "sample-2@gmil.com",
"Protocol": "email",
"TopicArn": "arn:aws:sns:us-east-1:xxx:xxxx"
}
}
}
}

CFT中的资源名称可以是一些随机字符串,但在多个计划/应用程序的情况下,每个邮件的名称应该相同。

由于json的原因,这个有点棘手。此外,我会使用templatefile而不是template_file,因为您可以将列表传递到其中

variable "emails_addresses" {
default = ["sample-1@gmail.com", "sample-2@gmail.com"]
}
variable "sns_arn" {
default = "arn:aws:sns:us-east-1:xxxxxx:xxxx"
}
variable "protocol" {
default = "email"
}
output "test" {
value = templatefile("./email-sns-stack.json.tpl", {
emails_addresses = var.emails_addresses,
sns_arn = var.sns_arn,
protocol = var.protocol  
})
}

其中email-sns-stack.json.tpl为:

{
"AWSTemplateFormatVersion": "2010-09-09",
"Resources": ${jsonencode(
{for email_address in emails_addresses: 
split("@",email_address)[0] => {
Type = "AWS::SNS::Subscription"
Properties = {
"Endpoint" = email_address
"Protocol" = protocol
"TopicArn" = sns_arn          
}
}})}
}

为了可读性,经过漂亮的json格式化后的输出:

{
"AWSTemplateFormatVersion": "2010-09-09",
"Resources": {
"sample-1": {
"Properties": {
"Endpoint": "sample-1@gmail.com",
"Protocol": "email",
"TopicArn": "arn:aws:sns:us-east-1:xxxxxx:xxxx"
},
"Type": "AWS::SNS::Subscription"
},
"sample-2": {
"Properties": {
"Endpoint": "sample-2@gmail.com",
"Protocol": "email",
"TopicArn": "arn:aws:sns:us-east-1:xxxxxx:xxxx"
},
"Type": "AWS::SNS::Subscription"
}
}
}

相关内容

  • 没有找到相关文章