RousselTMLEARNING

TP · Terraform: from discovery to expertise

Lab: Remote state, locking, import and refactoring with correction

The correction is integrated into the TP (See the green boxes)

What you will learn in this TP
  • Configure an S3 backend with locking
  • Import an existing resource
  • Refactor with moved
Mode :

All steps and instructions are shown. Recommended for this lab: semi-guided

Introduction #

Context. The team adopts Terraform while resources already exist. You set up shared state and take over the existing resources without breaking anything.

Prerequisites: Terraform 1.10 or later, Docker, LocalStack and terraform-local (pip install localstack terraform-local); no cloud account or charges  ·  Estimated time: 50 min

A locked remote state and existing resources cleanly taken over.
Disposable environment: passwords are written in clear text to keep the lab simple. Outside a lab, keep image versions pinned and move secrets out of the file: an unversioned .env file read with ${PASSWORD:?} in the Compose file, or a Docker secret read through a *_FILE variable (for example GF_SECURITY_ADMIN_PASSWORD__FILE for Grafana).

Hands-on #

Guided steps, with their solution.

  1. 1. Prepare the backend

    Why? The state bucket is versioned so a previous version can be restored.

    Start MinIO and create a versioned bucket for state.
    See the correction
    docker run -d --name minio -p 9000:9000 -e MINIO_ROOT_USER=formation -e MINIO_ROOT_PASSWORD=formation123 quay.io/minio/minio server /data
    export AWS_ACCESS_KEY_ID=formation AWS_SECRET_ACCESS_KEY=formation123
    aws --endpoint-url http://localhost:9000 s3 mb s3://etat-terraform
    aws --endpoint-url http://localhost:9000 s3api put-bucket-versioning --bucket etat-terraform --versioning-configuration Status=Enabled
  2. 2. Declare the backend

    Why? use_lockfile creates a lock file next to the state during each operation.

    Add backend.tf pointing to MinIO and re-initialise, migrating local state.
    See the correction
    cat > backend.tf <<'EOF'
    terraform {
      backend "s3" {
        bucket                      = "etat-terraform"
        key                         = "boutique/recette.tfstate"
        region                      = "eu-west-3"
        endpoints                   = { s3 = "http://localhost:9000" }
        use_path_style              = true
        use_lockfile                = true
        skip_credentials_validation = true
        skip_region_validation      = true
        skip_requesting_account_id  = true
      }
    }
    EOF
    tflocal init -migrate-state
    aws --endpoint-url http://localhost:9000 s3 ls s3://etat-terraform/boutique/
  3. 3. Import existing resources

    Why? The import block is reviewed in merge requests like the rest of the code.

    Create a bucket "by hand", generate its code with an import block then apply.
    See the correction
    awslocal s3 mb s3://ancien-bucket-manuel
    cat > import.tf <<'EOF'
    import {
      to = aws_s3_bucket.ancien
      id = "ancien-bucket-manuel"
    }
    EOF
    tflocal plan -generate-config-out=genere.tf     # génère le bloc resource à relire
    tflocal apply -auto-approve
    tflocal state list | grep ancien
  4. 4. Rename without recreating

    Why? Without a moved block, renaming a resource would destroy and recreate it.

    Rename aws_s3_bucket.documents to aws_s3_bucket.archives with a moved block and check the plan destroys nothing.
    See the correction
    sed -i 's/aws_s3_bucket" "documents"/aws_s3_bucket" "archives"/; s/aws_s3_bucket.documents.bucket/aws_s3_bucket.archives.bucket/' main.tf
    cat > moved.tf <<'EOF'
    moved {
      from = aws_s3_bucket.documents
      to   = aws_s3_bucket.archives
    }
    EOF
    tflocal plan        # « has moved to », 0 to destroy
    tflocal apply -auto-approve

Validate your work

Check that each goal above is reached and that you get the result described in the introduction.

Difficulty level : ●●●○○ (3/5)

My progress

  • ⏱ Estimated time : ≈ 50 min

Sign in to track your progress and take notes. Sign in

⭐ Rate this lesson

4.0 initial rating from the teaching team

Sign in to rate this lesson →

💬 Questions about this lesson

No questions yet: be the first to ask for help or share your configuration.

Ask a question about this lesson →

Recommended Articles

Terraform state: remote backends, locking, import and refactoring

Manage Terraform state: the role of the state file, sensitive data, remote backends (S3, azurerm,...

Terraform best practices: structure, state, security, review and maintenance

Terraform best practices for teams: repository structure, naming, pinned versions, encrypted and ...

Terraform multi-environment, workspaces and repository organization

Organize Terraform for several environments: one folder per environment, tfvars files, CLI worksp...

Terraform: principles, architecture and workflow

Understand Terraform: declarative infrastructure as code, architecture (core, providers, state), ...

The HCL language: resources, variables, outputs, data and expressions

Writing Terraform: terraform, provider, resource and data blocks, typed variables with validation...

Testing and securing Terraform: validate, terraform test, tflint, Checkov and policies

Ensure the quality of Terraform code: fmt and validate, native terraform test tests with mocked p...

Terraform modules: designing, versioning and reusing

Structure Terraform with modules: root module and child modules, inputs and outputs, sources (loc...

Preparing for the HashiCorp Certified: Terraform Associate certification

Preparation guide for the Terraform Associate: format, official objectives (IaC concepts, workflo...

Terraform across multiple clouds: AWS, Azure, Google Cloud, OVHcloud and Kubernetes

Use Terraform with the main providers: aws, azurerm, google, ovh and openstack, kubernetes and he...

Support us

♥ SUPPORT US

Support RousselTM Learning

Courses, articles, labs and certificates stay free with no intrusive ads. A voluntary contribution, of any amount you choose, pays for hosting, lab environments and new content.

Contribute with PayPal Any amount · card or PayPal accountLearn more
QR code PayPal
Or scan this QR code with your phone

Thank you, every contribution counts!