20 Best Practices to Improve Terraform Workflow | Part 2

In the previous part , we explored some strategies for building Terraform projects and some best practices for managing IaC with Terraform. Today, we'll continue to dive into the specifics of taking your Terraform code to the next level, hoping to provide you and your team with meaningful tips and guidance.
 

Tag resources

A strong and consistent tagging strategy will be a huge help when something goes wrong or when trying to figure out which part of your infrastructure is causing cloud expenses to skyrocket. You can also create some access control policies based on tags if needed. Like defining naming rules, try to be consistent and always label resources accordingly.
 

The Terraform parameter label should be declared as the last parameter (only or depends_onlifecycle parameters should be defined after the label if relevant).
 

When tagging, you can define something that applies to all resources managed by the provider default_tags. If the provider used does not support default tags, you will need to manually pass these tags to the module and apply them to the resource.
 

Introducing Policy as Code (PaC)

As business teams and infrastructure grow in size, trust in individual users often decreases. This is when policies should be put in place to ensure our systems continue to operate and remain secure. Developing a policy-as-code process allows us to define safe and acceptable rules at scale and automatically validate these rules.
 

Implement a confidentiality management policy

Secrets management may not be a top priority when starting to use Terraform, but ultimately it comes back to defining a policy for handling secrets.
 

As all tutorials say, never store secrets in clear text and commit them to a version control system . Secrets can be passed by TF_VARsetting environment variables with and sensitive = truemarking sensitive variables with .
 

Or a more mature solution is to set up a secrets store (such as Hashicorp Vault or AWS Secrets Manager) to handle access to confidential information. This way, secrets at rest are protected and encryption is enforced. There are also options for more advanced features such as key rotation and audit logging. It’s important to note, however, that this approach often incurs costs for businesses to use this hosting service.
 

Test Terraform code

Like all other code, IaC code should be tested accordingly. Running terraform planis the easiest way to quickly verify that your changes work as expected. Next, you can perform some static analysis on the Terraform code without applying it. Unit testing is also an option to verify that different parts of the system are functioning properly.
 

Another step is to Terraform linterintegrate into your CI/CD pipeline and try to catch any potential bugs related to cloud providers, deprecated syntax, enforcing best practices, etc.
 

Before proceeding officially with the above steps, you can set up some integration test replica sandbox environment by launching it, where you can verify that everything works as expected, collect the results, then destroy the sandbox and apply it to production.
 

Enable debugging/troubleshooting

When a problem arises, we must quickly and efficiently gather all the necessary information to solve the problem. You may find it helpful to set the Terraform log level for debugging purposes in these situations.

TF_LOG=DEBUG

Logs are also kept in files by setting the TF_LOG_PATH environment variable.
 

Build modules as much as possible

If there is no module in the community that works for your use case, you can try building your own. You will generally start building from something basic, and as the infrastructure matures you may need to go back to simple modules and add more functionality to them. When copying code in another environment, all you need to do is create an object from the module and populate it with the correct parameters for the new environment.
 

Use loops and conditionals

Your code should be able to create multiple instances of a resource, so it is recommended to use countor for instances that may change from one environment to another for_each. This will allow the flexibility to use the same code to suit many different use cases and provide commonality for parameters.
 

Use function

In addition to loops and conditionals, Terraform functions are crucial for achieving commonality in your code. They make your code more dynamic and ensure your configuration is DRY (Don't repeat yourself). Functions allow you to perform various operations, such as converting expressions to different data types, calculating lengths, and constructing complex variables.
 

Take advantage of dynamic modules

Without dynamic modules, the code cannot reach DRY state. When this feature is available, you have the flexibility to build your resources the way you like. For example, some cloud providers do not have dedicated resources for security group rules, and these rules are often embedded in the security group itself. With dynamic modules, you only need to change the input. But without dynamic modules, the configuration would need to be changed accordingly whenever a new rule is added.
 

Using Terraform WorkSpace

Please use Terraform Workspace so you will be able to reuse the same configuration in different environments.
 

Using Lifecycle Block

Sometimes there may be some complex conditions in the code. For example, let's say you have a script that must change something outside of Terraform on a resource tag (which is certainly not recommended). At this time, you can use the lifecycle module to ignore changes on the label to ensure that you will not roll back to the previous version.
 

If there is some resource that for some reason seems to be working fine but you have to recreate it without downtime, the lifecycle module can also help. You can use create_before_destroy=trueto achieve this purpose.
 

Validate using variables

Terraform does a great job of validating that variables receive the correct input, but what if you want to restrict something and don't have PaC implemented? Variable validation can be used at this time. This verification block exists inside the variable. You can refer to Terraform official instructions [1] to learn more.
 

Flexible use of auxiliary tools

Terraform is one of the most commonly used and loved IaC tools, and its community is also very large and active. Along with this community, there are many auxiliary tools created to help users better use Terraform. Of course choosing and adopting the right tool for our workflow is not a simple matter and often requires a phase of experimentation. Here we have summarized a list of some useful tools for your reference:

  • tflint - Terraform linter for checking for errors that your plan cannot catch.

  • tfenv – Terraform version manager

  • checkov – Terraform static analysis tool

  • terratest – Go library that helps you automate testing of Terraform

  • pre-commit-terraform – pre-commit git hooks for automation

  • terraform-docs - Quickly generate documentation from modules

  • atlantis – Terraform project collaboration workflow

  • terraform-cost-estimation – cost estimating service for your plans
     

Leverage IDE extensions

If you use Visual Studio Code or any other IDE when writing Terraform code, you can take advantage of its extensions to speed up the development process and ensure that your code is well-formatted. On vscode you can use the Terraform extension built by Anton Kulikov. Remember to install Terraform on your local machine to ensure it works properly.
 


 

Summarize

We explored many different best practices for Terraform and IaC, analyzed various options for working on and building Terraform projects, and learned how adopting accessibility tools can make our lives easier. While these are not tips that must be followed blindly, we hope this article serves as a guide that provides guidance, tips, and triggers for you to build your own optimal Terraform workflows and projects.
 

Original link :
https://spacelift.io/blog/terraform-best-practices
Reference link :
1. https://developer.hashicorp.com/terraform/language/values/variables

 

Guess you like

Origin blog.csdn.net/SEAL_Security/article/details/133267955