fledgling
fledgling

Reputation: 1051

Set aws access key and secret key with secretsmanager Terraform

I have the below terraform template which creates a user, access key and stores in secret manager.

resource "aws_iam_user" "test" {
  name = "test"
}

resource "aws_iam_access_key" "test" {
  user = aws_iam_user.test.name
}

resource "aws_secretsmanager_secret" "test" {
  name = "credentials"
  description = "My credentials"
}

resource "aws_secretsmanager_secret_version" "test" {
  secret_id     = "${aws_secretsmanager_secret.test.id}"
  secret_string = "{\"AccessKey\": data.aws_iam_access_key.test.id,\"SecretAccessKey\": data.aws_iam_access_key.test.secret}"
}

The values in the secret_string is not getting set. Is this right usage? Please help me set the right values

secret_string = "{\"AccessKey\": data.aws_iam_access_key.test.id,\"SecretAccessKey\": data.aws_iam_access_key.test.secret}"

Upvotes: 3

Views: 5746

Answers (1)

Matthew Schuchard
Matthew Schuchard

Reputation: 28774

You can construct your secret_string argument value as a Map type, and then encode it into a JSON string using Terraform's native jsonencode function to ensure the value is passed correctly to the argument. Your resource would look like:

resource "aws_secretsmanager_secret_version" "test" {
  secret_id     = "${aws_secretsmanager_secret.test.id}"
  secret_string = jsonencode({"AccessKey" = aws_iam_access_key.test.id, "SecretAccessKey" = aws_iam_access_key.test.secret})
}

Note also that aws_iam_access_key.test.id and aws_iam_access_key.test.secret are exported attributes from resources and not data, so the data prefix needs to be removed from their namespace.

Upvotes: 6

Related Questions