forked from cloud-custodian/cloud-custodian
-
Notifications
You must be signed in to change notification settings - Fork 0
/
asg.py
1720 lines (1402 loc) · 57.1 KB
/
asg.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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2015-2017 Capital One Services, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import, division, print_function, unicode_literals
from botocore.client import ClientError
from collections import Counter
from concurrent.futures import as_completed
from dateutil.parser import parse
import itertools
import time
from c7n.actions import Action
from c7n.exceptions import PolicyValidationError
from c7n.filters import ValueFilter, AgeFilter, Filter
from c7n.filters.offhours import OffHour, OnHour
import c7n.filters.vpc as net_filters
from c7n.manager import resources
from c7n import query
from c7n.tags import TagActionFilter, DEFAULT_TAG, TagCountFilter, TagTrim, TagDelayedAction
from c7n.utils import local_session, type_schema, chunks, get_retry
from .ec2 import deserialize_user_data
@resources.register('asg')
class ASG(query.QueryResourceManager):
class resource_type(query.TypeInfo):
service = 'autoscaling'
arn = 'AutoScalingGroupARN'
arn_type = 'autoScalingGroup'
arn_separator = ":"
id = name = 'AutoScalingGroupName'
date = 'CreatedTime'
dimension = 'AutoScalingGroupName'
enum_spec = ('describe_auto_scaling_groups', 'AutoScalingGroups', None)
filter_name = 'AutoScalingGroupNames'
filter_type = 'list'
config_type = 'AWS::AutoScaling::AutoScalingGroup'
default_report_fields = (
'AutoScalingGroupName',
'CreatedTime',
'LaunchConfigurationName',
'count:Instances',
'DesiredCapacity',
'HealthCheckType',
'list:LoadBalancerNames',
)
retry = staticmethod(get_retry(('ResourceInUse', 'Throttling',)))
ASG.filter_registry.register('offhour', OffHour)
ASG.filter_registry.register('onhour', OnHour)
ASG.filter_registry.register('tag-count', TagCountFilter)
ASG.filter_registry.register('marked-for-op', TagActionFilter)
ASG.filter_registry.register('network-location', net_filters.NetworkLocation)
class LaunchInfo(object):
permissions = ("ec2:DescribeLaunchTemplateVersions",
"autoscaling:DescribeLaunchConfigurations",)
def __init__(self, manager):
self.manager = manager
def initialize(self, asgs):
self.templates = self.get_launch_templates(asgs)
self.configs = self.get_launch_configs(asgs)
return self
def get_launch_templates(self, asgs):
tmpl_mgr = self.manager.get_resource_manager('launch-template-version')
# template ids include version identifiers
template_ids = list(tmpl_mgr.get_asg_templates(asgs))
if not template_ids:
return {}
return {
(t['LaunchTemplateId'],
str(t.get('c7n:VersionAlias', t['VersionNumber']))): t['LaunchTemplateData']
for t in tmpl_mgr.get_resources(template_ids)}
def get_launch_configs(self, asgs):
"""Return a mapping of launch configs for the given set of asgs"""
config_names = set()
for a in asgs:
if 'LaunchConfigurationName' not in a:
continue
config_names.add(a['LaunchConfigurationName'])
if not config_names:
return {}
lc_resources = self.manager.get_resource_manager('launch-config')
if len(config_names) < 5:
configs = lc_resources.get_resources(list(config_names))
else:
configs = lc_resources.resources()
return {
cfg['LaunchConfigurationName']: cfg for cfg in configs
if cfg['LaunchConfigurationName'] in config_names}
def get_launch_id(self, asg):
lid = asg.get('LaunchConfigurationName')
if lid is not None:
# We've noticed trailing white space allowed in some asgs
return lid.strip()
lid = asg.get('LaunchTemplate')
if lid is not None:
return (lid['LaunchTemplateId'], lid['Version'])
# we've noticed some corner cases where the asg name is the lc name, but not
# explicitly specified as launchconfiguration attribute.
lid = asg['AutoScalingGroupName']
return lid
def get(self, asg):
lid = self.get_launch_id(asg)
if isinstance(lid, tuple):
return self.templates.get(lid)
else:
return self.configs.get(lid)
def items(self):
return itertools.chain(*(
self.configs.items(), self.templates.items()))
def get_image_ids(self):
image_ids = {}
for cid, c in self.items():
if c.get('ImageId'):
image_ids.setdefault(c['ImageId'], []).append(cid)
return image_ids
def get_image_map(self):
# The describe_images api historically would return errors
# on an unknown ami in the set of images ids passed in.
# It now just silently drops those items, which is actually
# ideally for our use case.
#
# We used to do some balancing of picking up our asgs using
# the resource manager abstraction to take advantage of
# resource caching, but then we needed to do separate api
# calls to intersect with third party amis. Given the new
# describe behavior, we'll just do the api call to fetch the
# amis, it doesn't seem to have any upper bound on number of
# ImageIds to pass (Tested with 1k+ ImageIds)
#
# Explicitly use a describe source. Can't use a config source
# since it won't have state for third party ami, we auto
# propagate source normally. Can't use a cache either as their
# not in the account.
return {i['ImageId']: i for i in
self.manager.get_resource_manager(
'ami').get_source('describe').get_resources(
list(self.get_image_ids()), cache=False)}
def get_security_group_ids(self):
# return set of security group ids for given asg
sg_ids = set()
for k, v in self.items():
sg_ids.update(v.get('SecurityGroupIds', ()))
sg_ids.update(v.get('SecurityGroups', ()))
return sg_ids
@ASG.filter_registry.register('security-group')
class SecurityGroupFilter(net_filters.SecurityGroupFilter):
RelatedIdsExpression = ""
permissions = ('ec2:DescribeSecurityGroups',) + LaunchInfo.permissions
def get_related_ids(self, asgs):
return self.launch_info.get_security_group_ids()
def process(self, asgs, event=None):
self.launch_info = LaunchInfo(self.manager).initialize(asgs)
return super(SecurityGroupFilter, self).process(asgs, event)
@ASG.filter_registry.register('subnet')
class SubnetFilter(net_filters.SubnetFilter):
RelatedIdsExpression = ""
def get_related_ids(self, asgs):
subnet_ids = set()
for asg in asgs:
subnet_ids.update(
[sid.strip() for sid in asg.get('VPCZoneIdentifier', '').split(',')])
return subnet_ids
@ASG.filter_registry.register('launch-config')
class LaunchConfigFilter(ValueFilter):
"""Filter asg by launch config attributes.
This will also filter to launch template data in addition
to launch configurations.
:example:
.. code-block:: yaml
policies:
- name: launch-configs-with-public-address
resource: asg
filters:
- type: launch-config
key: AssociatePublicIpAddress
value: true
"""
schema = type_schema(
'launch-config', rinherit=ValueFilter.schema)
schema_alias = False
permissions = ("autoscaling:DescribeLaunchConfigurations",)
def process(self, asgs, event=None):
self.launch_info = LaunchInfo(self.manager).initialize(asgs)
return super(LaunchConfigFilter, self).process(asgs, event)
def __call__(self, asg):
return self.match(self.launch_info.get(asg))
class ConfigValidFilter(Filter):
def get_permissions(self):
return list(itertools.chain(*[
self.manager.get_resource_manager(m).get_permissions()
for m in ('subnet', 'security-group', 'key-pair', 'elb',
'app-elb-target-group', 'ebs-snapshot', 'ami')]))
def validate(self):
if self.manager.data.get('mode'):
raise PolicyValidationError(
"invalid-config makes too many queries to be run in lambda")
return self
def initialize(self, asgs):
self.launch_info = LaunchInfo(self.manager).initialize(asgs)
# pylint: disable=attribute-defined-outside-init
self.subnets = self.get_subnets()
self.security_groups = self.get_security_groups()
self.key_pairs = self.get_key_pairs()
self.elbs = self.get_elbs()
self.appelb_target_groups = self.get_appelb_target_groups()
self.snapshots = self.get_snapshots()
self.images, self.image_snaps = self.get_images()
def get_subnets(self):
manager = self.manager.get_resource_manager('subnet')
return set([s['SubnetId'] for s in manager.resources()])
def get_security_groups(self):
manager = self.manager.get_resource_manager('security-group')
return set([s['GroupId'] for s in manager.resources()])
def get_key_pairs(self):
manager = self.manager.get_resource_manager('key-pair')
return set([k['KeyName'] for k in manager.resources()])
def get_elbs(self):
manager = self.manager.get_resource_manager('elb')
return set([e['LoadBalancerName'] for e in manager.resources()])
def get_appelb_target_groups(self):
manager = self.manager.get_resource_manager('app-elb-target-group')
return set([a['TargetGroupArn'] for a in manager.resources()])
def get_images(self):
images = self.launch_info.get_image_map()
image_snaps = set()
for a in images.values():
# Capture any snapshots, images strongly reference their
# snapshots, and some of these will be third party in the
# case of a third party image.
for bd in a.get('BlockDeviceMappings', ()):
if 'Ebs' not in bd or 'SnapshotId' not in bd['Ebs']:
continue
image_snaps.add(bd['Ebs']['SnapshotId'].strip())
return set(images), image_snaps
def get_snapshots(self):
snaps = set()
for cid, cfg in self.launch_info.items():
for bd in cfg.get('BlockDeviceMappings', ()):
if 'Ebs' not in bd or 'SnapshotId' not in bd['Ebs']:
continue
snaps.add(bd['Ebs']['SnapshotId'].strip())
manager = self.manager.get_resource_manager('ebs-snapshot')
return set([
s['SnapshotId'] for s in manager.get_resources(
list(snaps), cache=False)])
def process(self, asgs, event=None):
self.initialize(asgs)
return super(ConfigValidFilter, self).process(asgs, event)
def get_asg_errors(self, asg):
errors = []
subnets = asg.get('VPCZoneIdentifier', '').split(',')
for subnet in subnets:
subnet = subnet.strip()
if subnet not in self.subnets:
errors.append(('invalid-subnet', subnet))
for elb in asg['LoadBalancerNames']:
elb = elb.strip()
if elb not in self.elbs:
errors.append(('invalid-elb', elb))
for appelb_target in asg.get('TargetGroupARNs', []):
appelb_target = appelb_target.strip()
if appelb_target not in self.appelb_target_groups:
errors.append(('invalid-appelb-target-group', appelb_target))
cfg_id = self.launch_info.get_launch_id(asg)
cfg = self.launch_info.get(asg)
if cfg is None:
errors.append(('invalid-config', cfg_id))
self.log.debug(
"asg:%s no launch config or template found" % asg['AutoScalingGroupName'])
asg['Invalid'] = errors
return True
for sg in itertools.chain(*(
cfg.get('SecurityGroups', ()), cfg.get('SecurityGroupIds', ()))):
sg = sg.strip()
if sg not in self.security_groups:
errors.append(('invalid-security-group', sg))
if cfg.get('KeyName') and cfg['KeyName'].strip() not in self.key_pairs:
errors.append(('invalid-key-pair', cfg['KeyName']))
if cfg.get('ImageId') and cfg['ImageId'].strip() not in self.images:
errors.append(('invalid-image', cfg['ImageId']))
for bd in cfg.get('BlockDeviceMappings', ()):
if 'Ebs' not in bd or 'SnapshotId' not in bd['Ebs']:
continue
snapshot_id = bd['Ebs']['SnapshotId'].strip()
if snapshot_id in self.image_snaps:
continue
if snapshot_id not in self.snapshots:
errors.append(('invalid-snapshot', bd['Ebs']['SnapshotId']))
return errors
@ASG.filter_registry.register('valid')
class ValidConfigFilter(ConfigValidFilter):
"""Filters autoscale groups to find those that are structurally valid.
This operates as the inverse of the invalid filter for multi-step
workflows.
See details on the invalid filter for a list of checks made.
:example:
.. code-block:: yaml
policies:
- name: asg-valid-config
resource: asg
filters:
- valid
"""
schema = type_schema('valid')
def __call__(self, asg):
errors = self.get_asg_errors(asg)
return not bool(errors)
@ASG.filter_registry.register('invalid')
class InvalidConfigFilter(ConfigValidFilter):
"""Filter autoscale groups to find those that are structurally invalid.
Structurally invalid means that the auto scale group will not be able
to launch an instance succesfully as the configuration has
- invalid subnets
- invalid security groups
- invalid key pair name
- invalid launch config volume snapshots
- invalid amis
- invalid health check elb (slower)
Internally this tries to reuse other resource managers for better
cache utilization.
:example:
.. code-block:: yaml
policies:
- name: asg-invalid-config
resource: asg
filters:
- invalid
"""
schema = type_schema('invalid')
def __call__(self, asg):
errors = self.get_asg_errors(asg)
if errors:
asg['Invalid'] = errors
return True
@ASG.filter_registry.register('not-encrypted')
class NotEncryptedFilter(Filter):
"""Check if an ASG is configured to have unencrypted volumes.
Checks both the ami snapshots and the launch configuration.
:example:
.. code-block:: yaml
policies:
- name: asg-unencrypted
resource: asg
filters:
- type: not-encrypted
exclude_image: true
"""
schema = type_schema('not-encrypted', exclude_image={'type': 'boolean'})
permissions = (
'ec2:DescribeImages',
'ec2:DescribeSnapshots',
'autoscaling:DescribeLaunchConfigurations')
images = unencrypted_configs = unencrypted_images = None
# TODO: resource-manager, notfound err mgr
def process(self, asgs, event=None):
self.launch_info = LaunchInfo(self.manager).initialize(asgs)
self.images = self.launch_info.get_image_map()
if not self.data.get('exclude_image'):
self.unencrypted_images = self.get_unencrypted_images()
self.unencrypted_launch = self.get_unencrypted_configs()
return super(NotEncryptedFilter, self).process(asgs, event)
def __call__(self, asg):
launch = self.launch_info.get(asg)
if not launch:
self.log.warning(
"ASG %s instances: %d has missing config or template",
asg['AutoScalingGroupName'], len(asg['Instances']))
return False
launch_id = self.launch_info.get_launch_id(asg)
unencrypted = []
if not self.data.get('exclude_image'):
if launch['ImageId'] in self.unencrypted_images:
unencrypted.append('Image')
if launch_id in self.unencrypted_launch:
unencrypted.append('LaunchConfig')
if unencrypted:
asg['Unencrypted'] = unencrypted
return bool(unencrypted)
def get_unencrypted_images(self):
"""retrieve images which have unencrypted snapshots referenced."""
unencrypted_images = set()
for i in self.images.values():
for bd in i['BlockDeviceMappings']:
if 'Ebs' in bd and not bd['Ebs'].get('Encrypted'):
unencrypted_images.add(i['ImageId'])
break
return unencrypted_images
def get_unencrypted_configs(self):
"""retrieve configs that have unencrypted ebs voluems referenced."""
unencrypted_configs = set()
snaps = {}
for cid, c in self.launch_info.items():
image = self.images.get(c.get('ImageId', ''))
# image deregistered/unavailable or exclude_image set
if image is not None:
image_block_devs = {
bd['DeviceName'] for bd in
image['BlockDeviceMappings'] if 'Ebs' in bd}
else:
image_block_devs = set()
for bd in c.get('BlockDeviceMappings', ()):
if 'Ebs' not in bd:
continue
# Launch configs can shadow image devices, images have
# precedence.
if bd['DeviceName'] in image_block_devs:
continue
if 'SnapshotId' in bd['Ebs']:
snaps.setdefault(
bd['Ebs']['SnapshotId'].strip(), []).append(cid)
elif not bd['Ebs'].get('Encrypted'):
unencrypted_configs.add(cid)
if not snaps:
return unencrypted_configs
for s in self.get_snapshots(list(snaps.keys())):
if not s.get('Encrypted'):
unencrypted_configs.update(snaps[s['SnapshotId']])
return unencrypted_configs
def get_snapshots(self, snap_ids):
"""get snapshots corresponding to id, but tolerant of invalid id's."""
return self.manager.get_resource_manager('ebs-snapshot').get_resources(
snap_ids, cache=False)
@ASG.filter_registry.register('image-age')
class ImageAgeFilter(AgeFilter):
"""Filter asg by image age (in days).
:example:
.. code-block:: yaml
policies:
- name: asg-older-image
resource: asg
filters:
- type: image-age
days: 90
op: ge
"""
permissions = (
"ec2:DescribeImages",
"autoscaling:DescribeLaunchConfigurations")
date_attribute = "CreationDate"
schema = type_schema(
'image-age',
op={'$ref': '#/definitions/filters_common/comparison_operators'},
days={'type': 'number'})
def process(self, asgs, event=None):
self.launch_info = LaunchInfo(self.manager).initialize(asgs)
self.images = self.launch_info.get_image_map()
return super(ImageAgeFilter, self).process(asgs, event)
def get_resource_date(self, asg):
cfg = self.launch_info.get(asg)
ami = self.images.get(cfg.get('ImageId'), {})
return parse(ami.get(
self.date_attribute, "2000-01-01T01:01:01.000Z"))
@ASG.filter_registry.register('image')
class ImageFilter(ValueFilter):
"""Filter asg by image
:example:
.. code-block:: yaml
policies:
- name: non-windows-asg
resource: asg
filters:
- type: image
key: Platform
value: Windows
op: ne
"""
permissions = (
"ec2:DescribeImages",
"autoscaling:DescribeLaunchConfigurations")
schema = type_schema('image', rinherit=ValueFilter.schema)
schema_alias = True
def process(self, asgs, event=None):
self.launch_info = LaunchInfo(self.manager).initialize(asgs)
self.images = self.launch_info.get_image_map()
return super(ImageFilter, self).process(asgs, event)
def __call__(self, i):
image = self.launch_info.get(i).get('ImageId', None)
# Finally, if we have no image...
if not image:
self.log.warning(
"Could not locate image for instance:%s ami:%s" % (
i['InstanceId'], i["ImageId"]))
# Match instead on empty skeleton?
return False
return self.match(image)
@ASG.filter_registry.register('vpc-id')
class VpcIdFilter(ValueFilter):
"""Filters ASG based on the VpcId
This filter is available as a ValueFilter as the vpc-id is not natively
associated to the results from describing the autoscaling groups.
:example:
.. code-block:: yaml
policies:
- name: asg-vpc-xyz
resource: asg
filters:
- type: vpc-id
value: vpc-12ab34cd
"""
schema = type_schema(
'vpc-id', rinherit=ValueFilter.schema)
schema['properties'].pop('key')
schema_alias = False
permissions = ('ec2:DescribeSubnets',)
# TODO: annotation
def __init__(self, data, manager=None):
super(VpcIdFilter, self).__init__(data, manager)
self.data['key'] = 'VpcId'
def process(self, asgs, event=None):
subnets = {}
for a in asgs:
subnet_ids = a.get('VPCZoneIdentifier', '')
if not subnet_ids:
continue
subnets.setdefault(subnet_ids.split(',')[0], []).append(a)
subnet_manager = self.manager.get_resource_manager('subnet')
# Invalid subnets on asgs happen, so query all
all_subnets = {s['SubnetId']: s for s in subnet_manager.resources()}
for s, s_asgs in subnets.items():
if s not in all_subnets:
self.log.warning(
"invalid subnet %s for asgs: %s",
s, [a['AutoScalingGroupName'] for a in s_asgs])
continue
for a in s_asgs:
a['VpcId'] = all_subnets[s]['VpcId']
return super(VpcIdFilter, self).process(asgs)
@ASG.filter_registry.register('progagated-tags') # compatibility
@ASG.filter_registry.register('propagated-tags')
class PropagatedTagFilter(Filter):
"""Filter ASG based on propagated tags
This filter is designed to find all autoscaling groups that have a list
of tag keys (provided) that are set to propagate to new instances. Using
this will allow for easy validation of asg tag sets are in place across an
account for compliance.
:example:
.. code-block:: yaml
policies:
- name: asg-non-propagated-tags
resource: asg
filters:
- type: propagated-tags
keys: ["ABC", "BCD"]
match: false
propagate: true
"""
schema = type_schema(
'progagated-tags',
aliases=('propagated-tags',),
keys={'type': 'array', 'items': {'type': 'string'}},
match={'type': 'boolean'},
propagate={'type': 'boolean'})
permissions = (
"autoscaling:DescribeLaunchConfigurations",
"autoscaling:DescribeAutoScalingGroups")
def process(self, asgs, event=None):
keys = self.data.get('keys', [])
match = self.data.get('match', True)
results = []
for asg in asgs:
if self.data.get('propagate', True):
tags = [t['Key'] for t in asg.get('Tags', []) if t[
'Key'] in keys and t['PropagateAtLaunch']]
if match and all(k in tags for k in keys):
results.append(asg)
if not match and not all(k in tags for k in keys):
results.append(asg)
else:
tags = [t['Key'] for t in asg.get('Tags', []) if t[
'Key'] in keys and not t['PropagateAtLaunch']]
if match and all(k in tags for k in keys):
results.append(asg)
if not match and not all(k in tags for k in keys):
results.append(asg)
return results
@ASG.action_registry.register('tag-trim')
class GroupTagTrim(TagTrim):
"""Action to trim the number of tags to avoid hitting tag limits
:example:
.. code-block:: yaml
policies:
- name: asg-tag-trim
resource: asg
filters:
- type: tag-count
count: 10
actions:
- type: tag-trim
space: 1
preserve:
- OwnerName
- OwnerContact
"""
max_tag_count = 10
permissions = ('autoscaling:DeleteTags',)
def process_tag_removal(self, client, resource, candidates):
tags = []
for t in candidates:
tags.append(
dict(Key=t, ResourceType='auto-scaling-group',
ResourceId=resource['AutoScalingGroupName']))
client.delete_tags(Tags=tags)
@ASG.filter_registry.register('capacity-delta')
class CapacityDelta(Filter):
"""Filter returns ASG that have less instances than desired or required
:example:
.. code-block:: yaml
policies:
- name: asg-capacity-delta
resource: asg
filters:
- capacity-delta
"""
schema = type_schema('capacity-delta')
def process(self, asgs, event=None):
return [
a for a in asgs if len(
a['Instances']) < a['DesiredCapacity'] or len(
a['Instances']) < a['MinSize']]
@ASG.filter_registry.register('user-data')
class UserDataFilter(ValueFilter):
"""Filter on ASG's whose launch configs have matching userdata.
Note: It is highly recommended to use regexes with the ?sm flags, since Custodian
uses re.match() and userdata spans multiple lines.
:example:
.. code-block:: yaml
policies:
- name: lc_userdata
resource: asg
filters:
- type: user-data
op: regex
value: (?smi).*password=
actions:
- delete
"""
schema = type_schema('user-data', rinherit=ValueFilter.schema)
schema_alias = False
batch_size = 50
annotation = 'c7n:user-data'
def __init__(self, data, manager):
super(UserDataFilter, self).__init__(data, manager)
self.data['key'] = '"c7n:user-data"'
def get_permissions(self):
return self.manager.get_resource_manager('asg').get_permissions()
def process(self, asgs, event=None):
'''Get list of autoscaling groups whose launch configs match the
user-data filter.
:return: List of ASG's with matching launch configs
'''
self.data['key'] = '"c7n:user-data"'
launch_info = LaunchInfo(self.manager).initialize(asgs)
results = []
for asg in asgs:
launch_config = launch_info.get(asg)
if self.annotation not in launch_config:
if not launch_config.get('UserData'):
asg[self.annotation] = None
else:
asg[self.annotation] = deserialize_user_data(
launch_config['UserData'])
if self.match(asg):
results.append(asg)
return results
@ASG.action_registry.register('resize')
class Resize(Action):
"""Action to resize the min/max/desired instances in an ASG
There are several ways to use this action:
1. set min/desired to current running instances
.. code-block:: yaml
policies:
- name: asg-resize
resource: asg
filters:
- capacity-delta
actions:
- type: resize
desired-size: "current"
2. apply a fixed resize of min, max or desired, optionally saving the
previous values to a named tag (for restoring later):
.. code-block:: yaml
policies:
- name: offhours-asg-off
resource: asg
filters:
- type: offhour
offhour: 19
default_tz: bst
actions:
- type: resize
min-size: 0
desired-size: 0
save-options-tag: OffHoursPrevious
3. restore previous values for min/max/desired from a tag:
.. code-block:: yaml
policies:
- name: offhours-asg-on
resource: asg
filters:
- type: onhour
onhour: 8
default_tz: bst
actions:
- type: resize
restore-options-tag: OffHoursPrevious
"""
schema = type_schema(
'resize',
**{
'min-size': {'type': 'integer', 'minimum': 0},
'max-size': {'type': 'integer', 'minimum': 0},
'desired-size': {
"anyOf": [
{'enum': ["current"]},
{'type': 'integer', 'minimum': 0}
]
},
# support previous key name with underscore
'desired_size': {
"anyOf": [
{'enum': ["current"]},
{'type': 'integer', 'minimum': 0}
]
},
'save-options-tag': {'type': 'string'},
'restore-options-tag': {'type': 'string'},
}
)
permissions = (
'autoscaling:UpdateAutoScalingGroup',
'autoscaling:CreateOrUpdateTags'
)
def process(self, asgs):
# ASG parameters to save to/restore from a tag
asg_params = ['MinSize', 'MaxSize', 'DesiredCapacity']
# support previous param desired_size when desired-size is not present
if 'desired_size' in self.data and 'desired-size' not in self.data:
self.data['desired-size'] = self.data['desired_size']
client = local_session(self.manager.session_factory).client(
'autoscaling')
for a in asgs:
tag_map = {t['Key']: t['Value'] for t in a.get('Tags', [])}
update = {}
current_size = len(a['Instances'])
if 'restore-options-tag' in self.data:
# we want to restore all ASG size params from saved data
self.log.debug(
'Want to restore ASG %s size from tag %s' %
(a['AutoScalingGroupName'], self.data['restore-options-tag']))
if self.data['restore-options-tag'] in tag_map:
for field in tag_map[self.data['restore-options-tag']].split(';'):
(param, value) = field.split('=')
if param in asg_params:
update[param] = int(value)
else:
# we want to resize, parse provided params
if 'min-size' in self.data:
update['MinSize'] = self.data['min-size']
if 'max-size' in self.data:
update['MaxSize'] = self.data['max-size']
if 'desired-size' in self.data:
if self.data['desired-size'] == 'current':
update['DesiredCapacity'] = min(current_size, a['DesiredCapacity'])
if 'MinSize' not in update:
# unless we were given a new value for min_size then
# ensure it is at least as low as current_size
update['MinSize'] = min(current_size, a['MinSize'])
elif type(self.data['desired-size']) == int:
update['DesiredCapacity'] = self.data['desired-size']
if update:
self.log.debug('ASG %s size: current=%d, min=%d, max=%d, desired=%d'
% (a['AutoScalingGroupName'], current_size, a['MinSize'],
a['MaxSize'], a['DesiredCapacity']))
if 'save-options-tag' in self.data:
# save existing ASG params to a tag before changing them
self.log.debug('Saving ASG %s size to tag %s' %
(a['AutoScalingGroupName'], self.data['save-options-tag']))
tags = [dict(
Key=self.data['save-options-tag'],
PropagateAtLaunch=False,
Value=';'.join({'%s=%d' % (param, a[param]) for param in asg_params}),
ResourceId=a['AutoScalingGroupName'],
ResourceType='auto-scaling-group',
)]
self.manager.retry(client.create_or_update_tags, Tags=tags)
self.log.debug('Resizing ASG %s with %s' % (a['AutoScalingGroupName'],
str(update)))
self.manager.retry(
client.update_auto_scaling_group,
AutoScalingGroupName=a['AutoScalingGroupName'],
**update)
else:
self.log.debug('nothing to resize')
@ASG.action_registry.register('remove-tag')
@ASG.action_registry.register('untag') # compatibility
@ASG.action_registry.register('unmark') # compatibility
class RemoveTag(Action):
"""Action to remove tag/tags from an ASG