Basic Terraform commands

Stay organized with collections Save and categorize content based on your preferences.

Apply changes

To apply your Terraform configuration in a Google Cloud project, complete the following steps:

  1. Launch Cloud Shell.
  2. Set the Google Cloud project where you want to apply the Terraform configuration:
    export GOOGLE_CLOUD_PROJECT=PROJECT_ID
  3. Create a directory and a new file within that directory. The filename must have the .tf extension—for example main.tf. In this tutorial, the file is referred to as main.tf.
    mkdir DIRECTORY && cd DIRECTORY && touch main.tf
  4. Copy the sample code into the newly created main.tf.

    Optionally, copy the code from GitHub. This is recommended when the Terraform snippet is part of an end-to-end solution.

  5. Review and modify the sample parameters to apply to your environment.
  6. Save your changes.
  7. Initialize Terraform:
    terraform init
  8. Review the configuration and verify that the resources that Terraform is going to create or update match your expectations:
    terraform plan

    Make corrections to the configuration as necessary.

  9. Apply the Terraform configuration by running the following command and entering yes at the prompt:
    terraform apply

    Wait until Terraform displays the "Apply complete!" message.

  10. Open your Google Cloud project to view the results. In the Google Cloud console, navigate to your resources in the UI to make sure that Terraform has created or updated them.

Reformat

To reformat your Terraform configuration in the standard style, enter the following command:

terraform fmt

Validate

To check whether your configuration is valid, enter the following command:

terraform validate

Delete changes

Remove resources previously applied with your Terraform configuration by running the following command and entering yes at the prompt:

terraform destroy

Specify the project ID

If you run the export GOOGLE_CLOUD_PROJECT command as specified in the previous section, most resources can infer the project_id.

Some resources, such as project_iam_*, cannot infer the project ID. As a workaround, some samples use the data "google_project" data source. You can replace this data source with the project ID string or a variable.

For a sample that uses this workaround, see sql_instance_iam_condition.

What's next