如何解决如何使用Terraform循环创建模板
我想通过基于列表变量(电子邮件地址)查找来使用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": "kalyanpawan07@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","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","Type": "AWS::SNS::Subscription"
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。