There have been a lot of changes in cloud infrastructure in recent times. Companies now work in a complex environment which includes virtual machines, containers, databases, networking components, security components, and cloud services.
Infrastructure as Code (IaC) helps organizations manage infrastructure by using version-controlled configuration files rather than a manual process. One of the popular tools for Infrastructure as Code is Terraform, which enables engineers to write infrastructure across different clouds.
But the creation of Terraform configuration files is not sufficient. Organizations now need appropriate workflows in order to keep the reliability, security, and scalability intact. Organizations can simplify and automate their cloud infrastructure workflows with Cloud DevOps services, combining Infrastructure as Code practices with reliable deployment and operational processes.
1. Use Remote State With Locking
It is alright to use the local state while experimenting with Terraform code, but any time beyond that will require the use of a remote shared state. The use of a remote backend in state management is the first best practice recommended whenever one is working in a team.
Use a state which allows for state locking in order to prevent simultaneous modification by more than one person. Treat your state as immutable, and never manually change the state under any circumstances. Ensure that your states have backups in case of disaster.
Some of the remote states, for instance, AWS S3, allow for versioning of state.
2. Make Use of Existing Shared and Community Modules
Don’t write your own modules for each and every purpose and reinvent the wheel; find out whether any module is available to cater to your specific purpose. By doing so, you will be able to save time and utilize the benefits of the Terraform community. In addition, you can assist the community by contributing to improving them or pointing out issues.
3. Import Existing Infrastructure
Since your project may already have been running for a couple of years, it may very well be possible that some portions of its infrastructure have already been built manually. Do not worry because you will be able to import existing infrastructure in Terraform and thus avoid managing infrastructure from multiple endpoints.
4. Do Not Hard-Code the Values
You may be tempted to use hard-coded values in certain instances, but this must be avoided as far as possible. Take a moment to decide whether the value you are using can instead be a variable and thus allow easier modifications in the future.
Moreover, check whether you can use a data source to get the value of an attribute instead of explicitly defining the value.
For instance, instead of looking up our AWS account ID manually and storing it in terraform.tfvars as:
aws_account_id="99999999999"
You can look up the value from a data source.
data "aws_caller_identity" "current" {} locals { account_id = data.aws_caller_identity.current.account_id }
5. Format and Validate Always
In IaC, it is necessary to maintain consistency over time, and Terraform helps with this through some useful commands. Don’t forget to format and validate your code by using the terraform fmt and terraform validate. This should be ideally automated via a CI/CD pipeline or a pre-commit hook.
6. Follow Naming and Folder Conventions
There are various recommendations regarding naming of your Terraform code found on the web. In my opinion, the key thing is not the recommendations itself, but the approach which your team can agree upon and try to be consistent with. Here are the recommendations that will be easy to apply if you are looking for some:
- Use underscores (_) and lowercase for names.
- Don’t repeat the resource type in the resource name.
- For single-valued variables and attributes, use singular nouns. For lists or maps, use plural nouns since it shows that it represents several values.
- Remember to make all variable and output names descriptive and provide description.
7. Use Proper Tagging
Consistent and good tagging practice will save your back many times in case of emergencies and when trying to determine which of your infrastructure components was the reason for your bill to spike up. Also, it will be nice to be able to build some cool access controls based on tags. So just as in naming convention, please be consistent and always tag your resources.
Argument tags of Terraform should be always specified as the last one (only depends_on or lifecycle arguments should be placed after tags if required).
It might be useful to specify some default_tags that would be applied automatically to all resources handled by a provider. Take a look at the sample below to understand how to properly set default tags for AWS provider. In case if the provider that you use does not support default tags, you have to pass them to modules manually.
8. Implement Policies as Code
With our team and infrastructure growing bigger, the amount of trust we place in individual users becomes lower. You need to implement some policies that would help us keep our system functioning and safe.
A policy as code solution helps us define the rules of security and acceptability at scale and check whether they hold.
9. Implement a Secrets Management Approach
While users do not typically admit they have secrets in their Terraform configuration, we have all done it once. While secret management is not something one thinks about when they start using Terraform, at some point, you will need to implement an approach to managing secrets.
As you must have heard many times, it is important not to store secrets as plain text and commit them in your version control system. One approach you may use here is to pass secrets through environment variables (using TF_VAR) while labeling your sensitive variables with sensitive = true.
The next level would be implementing a secrets storage system, for example, HashiCorp Vault or AWS Secrets Manager, which would allow you to manage your secrets securely. Using such tools would allow you to ensure the security of secrets at rest and enable encryption without too much hassle. Moreover, you might want to leverage some advanced features, such as secret rotation or logging. Be ready to pay the price for this approach.
10. Test Your Terraform Code
Like all other pieces of code, infrastructure as code needs to be tested properly. There are various ways of doing it, and again, you need to choose what suits you better.
Using terraform plan is the simplest method to check whether your changes are going to work or not. The next thing to do is to conduct some kind of static analysis of your Terraform code without applying it.
Unit testing can also be considered for the verification of correct operation of separate elements of your system.
Then you can integrate Terraform linter into your CI/CD pipeline in order to catch any errors associated with cloud providers, deprecated syntax, best practices, etc. One step further, you can set up some kind of integration testing through running your own sandbox environment where you can apply your plan, verify that everything works as intended, collect the results, destroy the sandbox and proceed with your plan deployment on production.
Here is a list of the tools which can be used for testing your Terraform code. I will describe some of them in the “Helper Tools” section below.
11. Troubleshooting
In case of any problems, we need to be efficient in collecting all the required data for resolving them. It may be useful to enable Terraform debug logging in this case.
TF_LOG=DEBUG <terraform command>
What else you may find useful is to store the logs in a file using the TF_LOG_PATH variable.
12. Create Small Reusable Modules Where Feasible
If there is no community module for your use case, it is recommended that you create your own module. Of course, even though you might be starting off with something trivial, as your infrastructure grows, there will come a time when you will need to go back to your trivial module and add some more features to it.
Of course, this is also going to be helpful when you have to recreate your code in a different environment, since all that you would need to do in such a case would be to create an object out of your module and fill it with the right parameters for the new environment.
13. Use Loops and Conditionals
It is ideal for your code to create several instances of a resource wherever possible, and hence a recommendation would be that you use count or for_each for those resources which may differ between two environments.
Combined with conditionals, this is going to give you the flexibility of accommodating many use cases with the same code.
14. Apply Built-In Functions
Apart from loops and conditionals, functions are very important tools in making your code generic through Terraform. Functions make your code dynamic, and your configuration DRY.
Functions can help you do many things such as convert expressions to other data types, calculate lengths, and even create complicated variables.
15. Leverage Dynamic Blocks
Your code cannot be DRY without dynamic blocks. When this feature was introduced, it greatly contributed to making code flexible when building resources in any way you want. For instance, some cloud providers lack dedicated resources to add security group rules, which means that security rules are contained within the security groups.
Prior to dynamic blocks, you would have to modify your code each time a new rule was created; now you just change the inputs.
16. Use Terraform Workspaces
Terraform workspaces are tools that help manage multiple environments or infrastructure states using the same Terraform configuration.
Rather than creating individual configuration files for each environment, for instance, development, staging, and production, workspaces make it possible to use the same codebase but have each environment state separated from others.
It is possible, for example, to have the following command lines when creating individual workspaces for each environment:
terraform workspace new development terraform workspace new staging terraform workspace new production
And then switching among environments whenever needed with the following command line:
terraform workspace select production
While Terraform workspaces can be helpful when working on smaller and less complex infrastructure deployments, bigger and complex infrastructure projects may need some further assessment of whether it would make sense to keep multiple configurations or state files separate.
17. Use the Lifecycle Block
Some time you may need some sophisticated conditions in your code. For example, maybe, you need to modify something outside Terraform on your resource tags (please note, this is not a recommendation, just an example). In this situation, you can use the lifecycle block of Terraform, which allows ignoring tag modifications and prevents you from reverting to the previous version.
Also, this is useful when you have some tricky resources that somehow work well but require recreation. This can be done with the create_before_destroy=true option.
18. Make Use of Helper Tools to Simplify Your Life
One of the most popular IaC tools out there is, without a doubt, Terraform. With this in mind, there is a vast community of people using Terraform. Along with that community, there is a great number of helper tools being developed all the time to assist us on our Terraform journey. Choosing and adopting the proper tools for our workflows may be sometimes challenging and requires some trial-and-error process.
Here is the list of tools that I consider helpful according to my personal experience but it is definitely not exhaustive:
- tflint – Terraform linter for those mistakes that plan cannot detect.
- tfenv – Terraform version management tool
- Checkov – Terraform static code analyzer.
- Terratest – Go library to run automated tests for Terraform.
- pre-commit-terraform – Pre-commit git hooks for automation.
- terraform-docs – Quick docs generation for modules.
- Atlantis – Collaboration workflow for Terraform projects.
- terraform-cost-estimation – Cost estimation service for your plans.
19. Use the IDE Extensions
When you are writing Terraform code within Visual Studio Code, or any other IDEs, there are many ways in which you can use their extensions to speed up your development process and also make sure that your code is written correctly.
In VSCode, you can install the Terraform extension made by Anton Kulikov. However, it is important to note that Terraform needs to be installed locally on your computer to ensure it is functioning correctly.
20. Use AI Safely to Speed Up Terraform Work
AI will help you in speeding up your Terraform work (creating modules, refactoring, creating docs, and explaining the plan outputs). However, AI needs to be used as your assistant and not the authority. You must never enter any secrets, credentials, customer data, and full state files in the AI prompt.
Conclusion
Terraform offers an excellent framework that helps in managing cloud infrastructure via Infrastructure as Code. However, when the infrastructure environment grows larger, keeping the configuration clean and ensuring secure workflows and consistent deployments becomes crucial.
Applying Terraform best practices that involve the use of correct state management, reusable modules, version control, security of sensitive data, change validation, and automation of workflows is a way of minimizing operational risk and increasing infrastructure consistency.
Each organization has different needs, and there is no one-size-fits-all approach. The choice of a proper Terraform workflow will depend on many aspects, including infrastructure size, organization’s structure, security requirements, and deployment processes. The proper start and continuous improvement of Terraform practices will help to create more manageable, scalable, and efficient infrastructure. Organizations can simplify and automate their cloud infrastructure workflows with Cloud DevOps services, combining Infrastructure as Code practices with reliable deployment and operational processes.