Writing Terraform Configurations
When you start writing Terraform configurations, you will notice very quickly that the language provided by Terraform is very rich and allows for a lot of manipulation.
In the recipes in this chapter, you will learn how to use the Terraform language effectively to apply it to real-life business scenarios. We will discuss how to use providers by specifying their version, and adding aliases to use multiple instances of the same provider. Then we will discuss how to make the code more dynamic with variables and outputs, and we will consider the use of built-in functions and conditions.
Finally, we will learn how to add dependencies between resources, add custom checks with pre- and postconditions, and check the provisioned infrastructure.
All the code examples explained in this book are for illustrative purposes only. Their purpose is to provision cloud infrastructure resources, which may have a cost depending on the cloud used. I strongly suggest that you delete these resources either manually or via the terraform destroy command, which we’ll look at in detail in the recipe Destroying infrastructure resources in Chapter 6, Applying a Basic Terraform Workflow. Additionally, in a lot of the code on the GitHub repository of this chapter, you’ll see the use of random resources, which allow you to have unique resources.
In this chapter, we will cover the following recipes:
- Configuring Terraform and the provider version to use
- Adding alias to a provider to use multiple instances of the same provider
- Manipulating variables
- Keeping sensitive variables safe
- Using local variables for custom functions
- Using outputs to expose Terraform provisioned data
- Calling Terraform’s built-in functions
- Using YAML files in Terraform configuration
- Writing conditional expressions
- Generating passwords with Terraform
- Managing Terraform resource dependencies
- Adding custom pre- and postconditions
- Using checks for infrastructure validation
Let’s get started!