Created
March 4, 2016 16:35
-
-
Save mccutchen/c1cc063a7beba88f8827 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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