Write your first Terraform configuration

Learn the init, plan, apply and destroy cycle on your own computer, with no cloud account needed.

· Updated

Terraform creates and changes infrastructure from files you write, so servers, networks and DNS records are described in code and reviewed like code. This guide uses the local provider, which only writes a file on your computer, so you can learn the cycle without a cloud account.

Before you start

Steps

  1. Save this as main.tf in the empty folder:

    main.tf
    terraform {
      required_providers {
        local = {
          source  = "hashicorp/local"
          version = "~> 2.5"
        }
      }
    }
    
    resource "local_file" "hello" {
      filename = "${path.module}/hello.txt"
      content  = "Hello from Terraform\n"
    }
  2. Download the provider:

    bash
    terraform init
  3. Preview the change. Terraform shows 1 to add and changes nothing yet:

    bash
    terraform plan
  4. Make the change. Type yes when asked:

    bash
    terraform apply
  5. Check the result: hello.txt now exists, with the text from main.tf.

  6. Change the content line, then run terraform plan again. Terraform shows exactly what will change before you apply it.

  7. Remove everything Terraform created:

    bash
    terraform destroy

What happens next

Terraform recorded what it made in terraform.tfstate. That file is how it knows what exists, so on a real project it's kept in shared remote storage, never edited by hand and never committed to Git.

Warning

State files can contain passwords and keys. Add *.tfstate and *.tfstate.* to your .gitignore.

Next steps