How to Migrate Terraform state to Terraform cloud using Vscode

Emmanuel EniadeEmmanuel Eniade
7 min read

HashiCorp Terraform is an infrastructure as code tool that lets you define both cloud and on-prem resources in human-readable configuration files that you can version, reuse, and share. You can then use a consistent workflow to provision and manage all of your infrastructure throughout its lifecycle. Terraform can manage low-level components like compute, storage, and networking resources, as well as high-level components like DNS entries and SaaS features.

How does Terraform work

Terraform creates and manages resources on cloud platforms and other services through their application programming interfaces (APIs). Providers enable Terraform to work with virtually any platform or service with an accessible API.

Terraform creates and manages cloud platforms and services through their APIs

HashiCorp and the Terraform community have already written thousands of providers to manage many different types of resources and services. You can find all publicly available providers on the Terraform Registry, including Amazon Web Services (AWS), Azure, Google Cloud Platform (GCP), Kubernetes, Helm, GitHub, Splunk, DataDog, and many more.

The core Terraform workflow consists of three stages:

  • Write: You define resources, which may be across multiple cloud providers and services. For example, you might create a configuration to deploy an application on virtual machines in a Virtual Private Cloud (VPC) network with security groups and a load balancer.

  • Plan: Terraform creates an execution plan describing the infrastructure it will create, update, or destroy based on the existing infrastructure and your configuration.

  • Apply: On approval, Terraform performs the proposed operations in the correct order, respecting any resource dependencies. For example, if you update the properties of a VPC and change the number of virtual machines in that VPC, Terraform will recreate the VPC before scaling the virtual machines.

The Terraform workflow has three steps: Write, Plan, and Apply

In order to migrate Terraform state to Terraform cloud there are prequesities we must put in place for us to be able to have a successful migration and they includes;

ii). Terraform installation

(ii). Terraform cloud account

(iii) Azure login to check resources created

(iv) Github Repo creation: This is optional but for the purpose of this learning, we will use Github

Without further ado, lets dive in to the step by step guide on how to migrate Terraform state to Terraform cloud;

1. Terraform account Creation

(a). To signin with your account, go to https://app.terraform.io/session

(b) Create an Organization - In the account settings, click on "Organizations." This will take you to the organizations page. On the right side of the page, click on "Create New Organization."

© Give your organization a unique name, Input an email and click on "Create Organization"

(d) Create a New Workspace - Click On "CLI-Driven Workflow" because it supports terraform on Visual Studio Code

(e) Configure Workspace - Give your workspace a name - Select a project "Default Project" - Give a description which is optional and click on the "Create" button

(f) Overview of Terraform Organization and Workspace

2. Github Repository creation/Vscode

Github repository is optional but for the purpose of this learning, we will create a repository in Github then clone it in Vscode.

To create a repo, navigate into Github with the following steps;

(a) Click on “+” and choose new repository

(b) Give it a name

© Click on create

(d) Now our Repository is created. Now click on “code” and copy the https URL to be used for cloning in VScode.

2B. Cloning Repository

To clone repository, copy the URL above and navigate into the VScode ;

i. Click on the source control by the left, click on clone repository then paste your URL and finally click on clone as highlighted

(ii) Upon cloning, create folder and name it by following below steps in red

(iii) Boom, cloning is completed in VSCode

(Iv) Now create a file in VScode and name it "main.tf" - main.tf file is the main configuration file in Terraform, where you define your resource definitions and implement infrastructure as code logic

(v) Go to Terraform official site to select a provider registry.terraform.io/browse/providers - The URL in the browser is highlighted, showing the link to the latest version of the AzureRM provider: https://registry.terraform.io/providers/hashicorp/azurerm/latest. - "Click" "USE PROVIDER" button , which allows users to copy the code

(vi) Paste Provider"azurerm" configuration on your main.tf file - Incomplete Configuration error: you will encounter this error

  • The provider "azurerm" block is empty and only contains a comment (# Configuration options). While an empty provider block is not necessarily an error in Terraform itself, the editor might flag it as an incomplete configuration

  • (vii) Initialize Terraform - In the terminal, initialize Terraform within your project directory: This command downloads the Azure provider and sets up your working directory. Run terraform init command. This command would ensure terraform is initialized as shown below.

(vii) Login into Azure using CLI command so that every resources created can be viewed on the protal

az login

(viii) Add resources into your main.tf file created. For the purpose of this we will create the following resources using terraform configuration and then we will run terraform plan

(a). Resource group

(b) Virtual network

© Subnet

(d) Public_ip address

Issues encountered after running terraform plan

(a) I got errors after running terraform plan because i did not include subscription id and features block in the main file.

(b) Subscription id error

© To resolve the issues, I went back into the main.tf file to include the features block and Azure subscription id as shown

(d) Boom terraform plan showed all the four resources i planned to provisioned

(ix) Run terraform apply. This command would help to provision our infrastructure and there you have it. Also a terraform state is created and this need to be migrated into the Terraform cloud.

(x) Navigate back into Azure portal to see resources provisioned

  1. Migrating terraform state into Terraform cloud

    To migrate our terraform state into the cloud, the follwoings steps need to be done;

    (a) Login into the cloud with terraform command terraform login This will help to obtain the API token required for integration. - Follow the prompts to generate and enter the API token from the Terraform Cloud website. This will store the token locally for future Terraform commands.

    (b) After logging into Terraform Cloud, you will be prompted to generate a token. Provide a description, set the expiration to 7 days, and click on "Generate Token

© A copy will also be sent to your email NOTE: The token should be kept secret because it grants access to your Terraform Cloud account and resources. If someone else obtains the token, they could potentially make unauthorized changes to your infrastructure, access sensitive data, and compromise the security and integrity of your cloud environment. Keeping the token secret ensures that only authorized individuals can manage and modify your Terraform configurations and state.

(d) Paste the token by just right clicking on the terminal “once” and press enter

(e) You have successfully logged into Terraform

3B. Migration state to Terraform cloud

(i) Refer to step 1f during organization creation. click on the name of the organization as shown

(ii) Click on the workspace name as shown in red below

(iii) Set Up Cloud Integration - Add Cloud Integration Block: Include the following block (“Examplecode”: highlighted in red) in your Terraform configuration file to set up cloud integration: NOTE: Setting up cloud integration with Terraform Cloud is essential because it allows for centralized management, state storage, automation, enhanced security and collaboration

(iv) Paste the code into the terraform main.tf in the VSCode as shown

(v) Reinitialize Terraform using terraform init to apply the new backend configuration. - Terraform will prompt you to “Migrate your existing state to Terraform Cloud”. Confirm the migration by entering “yes”

(vi) Navigate back to Terraform cloud to check if state has successfully migrated as shown.

(vii) Finally states successfully migrated

(viii) The command rm terraform.tfstate* is used to delete the Terraform state files from the main

As you can see our terraform state is now empty and this concludes the project.

Many thanks for stopping by. I hope you learn one or two from today’s lecture. Incase of any question, do not hesitate to reach out.

0
Subscribe to my newsletter

Read articles from Emmanuel Eniade directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Emmanuel Eniade
Emmanuel Eniade