learn.hashicorp.com
Open in
urlscan Pro
76.76.21.93
Public Scan
URL:
https://learn.hashicorp.com/tutorials/terraform/cloud-migrate?in=terraform/state
Submission: On July 19 via manual from AE — Scanned from DE
Submission: On July 19 via manual from AE — Scanned from DE
Form analysis
2 forms found in the DOM<form novalidate="" action="" role="search"><input type="search" id="search-box" class="search-box_searchInput__7Xc27 g-type-body-strong" placeholder="Search" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"
maxlength="512" required="" value="" aria-autocomplete="list" aria-controls="search-results" aria-activedescendant="" data-heap-track="SearchBox"><button type="submit" title="Submit your search query." class="search-box_submitButton__kImHH"><svg
width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
<path clip-rule="evenodd" d="M8.75 15a6.25 6.25 0 100-12.5 6.25 6.25 0 000 12.5z" stroke="var(--gray-3)" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path>
<path d="M17.5 17.5l-4.333-4.333" stroke="var(--gray-3)" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path>
</svg></button><button type="reset" title="Clear the search query." class="search-box_resetButton__QejMx"><svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M1.915 1.077h13.684v13.684H1.915z"></path>
<path d="M1.915 1.077l13.683 13.684M1.915 14.76L15.598 1.078" stroke="var(--gray-3)" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path>
</svg></button><svg class="search-box_iconSlash__eX_v_" width="24" height="24" fill="none" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" role="img">
<title>Type '/' to Search</title>
<rect x=".5" y=".5" width="23" height="23" rx=".5" stroke="var(--gray-3)"></rect>
<path d="M9 18l6-12" stroke="var(--gray-3)" stroke-width="1.5"></path>
</svg></form>
<form id="feedback-panel">
<div><label for="helpful">Was this tutorial helpful?</label>
<div class="style_buttonWrapper__WJv2y"><button class="style_root__ABjny style_size-small__CaWnr theme_variant-primary__L02E4 theme_background-light__d2uoe style_choiceButton___HjR0 " data-ga-button="yes" aria-label="Yes" type="button"
data-heap-track="feedback-form-button-helpful-yes">
<div class="style_icon__ihTKR style_size-small__CaWnr style_at-left__KBS3P"><svg viewBox="0 0 24 24" width="24" height="24" stroke="currentColor" stroke-width="1.5" fill="none" stroke-linecap="round" stroke-linejoin="round">
<path d="M14 9V5a3 3 0 00-3-3l-4 9v11h11.28a2 2 0 002-1.7l1.38-9a2 2 0 00-2-2.3zM7 22H4a2 2 0 01-2-2v-7a2 2 0 012-2h3"></path>
</svg></div><span class="style_text__pNYCe g-type-buttons-and-standalone-links">Yes</span>
</button><button class="style_root__ABjny style_size-small__CaWnr theme_variant-primary__L02E4 theme_background-light__d2uoe style_choiceButton___HjR0 style_negative__hR3vE" data-ga-button="no" aria-label="No" type="button"
data-heap-track="feedback-form-button-helpful-no">
<div class="style_icon__ihTKR style_size-small__CaWnr style_at-left__KBS3P"><svg viewBox="0 0 24 24" width="24" height="24" stroke="currentColor" stroke-width="1.5" fill="none" stroke-linecap="round" stroke-linejoin="round">
<path d="M14 9V5a3 3 0 00-3-3l-4 9v11h11.28a2 2 0 002-1.7l1.38-9a2 2 0 00-2-2.3zM7 22H4a2 2 0 01-2-2v-7a2 2 0 012-2h3"></path>
</svg></div><span class="style_text__pNYCe g-type-buttons-and-standalone-links">No</span>
</button></div>
</div>
</form>
Text Content
Skip to main content HashiCorp Learn Browse products INFRASTRUCTURE * TerraformLearn terraformDocs * PackerLearn packerDocs SECURITY * VaultLearn vaultDocs * BoundaryLearn boundaryDocs APPLICATIONS * NomadLearn nomadDocs * WaypointLearn waypointDocs * VagrantLearn vagrantDocs NETWORKING * ConsulLearn consulDocs CLOUD * HashiCorp Cloud Platform (HCP)Docs Advanced Search Search Type '/' to Search Sign in Loading account... * Bookmarks * Account Settings * Sign Out Show sidebar Jump to section * Overview * Prerequisites * Create state * Set up Terraform Cloud * Authenticate with Terraform Cloud * Migrate the state file * Configure the Terraform Cloud workspace * Initiate a run in the new workspace * Next steps Docs Forum Bookmark Back to terraform STATE * Import Terraform Configuration * Migrate State to Terraform Cloud * Manage Resources in Terraform State * Target resources * Troubleshoot Terraform * Manage Resource Drift * Manage Resource Lifecycle * Version Remote State with the Terraform Cloud API * Use Refresh-Only Mode to Sync Terraform State * Develop Configuration with the Console * Use Configuration to Move Resources Terraform Cloud MIGRATE STATE TO TERRAFORM CLOUD Reference this often? Create an account to bookmark tutorials. * 8 min * Products Used: This tutorial also appears in: Terraform Cloud, CLI and Associate Tutorials. As a current user of the Terraform CLI, you are responsible for maintaining a state file as a source of truth for your cloud infrastructure. You can keep your state file secure and share it with collaborators, by migrating it to Terraform Cloud without interrupting or recreating your existing infrastructure. Warning: When uploading a state file to Terraform Cloud using the steps in this tutorial, always use the same version of the Terraform CLI you used to create the resources. Using a newer version of Terraform may update the state file and cause state file corruption. »PREREQUISITES This tutorial assumes that you have the following: * The Terraform CLI installed locally * A Terraform Cloud account Note: Because the cloud block is not supported by older versions of Terraform, you must use 1.1.0 or higher in order to follow this tutorial. Previous versions can use the remote backend block to configure the CLI workflow and migrate state. »CREATE STATE Start by cloning this GitHub repository. $ git clone https://github.com/hashicorp/learn-state-migration $ git clone https://github.com/hashicorp/learn-state-migration Copy Next, change into the directory. $ cd learn-state-migration $ cd learn-state-migration Copy Review the main.tf file in the working directory to get an overview of the resources you are about to create. This configuration uses the random_pet resource to generate and output a random pet name with a given number of words. The length of the name is determined by the value of the name_length variable, which defaults 3. In a real-world configuration you may have additional variables such as cloud platform credentials defined in a .tfvars file. We'll cover how to set these values in the Terraform Cloud workspace later on in this tutorial, after you've migrated the state file. ## Terraform configuration terraform { required_providers { random = { source = "hashicorp/random" version = "3.0.1" } } required_version = ">= 1.1.0" } variable "name_length" { description = "The number of words in the pet name" default = "3" } resource "random_pet" "pet_name" { length = var.name_length separator = "-" } output "pet_name" { value = random_pet.pet_name.id } ## Terraform configuration terraform { required_providers { random = { source = "hashicorp/random" version = "3.0.1" } } required_version = ">= 1.1.0" } variable "name_length" { description = "The number of words in the pet name" default = "3" } resource "random_pet" "pet_name" { length = var.name_length separator = "-" } output "pet_name" { value = random_pet.pet_name.id } Copy Initialize the directory. $ terraform init Initializing the backend... Initializing provider plugins... - Finding hashicorp/random versions matching "3.0.1"... - Installing hashicorp/random v3.0.1... - Installed hashicorp/random v3.0.1 (signed by HashiCorp) Terraform has created a lock file .terraform.lock.hcl to record the provider selections it made above. Include this file in your version control repository so that Terraform can guarantee to make the same selections by default when you run "terraform init" in the future. Terraform has been successfully initialized! $ terraform init Initializing the backend... Initializing provider plugins... - Finding hashicorp/random versions matching "3.0.1"... - Installing hashicorp/random v3.0.1... - Installed hashicorp/random v3.0.1 (signed by HashiCorp) Terraform has created a lock file .terraform.lock.hcl to record the provider selections it made above. Include this file in your version control repository so that Terraform can guarantee to make the same selections by default when you run "terraform init" in the future. Terraform has been successfully initialized! Copy After Terraform initializes, apply the configuration and approve the run by typing "yes" at the prompt. $ terraform apply Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols: + create Terraform will perform the following actions: # random_pet.pet_name will be created + resource "random_pet" "pet_name" { + id = (known after apply) + length = 3 + separator = "-" } Plan: 1 to add, 0 to change, 0 to destroy. Changes to Outputs: + pet_name = (known after apply) Do you want to perform these actions? Terraform will perform the actions described above. Only 'yes' will be accepted to approve. Enter a value: yes random_pet.pet_name: Creating... random_pet.pet_name: Creation complete after 0s [id=mostly-joint-lacewing] Apply complete! Resources: 1 added, 0 changed, 0 destroyed. Outputs: pet_name = "mostly-joint-lacewing" $ terraform apply Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols: + create Terraform will perform the following actions: # random_pet.pet_name will be created + resource "random_pet" "pet_name" { + id = (known after apply) + length = 3 + separator = "-" } Plan: 1 to add, 0 to change, 0 to destroy. Changes to Outputs: + pet_name = (known after apply) Do you want to perform these actions? Terraform will perform the actions described above. Only 'yes' will be accepted to approve. Enter a value: yes random_pet.pet_name: Creating... random_pet.pet_name: Creation complete after 0s [id=mostly-joint-lacewing] Apply complete! Resources: 1 added, 0 changed, 0 destroyed. Outputs: pet_name = "mostly-joint-lacewing" Copy Terraform will output a three word randomly generated pet name. »SET UP TERRAFORM CLOUD Now that you have a local state file, you need to create a cloud code block in your configuration. The Terraform CLI workflow saves your state as a terraform.tfstate file in the directory where you run terraform apply. To migrate your state to Terraform Cloud, update the cloud block and change the <ORG_NAME> to your Terraform Cloud organization name. terraform { required_version = ">= 1.1.0" required_providers { random = { source = "hashicorp/random" version = "3.0.1" } } cloud { organization = "<ORG_NAME>" workspaces { name = "Example-Workspace" } } } terraform { required_version = ">= 1.1.0" required_providers { random = { source = "hashicorp/random" version = "3.0.1" } } cloud { organization = "<ORG_NAME>" workspaces { name = "Example-Workspace" } } } Copy Replace the organization and workspaces attribute values with the name of your Terraform Cloud organization and desired workspace name. While the organization defined in the cloud stanza must already exist, the workspace does not have to; Terraform Cloud will create it if necessary. If you opt to use a workspace that already exists, the workspace must not have any existing states. Note: If you are familiar with running Terraform using the CLI, you may have used Terraform workspaces. Terraform Cloud workspaces behave differently than Terraform CLI workspaces. Terraform CLI workspaces allow multiple state files to exist within a single directory, enabling you to use one configuration for multiple environments. Terraform Cloud workspaces contain everything needed to manage a given set of infrastructure, and function like separate working directories. »AUTHENTICATE WITH TERRAFORM CLOUD Now that you have defined your Terraform Cloud configuration, you must authenticate with Terraform Cloud in order to proceed with initialization. In order to authenticate with Terraform Cloud, run the terraform login subcommand, and follow the prompts to log in. Note: If you are using a version of Terraform prior to 0.12.21, the terraform login command is not available. Instead, set up a CLI configuration file to authenticate. $ terraform login Terraform will request an API token for app.terraform.io using your browser. If login is successful, Terraform will store the token in plain text in the following file for use by subsequent commands: /Users/username/.terraform.d/credentials.tfrc.json Do you want to proceed? Only 'yes' will be accepted to confirm. Enter a value: $ terraform login Terraform will request an API token for app.terraform.io using your browser. If login is successful, Terraform will store the token in plain text in the following file for use by subsequent commands: /Users/username/.terraform.d/credentials.tfrc.json Do you want to proceed? Only 'yes' will be accepted to confirm. Enter a value: Copy Respond to the confirmation prompt with a yes. For more detailed instructions on logging in, see the login tutorial. »MIGRATE THE STATE FILE Once you have authenticated to Terraform Cloud, you're ready to migrate your local state file to Terraform Cloud. To begin the migration, reinitialize. This causes Terraform to recognize your cloud block configuration. $ terraform init Initializing Terraform Cloud... Do you wish to proceed? As part of migrating to Terraform Cloud, Terraform can optionally copy your current workspace state to the configured Terraform Cloud workspace. Answer "yes" to copy the latest state snapshot to the configured Terraform Cloud workspace. Answer "no" to ignore the existing state and just activate the configured Terraform Cloud workspace with its existing state, if any. Should Terraform migrate your existing state? Enter a value: $ terraform init Initializing Terraform Cloud... Do you wish to proceed? As part of migrating to Terraform Cloud, Terraform can optionally copy your current workspace state to the configured Terraform Cloud workspace. Answer "yes" to copy the latest state snapshot to the configured Terraform Cloud workspace. Answer "no" to ignore the existing state and just activate the configured Terraform Cloud workspace with its existing state, if any. Should Terraform migrate your existing state? Enter a value: Copy During reinitialization, Terraform presents a prompt saying that it will copy the state file to your Terraform Cloud workspace. Enter yes and Terraform will migrate the state from your local machine to Terraform Cloud. »CONFIGURE THE TERRAFORM CLOUD WORKSPACE After migrating your state to Terraform Cloud, log in to the Terraform Cloud web UI, find your workspace name as defined in your cloud block, and click on it. Navigate to the States tab of the workspace, and see your first action within the workspace. Remember that your configuration has a variable that you need to add to the new workspace. Click the "Variables" tab in the workspace and then "Add variable". Enter the name of the variable, name_length, as the key. Then enter a new value, 5, and save the variable. For real-world configurations, add cloud platform credentials and any other configuration variables to the workspace as well. »INITIATE A RUN IN THE NEW WORKSPACE After verifying that the state was migrated to the Terraform Cloud workspace, remove the local state file. $ rm terraform.tfstate $ rm terraform.tfstate Copy Apply a new run. $ terraform apply Running apply in Terraform Cloud. Output will stream here. Pressing Ctrl-C will cancel the remote apply if it's still pending. If the apply started it will stop streaming the logs, but will not stop the apply running remotely. Preparing the remote apply... To view this run in a browser, visit: https://app.terraform.io/app/hashicorp-learn/res-new-test/runs/run-sfg5gvGnfdL7JPVc Waiting for the plan to start... ##... $ terraform apply Running apply in Terraform Cloud. Output will stream here. Pressing Ctrl-C will cancel the remote apply if it's still pending. If the apply started it will stop streaming the logs, but will not stop the apply running remotely. Preparing the remote apply... To view this run in a browser, visit: https://app.terraform.io/app/hashicorp-learn/res-new-test/runs/run-sfg5gvGnfdL7JPVc Waiting for the plan to start... ##... Copy Terraform will stream logs from Terraform Cloud and provide a link to the run in the Terraform Cloud UI. You set a new value for the name_length variable, so the resource will be replaced with one matching the new parameters. »NEXT STEPS Destroy the resources you created for this tutorial by first clicking the "Settings" option in the Terraform Cloud workspace, selecting "Destruction and Deletion", ensuring the "Allow destroy plans" checkbox is checked, and then clicking "Queue destroy plan". After the resources have been destroyed, return to the "Destruction and Deletion" page and click "Delete from Terraform Cloud" to delete the workspace. In this tutorial, you migrated a state file from your local machine to a Terraform Cloud workspace. To learn how to migrate the state files of multiple local workspaces, or restrict workspace access to a particular team, see the following documentation. * Migrating State from Multiple Local Workspaces * Managing Workspace Access If you have a large number of state files that you would like to migrate to Terraform Cloud, consider using the Terraform Cloud API to do so. For information on uploading state versions using the API, refer to the State Version API documentation. Was this tutorial helpful? Yes No -------------------------------------------------------------------------------- PreviousGo to previous tutorial: Import Terraform Configuration NextGo to next tutorial: Manage Resources in Terraform State * System Status * Cookie Manager * Terms of Use * Security * Privacy stdin: is not a tty We use cookies & other similar technology to collect data to improve your experience on our site, as described in our Privacy Policy and Cookie Policy. Manage PreferencesAccept