首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用terraform循环创建模板

如何使用terraform循环创建模板
EN

Stack Overflow用户
提问于 2020-09-12 17:37:30
回答 1查看 1.6K关注 0票数 2

我想通过基于列表变量(Email_addresses)进行遍历来使用terraform template_file创建CFT。下面是我正在尝试生成的变量和模板。

代码语言:javascript
复制
variables:-

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

期望的模板:

代码语言:javascript
复制
{
    "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中的资源名称可以是一些随机字符串,但如果有多个计划/应用,则每个邮件的资源名称应该相同。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-09-12 18:26:34

由于json的缘故,这一点有点棘手。另外,我将使用templatefile而不是template_file,因为您可以将列表传递给它。

代码语言:javascript
复制
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是:

代码语言:javascript
复制
{
    "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格式化之后:

代码语言:javascript
复制
{
  "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"
    }
  }
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63858912

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档