2023-06-13 15:32:02 +08:00
|
|
|
data "aws_caller_identity" "this" {}
|
|
|
|
|
|
|
|
resource "random_id" "rid" {
|
|
|
|
byte_length = 2
|
|
|
|
}
|
|
|
|
|
|
|
|
resource "aws_secretsmanager_secret" "secret1" {
|
2023-06-13 15:47:05 +08:00
|
|
|
name = "${var.secret_name}-${random_id.rid.dec}"
|
2023-06-13 15:32:02 +08:00
|
|
|
description = var.secret_description
|
2023-12-21 18:09:12 +08:00
|
|
|
kms_key_id = var.kms_key_id == null ? null : var.kms_key_id
|
2023-06-13 15:32:02 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
resource "aws_secretsmanager_secret_version" "this" {
|
|
|
|
secret_id = aws_secretsmanager_secret.secret1.id
|
2023-12-21 17:47:41 +08:00
|
|
|
secret_string = var.generate_secret ? random_password.this[0].result : var.secret_value
|
|
|
|
}
|
|
|
|
|
|
|
|
resource "random_password" "this" {
|
|
|
|
count = var.generate_secret ? 1 : 0
|
|
|
|
length = 22
|
|
|
|
special = true
|
|
|
|
}
|
|
|
|
|
|
|
|
resource "aws_secretsmanager_secret_policy" "policy" {
|
|
|
|
secret_arn = aws_secretsmanager_secret.secret1.arn
|
|
|
|
policy = var.secret_policy != null ? var.secret_policy : data.aws_iam_policy_document.policy-file.json
|
2023-06-13 15:32:02 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
data "aws_iam_policy_document" "policy-file" {
|
|
|
|
statement {
|
2023-12-21 17:47:41 +08:00
|
|
|
sid = "DenyCrossAccountAccess"
|
|
|
|
effect = "Deny"
|
2023-06-13 15:32:02 +08:00
|
|
|
|
|
|
|
principals {
|
2023-12-21 17:47:41 +08:00
|
|
|
identifiers = ["*"]
|
2023-06-13 15:32:02 +08:00
|
|
|
type = "AWS"
|
2023-12-21 17:47:41 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
condition {
|
|
|
|
test = "StringNotEquals"
|
|
|
|
values = [data.aws_caller_identity.this.account_id]
|
|
|
|
variable = "aws:PrincipalAccount"
|
2023-06-13 15:32:02 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
actions = ["secretsmanager:GetSecretValue"]
|
2023-12-21 17:47:41 +08:00
|
|
|
resources = [aws_secretsmanager_secret.secret1.arn]
|
2023-06-13 15:32:02 +08:00
|
|
|
}
|
2023-12-21 17:47:41 +08:00
|
|
|
}
|