Writing Terraform configurations
Use locals to specify explicit dependencies between resources
locals to specify explicit dependencies between resourcesHelpful way to give a hint to Terraform that some resources should be deleted before even when there is no direct dependency in Terraform configurations.
https://raw.githubusercontent.com/antonbabenko/terraform-best-practices/master/snippets/locals.tf
Terraform 0.12 - Required vs Optional arguments
Required argument
index_documentmust be set, ifvar.websiteis not an empty map.Optional argument
error_documentcan be omitted.
variable "website" {
type = map(string)
default = {}
}
resource "aws_s3_bucket" "this" {
# omitted...
dynamic "website" {
for_each = length(keys(var.website)) == 0 ? [] : [var.website]
content {
index_document = website.value.index_document
error_document = lookup(website.value, "error_document", null)
}
}
}Optional Object Attributes (Terraform 1.3+)
Use optional attributes in objects to provide default values for non-required fields:
Managing Secrets in Terraform
Secrets are sensitive data that can be anything from passwords and encryption keys to API tokens and service certificates. They are typically used to set up authentication and authorization for cloud resources. Safeguarding these sensitive resources is crucial because exposure could lead to security breaches. It’s highly recommended to avoid storing secrets in Terraform config and state, as anyone with access to version control can access them. Instead, consider using external data sources to fetch secrets from external sources at runtime. For instance, if you’re using AWS Secrets Manager, you can use the aws_secretsmanager_secret_version data source to access the secret value. The following example uses write-only arguments, which are supported in Terraform 1.11+, and keep the value out of Terraform state.
Variable Validation and Input Handling
Basic Variable Validation
Use validation blocks to ensure variables meet specific criteria:
Object and List Validation
Validate complex data structures to ensure they contain expected values:
Last updated