How to retrieve a secret in terraform from aws secret manager
Solution 1
Here is an example. By default, aws_secretsmanager_secret_version
retrieves information based on the AWSCURRENT
label (a.k.a. the latest version):
data "aws_secretsmanager_secret" "secrets" {
arn = "arn:aws:secretsmanager:us-east-1:123456789012:secret:my_secrety_name-123456"
}
data "aws_secretsmanager_secret_version" "current" {
secret_id = data.aws_secretsmanager_secret.secrets.id
}
And use data.aws_secretsmanager_secret_version.current.secret_string
to get the secret. If you want to retrieve a specific value inside that secret like DATABASE_URL
you can use the built-in function jsondecode
:
jsondecode(data.aws_secretsmanager_secret_version.current.secret_string)["DATABASE_URL"]
Solution 2
Please note that Terraform 0.14
added the ability to redact Sensitive values in console output.
Therefore, if you are using Terraform > 0.14, you will have to use nonsensitive
function to expose the actual secret value.
nonsensitive
function takes a sensitive value and returns a copy of that value with the sensitive marking removed, thereby exposing the actual value.
data "aws_secretsmanager_secret" "secrets" {
arn = "arn:aws:secretsmanager:us-east-1:123456789012:secret:my_secrety_name-123456"
}
data "aws_secretsmanager_secret_version" "current" {
secret_id = data.aws_secretsmanager_secret.secrets.id
}
output "sensitive_example_hash" {
value = jsondecode(nonsensitive(data.aws_secretsmanager_secret_version.current.secret_string))
}
user_mda
Updated on June 18, 2022Comments
-
user_mda almost 2 years
I have a secret stored in secrets manager to which I have access to the arn. I want to retrieve the value from this arn and use it in terraform how can I achieve this?
I found this from terraform website
data "aws_secretsmanager_secret" "by-arn" { arn = "arn:aws:secretsmanager:us-east-1:123456789012:secret:example-123456" }
How do I then retrieve the value? Meaning what is the "
get-value"
equivalent in terraform for an EC2 isntance? -
user_mda almost 4 yearsHi ! Thank you can you please give an example of the secrets arn instead of name? @pabloxio
-
pabloxio almost 4 yearsYou can use
arn
orname
to retrieve the secret. I usedname
but here is an example usingarn
:arn = "arn:aws:secretsmanager:us-east-1:123456789012:secret: my_secrety_name"
-
user_mda almost 4 yearsso the same works for arn? can you replace the example?
-
pabloxio almost 4 yearsSure... just remember that AWS adds a suffix to the AWS Secret Secret name, in this example
123456
-
Jordan Morris about 2 yearsNote, don't ever make real sensitive data an output like this, because outputs are saved as plaintext in terraform state files.