【问题标题】:Terraform: Replace function not working inside for_each while creating a resourceTerraform:在创建资源时替换函数在 for_each 中不起作用
【发布时间】:2021-01-25 17:46:14
【问题描述】:

在使用 for_each 创建资源之一时,我还从其他资源获取信息以将数据填充到资源创建中的属性之一。但是我需要替换 each.value 部分以正确匹配并从其他资源获取响应,但奇怪的是,替换功能似乎并没有完成它的工作。任何帮助深表感谢。谢谢。

代码示例如下。在创建路由 53 记录时,尝试从 cloud_front 资源中获取信息。

resource "aws_route53_record" "redirect-records" {
  for_each = var.redirects
  zone_id  =  data.aws_route53_zone.main[each.value.domain_tf_alias].zone_id  
  name     = each.value.source
  type     = "A"
  alias {
    name                   = **aws_cloudfront_distribution.main[replace(each.value.source,".","-")].domain_name** 
    zone_id                = **aws_cloudfront_distribution.main[replace(each.value.source,".","-")].hosted_zone_id**
    evaluate_target_health = false
  }
}

预期:我需要将 www.example.com 中的 each.value.source 示例替换为 www-example-com,但这没有发生。

Error: Invalid index

  on rules.tf line 25, in resource "aws_route53_record" "redirect-records":
  25:     name                   = aws_cloudfront_distribution.main[replace(each.value.source,".","-")].domain_name # If acm domain exists then get from cloudFront else from S3
    |----------------
    | aws_cloudfront_distribution.main is object with 4 attributes
    | each.value.source is "www.aclgrc-s3.com"

The given key does not identify an element in this collection value.

【问题讨论】:

  • 什么是var.redirects
  • 还有为什么你认为它不起作用?有任何错误信息吗?
  • 是的,让我分享一条错误消息。
  • 我已包含错误消息。 var.redirects 是一个地图对象数组。来源是一个网址,如 www.example.com、support.helloworld.com 等。我需要将它们替换为 www-example-com 和 support-helloworld-com。
  • replace 工作正常。我会仔细检查您的 aws_cloudfront_distribution.main 中的实际键是什么。

标签: amazon-web-services terraform terraform-provider-aws


【解决方案1】:

基于聊天讨论。

问题不在于replace 函数。该功能完全按预期工作。

问题是由var.redirectsaws_cloudfront_distribution.main 中的键不匹配 引起的。随后,解决方案是确保两个数据集有匹配的key。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-17
    • 1970-01-01
    • 2019-12-16
    • 2020-12-09
    • 1970-01-01
    • 2021-04-15
    • 1970-01-01
    • 2023-02-16
    相关资源
    最近更新 更多