Remote state management with Terraform Cloud

This is a newbie who just discovered Terraform & other HCP tools and feeling the excitement I’ve felt for a long time.

But kinda need a little hand-holding with below.

Say you have this (following the beginner’s tutorials):

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 2.70"
    }
  }
}

provider "aws" {
  profile = "default"
  region  = "us-west-2"
}

resource "aws_instance" "example" {
  ami           = "ami-08d70e59c07c61a3a"
  instance_type = "t2.micro"
}

and want to use Terraform Cloud for remote state management.

Where do you add this block:

terraform {
  backend "remote" {
    organization = "<ORG_NAME>"

    workspaces {
      name = "Example-Workspace"
    }
  }
}

To the same .tf file as below:

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 2.70"
    }
  }
}

terraform {
  backend "remote" {
    organization = "<ORG_NAME>"

    workspaces {
      name = "Example-Workspace"
    }
  }
}

provider "aws" {
  profile = "default"
  region  = "us-west-2"
}

resource "aws_instance" "example" {
  ami           = "ami-08d70e59c07c61a3a"
  instance_type = "t2.micro"
}

or

terraform {
  backend "remote" {
    organization = "<ORG_NAME>"

    workspaces {
      name = "Example-Workspace"
    }
  }
}

provider "aws" {
  profile = "default"
  region  = "us-west-2"
}

resource "aws_instance" "example" {
  ami           = "ami-08d70e59c07c61a3a"
  instance_type = "t2.micro"
}

Thanks for your guidance.

There is obviously and clearly a difference between “backend” and “provider” blocks (please correct me if my understanding is wrong).

So I’ll assume that this:

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 2.70"
    }
  }
}

terraform {
  backend "remote" {
    organization = "<ORG_NAME>"

    workspaces {
      name = "Example-Workspace"
    }
  }
}

provider "aws" {
  profile = "default"
  region  = "us-west-2"
}

resource "aws_instance" "example" {
  ami           = "ami-08d70e59c07c61a3a"
  instance_type = "t2.micro"
}

is the right approach.

Still would appreciate it if someone can ascertain this for me.

Thanks.

Hi @metacogni!

Both required_providers and backend are nested block types of terraform blocks, so you can put them both together in a single terraform block if you like, or you can have two separate terraform blocks like in your third code block.

Both are equivalent as far as Terraform is concerned, though we’d normally only use multiple terraform blocks if they are in different files. For example, a common convention is to put the terraform block with backend into a backend.tf file and the terraform block with required_providers in versions.tf, although Terraform itself assigns no meaning to those filenames.

1 Like

Thank you so much for your guidance, Mart.