Create aws_ses_receipt_rule in predefined order with for_each loop

Viewed 118

I am trying to define SES rule sets with an order defined by a collection of rules in a variable.

I have tried the solution in https://github.com/hashicorp/terraform-provider-aws/issues/24067 to use the after property of the resource, and It does create the first rule, and fails when creating the second, and all subsequent rules, because the first rule does not exist yet (the one with after=null). I guess it needs some time to finalize. depends_on does not work with dynamic dependencies, as far as i know, so this will not make it either.

If I re-run the apply, then the second rule is created, but all the other rules fail.

my recipients_by_position map is indexed by 0-padded position (i.e. "01", "02", etc):

This is my code

locals {

  recipients = {
    "mail1-recipient1" = {
      short_name    = "mail1"
      domain        = "mail1.domain.com"
      recipient     = "recipient1"
      position      = 1
      target_bucket = "bucket1"
    }
    "mail1-recipient2" = {
      short_name    = "mail1"
      domain        = "mail1.domain.com"
      recipient     = "recipient2"
      position      = 2
      target_bucket = "bucket1"
    }
    "mail2-recipient1" = {
      short_name    = "mail2"
      domain        = "mail2.domain.com"
      recipient     = "recipient1"
      position      = 3
      target_bucket = "bucket2"
    }
  }
  spec_by_domain = {
    "mail1.domain.com" = {
      irrelevant ={}
    }
    "mail2.domain.com" = {
      irrelevant ={}
    }
  }

  recipients_by_position = {for r in local.recipients: "${format("%02s",r.position)}" => r}
}

resource "aws_ses_domain_identity" "domains" {
  for_each = local.spec_by_domain
  domain = each.key
}

resource "aws_ses_receipt_rule_set" "main" {
  rule_set_name = "new-rules"
}


# store it in S3
resource "aws_ses_receipt_rule" "store" {
  for_each = local.recipients_by_position
  after   = each.value.position == 1 ? null : "${format("%02s",each.value.position - 1)}"

#  name          = "${each.value.short_name}-store_on_s3-${each.value.recipient}"
  name          = each.key
  rule_set_name = aws_ses_receipt_rule_set.main.rule_set_name
  recipients    =  ["${each.value.recipient}@${each.value.domain}"]
  enabled       = true
  scan_enabled  = true

  s3_action {
    bucket_name = aws_s3_bucket.mailboxes[each.value.domain].bucket
    object_key_prefix = each.value.recipient
    position    = 1
  }
}

apply fails with a bunch of

Error: Error creating SES rule: RuleDoesNotExist: Rule does not exist: xx

with xx from 01 to whatever number of rules were defined

0 Answers
Related