forked from AdaCore/e3-aws
/
__init__.py
481 lines (393 loc) · 15.4 KB
/
__init__.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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
from e3.aws import client
from e3.env import Env
from enum import Enum
import re
import yaml
VALID_STACK_NAME = re.compile('^[a-zA-Z][a-zA-Z0-9-]*$')
VALID_STACK_NAME_MAX_LEN = 128
class AWSType(Enum):
"""Cloud Formation resource types."""
EC2_EIP = 'AWS::EC2::EIP'
EC2_INSTANCE = 'AWS::EC2::Instance'
EC2_INTERNET_GATEWAY = 'AWS::EC2::InternetGateway'
EC2_NAT_GATEWAY = 'AWS::EC2::NatGateway'
EC2_NETWORK_INTERFACE = 'AWS::EC2::NetworkInterface'
EC2_ROUTE = 'AWS::EC2::Route'
EC2_ROUTE_TABLE = 'AWS::EC2::RouteTable'
EC2_SECURITY_GROUP = 'AWS::EC2::SecurityGroup'
EC2_SUBNET = 'AWS::EC2::Subnet'
EC2_SUBNET_ROUTE_TABLE_ASSOCIATION = \
'AWS::EC2::SubnetRouteTableAssociation'
EC2_VOLUME = 'AWS::EC2::Volume'
EC2_VPC = 'AWS::EC2::VPC'
EC2_VPC_ENDPOINT = 'AWS::EC2::VPCEndpoint'
EC2_VPC_GATEWAY_ATTACHMENT = 'AWS::EC2::VPCGatewayAttachment'
IAM_ROLE = 'AWS::IAM::Role'
IAM_POLICY = 'AWS::IAM::Policy'
IAM_INSTANCE_PROFILE = 'AWS::IAM::InstanceProfile'
ROUTE53_HOSTED_ZONE = 'AWS::Route53::HostedZone'
ROUTE53_RECORDSET = 'AWS::Route53::RecordSet'
S3_BUCKET = 'AWS::S3::Bucket'
S3_BUCKET_POLICY = 'AWS::S3::BucketPolicy'
SERVICE_DISCOVERY_PRIVATE_DNS_NAMESPACE = \
'AWS::ServiceDiscovery::PrivateDnsNamespace'
CODE_COMMIT_REPOSITORY = \
'AWS::CodeCommit::Repository'
class GetAtt(object):
"""Intrinsic function Fn::Getatt."""
def __init__(self, name, attribute):
"""Initialize a Getatt instance.
:param name: resource name
:type name: str
:param attribute: attribute name
:type attribute: str
"""
self.name = name
self.attribute = attribute
class Ref(object):
"""Intrinsic function Fn::Ref."""
def __init__(self, name):
"""Initialize a reference.
:param name: resource name
:type name: str
"""
self.name = name
class Base64(object):
"""Intrinsic function Fn::Base64."""
def __init__(self, content):
"""Initialize a base64 content.
:param content: content to be encoded into base64
:type content: str
"""
self.content = content
class Join(object):
"""Intrinsic function Fn::Join."""
def __init__(self, content, delimiter=""):
"""Initialize a Join object.
:param content: a list
:type content: list
:param delimiter: a join delimiter
:type delimiter: str
"""
self.content = content
self.delimiter = delimiter
# Declare Yaml representer for intrinsic functions
def getatt_representer(dumper, data):
return dumper.represent_scalar(
'!GetAtt', '%s.%s' % (data.name, data.attribute))
def ref_representer(dumper, data):
return dumper.represent_scalar('!Ref', data.name)
def base64_representer(dumper, data):
return dumper.represent_dict({"Fn::Base64": data.content})
def join_representer(dumper, data):
return dumper.represent_sequence('!Join', [data.delimiter, data.content])
class CFNYamlDumper(yaml.Dumper):
def __init__(self, stream,
default_style=None,
default_flow_style=None,
canonical=None,
indent=None,
width=None,
allow_unicode=None,
line_break=None,
encoding=None,
explicit_start=None,
explicit_end=None,
version=None,
tags=None,
sort_keys=True):
"""Yaml dumper for cloud formation templates.
See yaml.Dumper documentation.
"""
super(CFNYamlDumper, self).__init__(
stream=stream,
default_style=default_style,
default_flow_style=default_flow_style,
canonical=canonical,
indent=indent,
width=width,
allow_unicode=allow_unicode,
line_break=line_break,
encoding=encoding,
explicit_start=explicit_start,
explicit_end=explicit_end,
version=version,
tags=tags,
sort_keys=sort_keys)
self.add_representer(GetAtt, getatt_representer)
self.add_representer(Ref, ref_representer)
self.add_representer(Base64, base64_representer)
self.add_representer(Join, join_representer)
def ignore_aliases(self, data):
"""Ignore aliases."""
return True
class Resource(object):
"""A CloudFormation resource."""
# List of valid attribute names
ATTRIBUTES = ()
def __init__(self, name, kind):
"""Initialize a resource.
:param name: name of the resource (alphanumeric)
:type name: str
:param kind: resource kind
:type kind: e3.aws.cfn.types.AWSType
"""
assert isinstance(kind, AWSType), \
'resource kind should be an AWSType: found %s' % kind
assert name.isalnum(), \
'resource name should be alphanumeric: found %s' % name
self.name = name
self.kind = kind
self.depends = None
# Track region in which the resource is created
e = Env()
if hasattr(e, 'aws_env'):
self.region = Env().aws_env.default_region
else:
self.region = 'invalid-region'
self.metadata = {}
def getatt(self, name):
"""Return an attribute reference.
:param name: attribute name. should one of the valid attribute
declared in ATTRIBUTES class variable
:type name: str
:return: a getatt object
:rtype: e3.aws.cfn.types.GetAtt
"""
assert name in self.ATTRIBUTES, 'invalid attribute %s' % name
return GetAtt(self.name, name)
@property
def ref(self):
"""Return a reference to the current resource.
:return: a reference
:rtype: e3.aws.cfn.types.Ref
"""
return Ref(self.name)
@property
def properties(self):
"""Return the resource properties dict.
:return: the resources Properties key value for the current resource.
:rtype: dict
"""
return {}
def export(self):
"""Export resource as a template fragment.
:return: the dict representing the resources. The resulting dict can
be serialized using Yaml to get a valid CloudFormation template
fragment
:rtype: dict
"""
result = {'Type': self.kind.value,
'Properties': self.properties}
if self.depends is not None:
result['DependsOn'] = self.depends
if self.metadata:
result['Metadata'] = self.metadata
return result
class Stack(object):
"""A CloudFormation stack."""
def __init__(self, name, description=None):
"""Initialize a stack.
:param name: stack name
:type name: str
:param description: a description of the stack
:type description: str | None
"""
assert re.match(VALID_STACK_NAME, name) and \
len(name) <= VALID_STACK_NAME_MAX_LEN, \
'invalid stack name: %s' % name
self.resources = {}
self.name = name
self.description = description
def add(self, element):
"""Add a resource or merge a stack.
:param element: if a resource add the resource to the stack. If a stack
merge its resources into the current stack.
:type element: Stack | Resources
:return: the current stack
:rtype: Stack
"""
assert isinstance(element, Resource) or isinstance(element, Stack), \
"a resource or a stack is expected. got %s" % element
assert element.name not in self.resources, \
'resource already exist: %s' % element.name
self.resources[element.name] = element
return self
def __iadd__(self, element):
"""Add a resource or merge a stack.
:param element: if a resource add the resource to the stack. If a stack
merge its resources into the current stack.
:type element: Stack | Resources
:return: the current stack
:rtype: Stack
"""
return self.add(element)
def __getitem__(self, key):
if key not in self.resources:
raise KeyError
return self.resources[key]
def __contains__(self, key):
return key in self.resources
def export(self):
"""Export stack as dict.
:return: a dict that can be serialized as YAML to produce a template
:rtype: dict
"""
resources = {}
for resource in self.resources.values():
if isinstance(resource, Resource):
assert resource.name not in resources
resources[resource.name] = resource.export()
else:
# resource is a stack
stack_resources = resource.export()['Resources']
for k, v in stack_resources.items():
assert k not in resources
resources[k] = v
result = {
'AWSTemplateFormatVersion': '2010-09-09',
'Resources': resources}
if self.description is not None:
result['Description'] = self.description
return result
@property
def body(self):
"""Export stack as a CloudFormation template.
:return: a valid CloudFormation template
:rtype: str
"""
return yaml.dump(self.export(), Dumper=CFNYamlDumper)
@client('cloudformation')
def create(self, client, url=None):
"""Create a stack.
:param client: a botocore client
:type client: botocore.client.Client. This parameter is handled by the
decorator
param url: url of the template body in S3. When not None this suppose
the user has uploaded the template body on S3 first at the given
url. Use S3 to refer to the template body rather than using inline
version allows to use template of size up to 500Ko instead of
50Ko.
:type url: str | None
"""
if url is None:
return client.create_stack(StackName=self.name,
TemplateBody=self.body,
Capabilities=['CAPABILITY_IAM'])
else:
return client.create_stack(StackName=self.name,
TemplateURL=url,
Capabilities=['CAPABILITY_IAM'])
def exists(self):
"""Check if a given stack exists.
:return: True if it does, False otherwise
"""
try:
self.state()
return True
except Exception:
return False
@client('cloudformation')
def state(self, client):
"""Return state of the stack on AWS."""
return client.describe_stacks(StackName=self.name)
@client('cloudformation')
def validate(self, client, url=None):
"""Validate a template.
:param client: a botocore client
:type client: botocore.client.Client. This parameter is handled by the
decorator
param url: url of the template body in S3. When not None this suppose
the user has uploaded the template body on S3 first at the given
url. Use S3 to refer to the template body rather than using inline
version allows to use template of size up to 500Ko instead of
50Ko.
:type url: str | None
"""
if url is None:
return client.validate_template(TemplateBody=self.body)
else:
return client.validate_template(TemplateURL=url)
@client('cloudformation')
def create_change_set(self, name, client, url=None):
"""Create a change set.
This creates a difference between the state of the stack on AWS servers
and the current one generated with e3-aws.
:param client: a botocore client. This parameter is handled by the
decorator
:type client: botocore.client.Client
:param name: name of the changeset
:type name: str
:param url: url of the template body in S3. When not None this suppose
the user has uploaded the template body on S3 first at the given
url. Use S3 to refer to the template body rather than using inline
version allows to use template of size up to 500Ko instead of
50Ko.
:type url: str | None
"""
if url is None:
return client.create_change_set(ChangeSetName=name,
StackName=self.name,
TemplateBody=self.body,
Capabilities=['CAPABILITY_IAM'])
else:
return client.create_change_set(ChangeSetName=name,
StackName=self.name,
TemplateURL=url,
Capabilities=['CAPABILITY_IAM'])
@client('cloudformation')
def describe_change_set(self, name, client):
"""Describe a change set.
Retrieve status of a given changeset
:param client: a botocore client
:type client: botocore.client.Client
:param name: name of the changeset
:type name: str
"""
return client.describe_change_set(ChangeSetName=name,
StackName=self.name)
@client('cloudformation')
def delete_change_set(self, name, client):
"""Delete a change set.
:param client: a botocore client
:type client: botocore.client.Client
:param name: name of the changeset
:type name: str
"""
return client.delete_change_set(ChangeSetName=name,
StackName=self.name)
@client('cloudformation')
def delete(self, client):
"""Delete a stack.
Delete a stack. Note that operation is aynchron
:param client: a botocore client
:type client: botocore.client.Client
"""
return client.delete_stack(StackName=self.name)
@client('cloudformation')
def cost(self, client):
"""Compute cost of the stack (estimation).
:param client: a botocore client
:type client: botocore.client.BaseClient
"""
return client.estimate_template_cost(TemplateBody=self.body)
@client('cloudformation')
def resource_status(self, client, in_progress_only=True):
"""Return status of each resources of the stack.
The state of the stack taken is the one pushed on AWS (after a call
to create for example).
:param client: a botocore client
:type client: botocore.client.BaseClient
:param in_progress_only: if True return only resources that are in
one of the "PROGRESS" state (deletion, creation, ...)
:type in_progress_only: bool
:return: a dict associating a resource logical name to a status name
:rtype: dict
"""
aws_result = client.describe_stack_resources(StackName=self.name)
assert 'StackResources' in aws_result
result = {}
for res in aws_result['StackResources']:
if 'PROGRESS' in res['ResourceStatus'] or not in_progress_only:
result[res['LogicalResourceId']] = res['ResourceStatus']
return result