Skip to content

Instantly share code, notes, and snippets.

@mccutchen
Created March 4, 2016 16:35
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 mccutchen/c1cc063a7beba88f8827 to your computer and use it in GitHub Desktop.
Save mccutchen/c1cc063a7beba88f8827 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
"""
Once you've used `terraforming` to generate both HCL resource defintions and a
`terraform.tfstate` file to import your existing AWS resources into terraform,
your new resources will be littered with references to specific AWS resource
IDs rather than symbolic references to terraform-level resources.
This script will attempt to rewrite those IDs with symbolic references, so that
terrafrom can properly manage the resources and build a dependency graph
between them.
Example usage, from within a directory containing your `terraform.tfstate`
file:
cat my-resource-defs.tf | update-terraform-refs.py > my-updated-defs.tf
"""
import json
import re
import sys
def make_id_map():
state = json.load(open('terraform.tfstate'))
id_map = {}
for module in state['modules']:
for resource_name, resource_def in module['resources'].iteritems():
rid = resource_def['primary']['id']
if rid != resource_name.split('.')[-1]:
id_map[rid] = resource_name
return id_map
def main():
id_map = make_id_map()
defs = sys.stdin.read()
for rid, name in id_map.iteritems():
pattern = r'"%s"' % re.escape(rid)
replace = r'"${%s.id}"' % name
defs = re.sub(pattern, replace, defs)
print defs
if __name__ == '__main__':
sys.exit(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment