How to easily migrate my state?

I've deployed my environments in env0, and now I want to change my state backend for many environments. How can I do this easily?

TL;DR; 

1. Reconfigure your state on all your templates and environments

2. set an Organization or Project level Environment Variable:

TF_CLI_ARGS_init=-migrate-state -force-copy

Background:

State migration can be quite troublesome en masse.

No fear, env0 can help you easily migrate your state. 

Whether you're using an existing state backend, or you've decided to consolidate your state into a single AWS account, or you simply want to move your state from env0 to a different location, here's a simplified way of migrating your state.

Existing State

First, let's assume you have already deployed your environment with env0, and the state is currently defined as such:

terraform {
required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "3.41.0"
    }
  }
   backend "s3" {
  bucket         = "env0-acme-tfstate-dev" # bucket will be in the deployer's account
  key            = "acme-demo-s3"
    region         = "us-west-2"
}
}

Unified State Example

The state is happily in a different AWS account, but lets say you now want to consolidate all the state into the same AWS account, and you have a configuration like this:


terraform {
required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "3.41.0"
    }
  }
  backend "s3" {
bucket         = "env0-acme-tfstate-dev" # bucket will be in the deployer's account
key            = "acme-demo-s3"
    region         = "us-west-2"
role_arn = "arn:aws:iam::326535729404:role/env0-acme-assume-role"
}
}

note: the role is chained from the deployer role, so the role_arn needs to trust the deployer role.

Migrate-State and Force-Copy 

Using an Environment Variable (temporarily), we can tell Terraform to migrate the state (forcibly) using the following configuration. If you want to migrate states for every environment, specify the variable at the Organization level, or Project level for a specific set of environments, or Template level if it's for a certain set of Templates.

AWS_CLI_ARGS_init=-migrate-state -force-copy

Once the state has been successfully migrated, you can remove this configuration.