Skip to content

Instantly share code, notes, and snippets.

@ebuildy
Created December 8, 2023 16:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ebuildy/8269483cba2e78523306b7f82de147ee to your computer and use it in GitHub Desktop.
Save ebuildy/8269483cba2e78523306b7f82de147ee to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
"""
To generate json plan:
terraform plan -var-file=..... -out=output.tfplan
terraform show -json output.tfplan > plan.json
"""
import argparse
import json
import sys
parser = argparse.ArgumentParser(
prog='modularize-state',
description='Generate terraform mv instructions to migrate state resources into module',
usage="bin/modularize-state.py plan.json, then copy paste intructions")
parser.add_argument('-v', '--verbose', action='store_true')
parser.add_argument('inplan', nargs='?', type=argparse.FileType('r'), default=sys.stdin)
args = parser.parse_args()
plan_data = json.loads(args.inplan.read())
resource_changes = plan_data["resource_changes"]
resources_to_delete = list(filter(lambda c: c["change"]["actions"][0] == "delete", resource_changes))
resources_to_create = list(filter(lambda c: c["change"]["actions"][0] == "create", resource_changes))
if args.verbose:
[print(f"- {res['address']}") for res in resources_to_delete]
print()
[print(f"+ {res['address']}") for res in resources_to_create]
print()
for resource_to_delete in resources_to_delete:
resource_to_delete_id = resource_to_delete["address"]
for resource_to_create in resources_to_create:
resource_to_create_id = resource_to_create["address"]
if resource_to_create_id.endswith(resource_to_delete_id):
print(f"terraform state mv '{resource_to_delete_id}' '{resource_to_create_id}'")
@tsouloumiacpetal
Copy link

terraform show -json output.tfplan > plan.json

On peut tu piper ca direct dans ton script ? 😆

terraform show -json output.tfplan | python3 modularize-state.py -

@ebuildy
Copy link
Author

ebuildy commented Dec 11, 2023

terraform show -json output.tfplan > plan.json

On peut tu piper ca direct dans ton script ? 😆

terraform show -json output.tfplan | python3 modularize-state.py -

sure! grâce au default=sys.stdin

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment