Reusing Common Tags for EC2 Instances
Imagine you have an AWS EC2 instance named “web” with a specific AMI and instance type created for Project Cerberus in the finance department. The instance is tagged as follows:locals block and reference them directly in each resource.
Improved Configuration with Local Values
The revised Terraform configuration using local values is as follows:local.common_tags, both EC2 instances now share the same tag definitions, reducing redundancy and simplifying maintenance.
Using local values not only enhances code readability but also minimizes typographical errors when managing multiple similar configurations.
Creating an S3 Bucket with a Unique Name
S3 buckets require globally unique names. To achieve this, you can generate a random string using Terraform’srandom_string resource and concatenate it with a project variable. This ensures that your bucket name follows a predictable naming convention, such as “projectname-randomstring-bucket”.
Configuring the S3 Bucket
Begin by defining the project variable, the random string resource, and a local value that creates the bucket prefix. Then, use this local value in the S3 bucket resource:- The variable
projectdefaults to “cerberus”. - The
random_stringresource generates a six-character random string without special characters or uppercase letters. - The local value
bucket_prefixinterpolates the project name, random string, and a static suffix to create a unique name. - The AWS S3 bucket resource consumes
local.bucket_prefixas its bucket name, ensuring compliance with S3’s uniqueness requirements.
terraform apply -auto-approve, the process output confirms that the random string was generated and the S3 bucket was created with the expected unique name:
Using clear variable names and concise descriptions improves both code maintainability and search engine discoverability. Consider periodically reviewing your documentation to ensure it remains up-to-date with best practices.
Summary
In this guide, you learned how to simplify Terraform configurations by using local values to:- Eliminate repeated code for resource attribute definitions.
- Improve consistency in tagging AWS EC2 instances.
- Ensure unique naming for S3 buckets by combining project variables with random strings.