Best practices for security

This document provides guidelines and recommendations for securely using Terraform for Google Cloud. Terraform requires sensitive access to your cloud infrastructure to operate. Following security best practices can help to minimize the associated risks and improve your overall cloud security.

This guide is not an introduction to Terraform. For an introduction to using Terraform with Google Cloud, see Get started with Terraform.

Use remote state

For Google Cloud customers, we recommend using the Cloud Storage state backend. This approach locks the state to allow for collaboration as a team. It also separates the state and all the potentially sensitive information from version control.

Make sure that only the build system and highly privileged administrators can access the bucket that is used for remote state.

To prevent accidentally committing development state to source control, use gitignore for Terraform state files.

Encrypt state

Though Google Cloud buckets are encrypted at rest, you can use customer-supplied encryption keys to provide an added layer of protection. Do this by using the GOOGLE_ENCRYPTION_KEY environment variable. Even though no secrets should be in the state file, always encrypt the state as an additional measure of defense.

Don't store secrets in state

There are many resources and data providers in Terraform that store secret values in plaintext in the state file. Where possible, avoid storing secrets in state. Following are some examples of providers that store secrets in plaintext:

Mark sensitive outputs

Instead of attempting to manually encrypt sensitive values, rely on Terraform's built-in support for sensitive state management. When exporting sensitive values to output, make sure that the values are marked as sensitive.

Ensure separation of duties

If you can't run Terraform from an automated system where no users have access, adhere to a separation of duties by separating permissions and directories. For example, a network project would correspond with a network Terraform service account or user whose access is limited to this project.

Run pre-apply checks

When running Terraform in an automated pipeline, use a tool like gcloud terraform vet to check plan output against policies before it is applied. Doing so can detect security regressions before they happen.

Run continuous audits

After the terraform apply command has executed, run automated security checks. These checks can help to ensure that infrastructure doesn't drift into an insecure state. The following tools are valid choices for this type of check:

What's next