|
| 1 | +data "aws_caller_identity" "current" {} |
| 2 | + |
| 3 | +locals { |
| 4 | + # When source_accounts is set, automatically include the current (audit) account |
| 5 | + # to ensure the local AWS Config can also publish to the SNS topic |
| 6 | + effective_source_accounts = length(var.source_accounts) > 0 ? distinct(concat( |
| 7 | + var.source_accounts, |
| 8 | + [data.aws_caller_identity.current.account_id] |
| 9 | + )) : [] |
| 10 | +} |
| 11 | + |
1 | 12 | resource "aws_sns_topic" "this" { |
2 | 13 | name_prefix = "${var.name}-" |
3 | 14 | } |
@@ -40,6 +51,65 @@ data "aws_iam_policy_document" "sns_topic_policy" { |
40 | 51 | aws_sns_topic.this.arn, |
41 | 52 | ] |
42 | 53 | } |
| 54 | + |
| 55 | + # Optional: if org_id is set, add an AllowAWSConfigFromOrg statement that |
| 56 | + # allows config.amazonaws.com to publish, restricted by aws:PrincipalOrgID. |
| 57 | + dynamic "statement" { |
| 58 | + for_each = var.org_id == null ? [] : [1] |
| 59 | + content { |
| 60 | + sid = "AllowAWSConfigFromOrg" |
| 61 | + effect = "Allow" |
| 62 | + |
| 63 | + principals { |
| 64 | + type = "Service" |
| 65 | + identifiers = ["config.amazonaws.com"] |
| 66 | + } |
| 67 | + |
| 68 | + actions = [ |
| 69 | + "SNS:Publish", |
| 70 | + ] |
| 71 | + |
| 72 | + resources = [ |
| 73 | + aws_sns_topic.this.arn |
| 74 | + ] |
| 75 | + |
| 76 | + condition { |
| 77 | + test = "StringEquals" |
| 78 | + variable = "aws:PrincipalOrgID" |
| 79 | + values = [var.org_id] |
| 80 | + } |
| 81 | + } |
| 82 | + } |
| 83 | + # Optional: if source_accounts is non-empty, add an AllowAWSConfigFromSourceAccounts |
| 84 | + # statement that restricts publishes by AWS:SourceAccount. |
| 85 | + # This automatically includes the current (audit) account ID. |
| 86 | + dynamic "statement" { |
| 87 | + for_each = length(local.effective_source_accounts) == 0 ? [] : [1] |
| 88 | + content { |
| 89 | + sid = "AllowAWSConfigFromSourceAccounts" |
| 90 | + effect = "Allow" |
| 91 | + |
| 92 | + principals { |
| 93 | + type = "Service" |
| 94 | + identifiers = ["config.amazonaws.com"] |
| 95 | + } |
| 96 | + |
| 97 | + actions = [ |
| 98 | + "SNS:Publish", |
| 99 | + ] |
| 100 | + |
| 101 | + resources = [ |
| 102 | + aws_sns_topic.this.arn, |
| 103 | + ] |
| 104 | + |
| 105 | + condition { |
| 106 | + test = "StringEquals" |
| 107 | + variable = "AWS:SourceAccount" |
| 108 | + values = local.effective_source_accounts |
| 109 | + } |
| 110 | + } |
| 111 | + } |
| 112 | + |
43 | 113 | } |
44 | 114 |
|
45 | 115 | resource "aws_sns_topic_subscription" "this" { |
|
0 commit comments