Passing sensitive values to Terraform Modules

Build With IlaBuild With Ila
2 min read

Table of contents

Terraform provides huge flexibility to its users by enabling them to write code as small, specific, self-contained components of code known as Modules. It becomes easier to manage a complex project. With Modules, one can create Reusable Templates for common infrastructure components. This leads to a scalable approach to manage complexity.

This modularity is facilitated by the use of Variables in Terraform. Terraform’s input variables don’t change values during a Terraform run sucha as plan, apply or destroy. Instead, these variables allow users to safely customize their infrastructure by assigning different values to the variables before execution begins rather than editing configuration files manually.

More often than not, these variables are required for changing sensitive or secret information such as usernames, passwords, API tokens or personally identifiable information. It is rather necessary to not accidentally expose such information in CLI output, log output or source control. This can be achieved by using the .tfvars file to store such data.

The .tfvars files are used to set variable values. This data can be used at the execution time using the -var-file parameter.

Suppose you want to create an ec2 Instance and you write a module ec2_instance for that. You will have to provide some information to your resource your .tf file for doing so, as given below:

If we want to use variables in place of actual values, then those variables need to be defined in a separate variables.tf file and replace above code as below:

The variables will fetch values from a separate .tfvars file and use it at the time of execution of the code. This .tfvars file is not required to be checked into the version control system. In this way, the rest of the code can be shared among different teams and for different use cases/environments leading to collaboration, resuability, scalability of code while maintaining the security and compliance.

0
Subscribe to my newsletter

Read articles from Build With Ila directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Build With Ila
Build With Ila