-
Notifications
You must be signed in to change notification settings - Fork 93
/
terraform.py
303 lines (222 loc) · 8.04 KB
/
terraform.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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
import contextlib
import io
import json
import logging
import os
import platform
import re
import subprocess
import sys
import tempfile
import urllib.request
import zipfile
from typing import Any, Dict, List
from _nebari import constants
from _nebari.utils import deep_merge, run_subprocess_cmd, timer
logger = logging.getLogger(__name__)
class TerraformException(Exception):
pass
def deploy(
directory,
terraform_init: bool = True,
terraform_import: bool = False,
terraform_apply: bool = True,
terraform_destroy: bool = False,
input_vars: Dict[str, Any] = None,
state_imports: List = None,
):
"""Execute a given terraform directory.
Parameters:
directory: directory in which to run terraform operations on
terraform_init: whether to run `terraform init` default True
terraform_import: whether to run `terraform import` default
False for each `state_imports` supplied to function
terraform_apply: whether to run `terraform apply` default True
terraform_destroy: whether to run `terraform destroy` default
False
input_vars: supply values for "variable" resources within
terraform module
state_imports: (addr, id) pairs for iterate through and attempt
to terraform import
"""
input_vars = input_vars or {}
state_imports = state_imports or []
with tempfile.NamedTemporaryFile(
mode="w", encoding="utf-8", suffix=".tfvars.json"
) as f:
json.dump(input_vars, f.file)
f.file.flush()
if terraform_init:
init(directory)
if terraform_import:
for addr, id in state_imports:
tfimport(
addr, id, directory=directory, var_files=[f.name], exist_ok=True
)
if terraform_apply:
apply(directory, var_files=[f.name])
if terraform_destroy:
destroy(directory, var_files=[f.name])
return output(directory)
def download_terraform_binary(version=constants.TERRAFORM_VERSION):
os_mapping = {
"linux": "linux",
"win32": "windows",
"darwin": "darwin",
"freebsd": "freebsd",
"openbsd": "openbsd",
"solaris": "solaris",
}
architecture_mapping = {
"x86_64": "amd64",
"i386": "386",
"armv7l": "arm",
"aarch64": "arm64",
"arm64": "arm64",
}
download_url = f"https://releases.hashicorp.com/terraform/{version}/terraform_{version}_{os_mapping[sys.platform]}_{architecture_mapping[platform.machine()]}.zip"
filename_directory = os.path.join(tempfile.gettempdir(), "terraform", version)
filename_path = os.path.join(filename_directory, "terraform")
if not os.path.isfile(filename_path):
logger.info(
f"downloading and extracting terraform binary from url={download_url} to path={filename_path}"
)
with urllib.request.urlopen(download_url) as f:
bytes_io = io.BytesIO(f.read())
download_file = zipfile.ZipFile(bytes_io)
download_file.extract("terraform", filename_directory)
os.chmod(filename_path, 0o555)
return filename_path
def run_terraform_subprocess(processargs, **kwargs):
terraform_path = download_terraform_binary()
logger.info(f" terraform at {terraform_path}")
if run_subprocess_cmd([terraform_path] + processargs, **kwargs):
raise TerraformException("Terraform returned an error")
def version():
terraform_path = download_terraform_binary()
logger.info(f"checking terraform={terraform_path} version")
version_output = subprocess.check_output([terraform_path, "--version"]).decode(
"utf-8"
)
return re.search(r"(\d+)\.(\d+).(\d+)", version_output).group(0)
def init(directory=None, upgrade=True):
logger.info(f"terraform init directory={directory}")
with timer(logger, "terraform init"):
command = ["init"]
if upgrade:
command.append("-upgrade")
run_terraform_subprocess(command, cwd=directory, prefix="terraform")
def apply(directory=None, targets=None, var_files=None):
targets = targets or []
var_files = var_files or []
logger.info(f"terraform apply directory={directory} targets={targets}")
command = (
["apply", "-auto-approve"]
+ ["-target=" + _ for _ in targets]
+ ["-var-file=" + _ for _ in var_files]
)
with timer(logger, "terraform apply"):
run_terraform_subprocess(command, cwd=directory, prefix="terraform")
def output(directory=None):
terraform_path = download_terraform_binary()
logger.info(f"terraform={terraform_path} output directory={directory}")
with timer(logger, "terraform output"):
return json.loads(
subprocess.check_output(
[terraform_path, "output", "-json"], cwd=directory
).decode("utf8")[:-1]
)
def tfimport(addr, id, directory=None, var_files=None, exist_ok=False):
var_files = var_files or []
logger.info(f"terraform import directory={directory} addr={addr} id={id}")
command = ["import"] + ["-var-file=" + _ for _ in var_files] + [addr, id]
logger.error(str(command))
with timer(logger, "terraform import"):
try:
run_terraform_subprocess(
command,
cwd=directory,
prefix="terraform",
strip_errors=True,
timeout=30,
)
except TerraformException as e:
if not exist_ok:
raise e
def refresh(directory=None, var_files=None):
var_files = var_files or []
logger.info(f"terraform refresh directory={directory}")
command = ["refresh"] + ["-var-file=" + _ for _ in var_files]
with timer(logger, "terraform refresh"):
run_terraform_subprocess(command, cwd=directory, prefix="terraform")
def destroy(directory=None, targets=None, var_files=None):
targets = targets or []
var_files = var_files or []
logger.info(f"terraform destroy directory={directory} targets={targets}")
command = (
[
"destroy",
"-auto-approve",
]
+ ["-target=" + _ for _ in targets]
+ ["-var-file=" + _ for _ in var_files]
)
with timer(logger, "terraform destroy"):
run_terraform_subprocess(command, cwd=directory, prefix="terraform")
def rm_local_state(directory=None):
logger.info(f"rm local state file terraform.tfstate directory={directory}")
tfstate_path = "terraform.tfstate"
if directory:
tfstate_path = os.path.join(directory, tfstate_path)
if os.path.isfile(tfstate_path):
os.remove(tfstate_path)
# ========== Terraform JSON ============
@contextlib.contextmanager
def tf_context(filename):
try:
tf_clear()
yield
finally:
with open(filename, "w") as f:
f.write(tf_render())
tf_clear()
_TF_OBJECTS = {}
def tf_clear():
global _TF_OBJECTS
_TF_OBJECTS = {}
def tf_render():
global _TF_OBJECTS
return json.dumps(_TF_OBJECTS, indent=4)
def tf_render_objects(terraform_objects):
return json.dumps(deep_merge(*terraform_objects), indent=4)
def register(f):
def wrapper(*args, **kwargs):
global _TF_OBJECTS
obj = f(*args, **kwargs)
_TF_OBJECTS = deep_merge(_TF_OBJECTS, obj)
return obj
return wrapper
@register
def Terraform(**kwargs):
return {"terraform": kwargs}
@register
def RequiredProvider(_name, **kwargs):
return {"terraform": {"required_providers": {_name: kwargs}}}
@register
def Provider(_name, **kwargs):
return {"provider": {_name: kwargs}}
@register
def TerraformBackend(_name, **kwargs):
return {"terraform": {"backend": {_name: kwargs}}}
@register
def Variable(_name, **kwargs):
return {"variable": {_name: kwargs}}
@register
def Data(_resource_type, _name, **kwargs):
return {"data": {_resource_type: {_name: kwargs}}}
@register
def Resource(_resource_type, _name, **kwargs):
return {"resource": {_resource_type: {_name: kwargs}}}
@register
def Output(_name, **kwargs):
return {"output": {_name: kwargs}}