-
Notifications
You must be signed in to change notification settings - Fork 4
/
mergestates.py
164 lines (137 loc) · 5.21 KB
/
mergestates.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
import tempfile
import json
import sys
import os
DEBUG = os.getenv("DEBUG", False)
DRYRUN = os.getenv("DRYRUN", False)
def run(dir, command):
if DEBUG:
print(command)
return os.system("cd "+dir+"; "+command)
def exists_resource(resource, resources):
for item in resources:
# "mode":"data",
# "type":"aws_route53_zone",
# "name":"private",
if item["mode"] == resource["mode"] and item["type"] == resource["type"] and item["name"] == resource["name"]:
if DEBUG:
print("FOUND " + resource['mode'] + " " + resource['type'] + " " + resource['name'])
return True
return False
###############################################################################
if len(sys.argv) <= 2 :
sys.exit("Usage: "+ sys.argv[0] + " <project1> <project2> ... <target_project>")
for project in sys.argv[1:]:
# check if directory exists
args = project.split(':')
if len(args) == 1:
if not os.path.isdir(project):
sys.exit("Directory " + project + " does not exist")
else:
if not os.path.isdir(args[0]):
sys.exit("Directory " + args[0] + " within "+ project + " does not exist")
try:
tmpdir = tempfile.mkdtemp()
if DEBUG:
print("tmpdir: " + tmpdir)
projects = []
i=0
for project in sys.argv[1:-1]:
args = project.split(':')
if len(args) == 1:
projects.append({'name': str(i),'path': project, "tmpfile": tmpdir+"/"+str(i)})
else:
projects.append({'name': str(i),'path': args[0], "tmpfile": tmpdir+"/"+str(i), "item": args[1]})
i+=1
if DEBUG:
print("projects:")
for project in projects:
print(" " + project['path'])
if "item" in project.keys():
print(" item: " + project["item"])
target_project = sys.argv[-1]
if DEBUG:
print("target: " + sys.argv[-1])
# target terraform state
if run(target_project, "terraform state pull > " + tmpdir+'/target'):
sys.exit("Error retrieving terraform state for " + project['path'])
# load json target state
try:
target_state = json.load(open(tmpdir+'/target'))
except:
sys.exit("Error loading target's terraform state")
# retrieve terraform states
for project in projects:
if run(project['path'], "terraform state pull > " + project['tmpfile']):
sys.exit("Error retrieving terraform state for " + project['path'])
else:
# load json state
try:
state = json.load(open(project['tmpfile']))
except:
sys.exit("Error loading terraform state for: " + project['path'])
# merge all resources
if "item" not in project.keys():
resources = state['resources']
for resource in target_state['resources']:
# merge data resources skipping source resources
if resource["mode"] == "data" and exists_resource(resource, resources):
if DEBUG:
print(" " + resource['type'] + "/" + resource['name'] + " exists in target state")
try:
resources.remove(resource)
except:
if DEBUG:
print(" skipping "+ resource['mode'] + "." + resource['type'] + "." + resource['name'])
pass
# print(str(resources))
else:
# merge specific resource
resources = []
for resource in state['resources']:
# {'module': 'module.spinnaker-service.module.rosco.module.kms-parameter-store[0]', 'mode': 'managed', 'type': 'aws_iam_role_policy_attachment', 'name': 'ssm_role_policy_attachment',
base = ''
if 'module' in resource.keys():
base = resource['module'] + '.'
if resource['mode'] == 'data':
resource_path = base+resource['mode']+'.'+resource['type']+'.'+resource['name']
else:
resource_path = base+resource['type']+'.'+resource['name']
if resource_path == project['item']:
if resource["mode"] == "data" and exists_resource(resource, target_state['resources']):
if DEBUG:
print(" skipping " + resource_path + " Already exists in target state")
else:
if DEBUG:
print(">> adding " + resource_path)
resources.append(resource)
if DEBUG and len(resources) == 0:
print(" no-op merge for " + project['path'])
# merge resources into target state
target_state['resources'] = resources + target_state['resources']
# increment serial
target_state['serial'] = target_state['serial'] + 1
# write merged state
with open(tmpdir+'/merged', 'w') as outfile:
json.dump(target_state, outfile)
if not DRYRUN:
if run(target_project, "terraform state push " + tmpdir+'/merged'):
sys.exit("Error pushing terraform state to " + target_project)
else:
print("DRYRUN - skipping: terraform state push")
except Exception as e:
if DEBUG:
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
print(exc_type, fname, exc_tb.tb_lineno)
print("Error: " + str(e))
sys.exit(1)
finally:
if not DRYRUN:
# remove tmpdir
if tmpdir and os.path.isdir(tmpdir):
if DEBUG:
print("removing tmpdir: " + tmpdir)
os.system("rm -rf " + tmpdir)
else:
print("not removing temporal files: " + tmpdir)