Skip to content

Instantly share code, notes, and snippets.

@coryodaniel
Last active May 7, 2020 23:25
Show Gist options
  • Select an option

  • Save coryodaniel/9d068230a8578b1cbe4bf6276619d3fd to your computer and use it in GitHub Desktop.

Select an option

Save coryodaniel/9d068230a8578b1cbe4bf6276619d3fd to your computer and use it in GitHub Desktop.

Revisions

  1. coryodaniel renamed this gist May 7, 2020. 1 changed file with 22 additions and 0 deletions.
    22 changes: 22 additions & 0 deletions run.sh → terraform-state-demo.files
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,25 @@
    ==> ./module <==
    ==> ./module/main.tf <==
    variable "msg" {}
    resource "null_resource" "goodbye" {
    provisioner "local-exec" {
    command = "echo ${var.msg}"
    }
    }

    ==> ./main.tf <==
    resource "null_resource" "hello" {
    provisioner "local-exec" {
    command = "echo hello world"
    }
    }

    module "goodbye-mundo" {
    source = "./module"
    msg = "goodbye mundo"
    }

    ==> ./run.sh <==
    #! /usr/bin/env bash
    rm -f *tfstate*

  2. coryodaniel created this gist May 7, 2020.
    60 changes: 60 additions & 0 deletions run.sh
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,60 @@
    #! /usr/bin/env bash
    rm -f *tfstate*

    OLD_STATE_FILE=terraform.tfstate
    NEW_STATE_FILE=new.tfstate

    OLD_RESOURCE_ADDRESS=module.goodbye-mundo.null_resource.goodbye
    NEW_RESOURCE_ADDRESS=null_resource.goodbye

    function tf_apply {
    terraform apply -auto-approve
    }

    function tf_mv_state {
    terraform state mv \
    -state=${OLD_STATE_FILE} \
    -state-out=${NEW_STATE_FILE} \
    ${OLD_RESOURCE_ADDRESS} ${NEW_RESOURCE_ADDRESS}
    }

    function tf_reset_new_state {
    terraform state rm \
    -state=${NEW_STATE_FILE} \
    null_resource.goodbye
    }

    echo "Ready to start?"
    select yn in "Yes" "No"; do
    case $yn in
    Yes ) tf_apply; break;;
    No ) exit;;
    esac
    done

    echo
    echo "Terraform should have cleanly applied creating a state file: ${OLD_STATE_FILE}"
    echo "This file should contain two resources:"
    echo " - A top-level resource: null_resource.hello"
    echo " - A module w/ a single resource: ${OLD_RESOURCE_ADDRESS}"
    echo

    echo "Move inner module (${OLD_RESOURCE_ADDRESS}) state?"
    select yn in "Yes" "No"; do
    case $yn in
    Yes ) tf_mv_state; break;;
    No ) exit;;
    esac
    done

    echo
    echo "Terraform should have moved the inner-module (${OLD_RESOURCE_ADDRESS}) to ${NEW_STATE_FILE} at the address ${NEW_RESOURCE_ADDRESS}"
    echo

    echo "Reset new state file ${NEW_STATE_FILE}?"
    select yn in "Yes" "No"; do
    case $yn in
    Yes ) tf_reset_new_state; break;;
    No ) exit;;
    esac
    done