Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
391 views
in Technique[技术] by (71.8m points)

amazon web services - Terraform: Replace function not working inside for_each while creating a resource

While creating one of the resource using for_each, I am also getting the info from other resource to populate data to one of the attribute in the resource creation. However I need to replace the each.value part to match properly and get the response from other resource, but wierdly, the replace function doesn't seem to do it's job. Any help is much appreciated. Thank you.

Code sample is below. While creating route 53 record, trying to get the info from cloud_front resource.

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
  }
}

Expected: I need the each.value.source say example from www.example.com to be replaced to www-example-com, but that is not happening.

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.
question from:https://stackoverflow.com/questions/65881763/terraform-replace-function-not-working-inside-for-each-while-creating-a-resourc

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Based on the chat discussion.

The issue is not with the replace function. The function works exactly as expected.

The issue is caused by the mismatch of keys in var.redirects and aws_cloudfront_distribution.main. Subsequently, the solution is to ensure that the two data sets have matching keys.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...