Skip to content

Instantly share code, notes, and snippets.

@coryodaniel
Last active May 7, 2020 23:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coryodaniel/9d068230a8578b1cbe4bf6276619d3fd to your computer and use it in GitHub Desktop.
Save coryodaniel/9d068230a8578b1cbe4bf6276619d3fd to your computer and use it in GitHub Desktop.
terraform state move between multiple files demo
==> ./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*
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment