Contents
Terraform provides mechanisms to handle sensitive and temporary data without persisting it in state or plan files. The ephemeral block declares temporary resources that only exist during the current Terraform operation, making them ideal for managing secrets, temporary passwords, or connections to other systems.
Ephemeral Resources
The ephemeral block declares a temporary ephemeral resource that only exists during the current Terraform operation. Terraform does not store ephemeral resources in state or plan files.
ephemeral "<TYPE>" "<LABEL>" {
<PROVIDER_ARGUMENTS>
count = <NUMBER> # mutually exclusive with for_each
depends_on = [<RESOURCE.ADDRESS.EXPRESSION>]
for_each = <MAP_OR_SET_OF_STRINGS>
provider = <REFERENCE.TO.ALIAS>
lifecycle {
precondition {
condition = <EXPRESSION>
error_message = "<STRING>"
}
postcondition {
condition = <EXPRESSION>
error_message = "<STRING>"
}
}
}Example
Set and store an ephemeral password in AWS Secrets Manager
Use an ephemeral resource to generate a random password, store it in AWS Secrets Manager, and pass it to the password_wo write-only argument of aws_db_instance:
ephemeral "random_password" "db_password" {
length = 16
override_special = "!#$%&*()-_=+[]{}<>:?"
}
resource "aws_secretsmanager_secret" "db_password" {
name = "db_password"
}
resource "aws_secretsmanager_secret_version" "db_password" {
secret_id = aws_secretsmanager_secret.db_password.id
secret_string_wo = ephemeral.random_password.db_password.result
secret_string_wo_version = 1
}
ephemeral "aws_secretsmanager_secret_version" "db_password" {
secret_id = aws_secretsmanager_secret_version.db_password.secret_id
}
resource "aws_db_instance" "example" {
instance_class = "db.t3.micro"
allocated_storage = "5"
engine = "postgres"
username = "example"
skip_final_snapshot = true
password_wo = ephemeral.aws_secretsmanager_secret_version.db_password.secret_string
password_wo_version = aws_secretsmanager_secret_version.db_password.secret_string_wo_version
}The ephemeral resource aws_secretsmanager_secret_version references an argument that Terraform initially does not know. Terraform defers executing it until the apply stage, to ensure the resource is evaluated after it has the information it needs.
The flow:
- Generate a random password using ephemeral
random_password - Store it in AWS Secrets Manager
- Retrieve it using ephemeral
aws_secretsmanager_secret_version - Write the password to the write-only
password_woargument ofaws_db_instance