-
Notifications
You must be signed in to change notification settings - Fork 0
/
cf-hitman-batch.yml
467 lines (426 loc) · 14.4 KB
/
cf-hitman-batch.yml
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
AWSTemplateFormatVersion: '2010-09-09'
Description: Hitman Batch
Metadata:
AWS::CloudFormation::Interface:
ParameterGroups:
- Label:
default: 'ComputeEnv network'
Parameters: ['ComputeEnvVPC', 'ComputeEnvSubnets']
- Label:
default: 'ComputeEnv Cpu'
Parameters: ['ComputeEnvMinCpu', 'ComputeEnvDesiredCpu', 'ComputeEnvMaxCpu']
- Label:
default: 'Hitman Role on Spoke accounts'
Parameters: ['NukeRoleToAssume', 'NukeRoleExternalId']
- Label:
default: 'Hitman Role on Organizations account'
Parameters: ['HitmanOrganizationsAccount', 'HitmanOrganizationsRole']
Parameters:
TagBlock:
Description: Applicative block tag
Type: String
TagApp:
Description: Application tag
Type: String
TagOrg:
Description: Organization tag
Type: String
HitmanFrequency:
Description: define execution frequency
Type: String
Default: "cron(30 2 ? * SAT *)"
ComputeEnvVPC:
Description: compute envs VPC location
Type: AWS::EC2::VPC::Id
ComputeEnvSubnets:
Description: compute envs subnets location
Type: List<AWS::EC2::Subnet::Id>
ComputeEnvMinCpu:
Description: compute env min number of CPUs
Type: Number
Default: 0
ComputeEnvDesiredCpu:
Description: compute env desired number of CPUs
Type: Number
Default: 0
ComputeEnvMaxCpu:
Description: compute env max number of CPUs
Type: Number
Default: 4
JobDefinitionMemory:
Description: job definition memory size
Type: Number
Default: 1000
NukeEcrImage:
Description: ECR image to use
Type: String
NukeRoleToAssume:
Description: IAM role to assume on the account to Nuke
Type: String
Default: hitman-nuke-role
NukeRoleExternalId:
Description: Hitman Role External ID
Type: String
HitmanOrganizationsAccount:
Description: Id of the account hosting AWS Organizations
Type: String
HitmanOrganizationsRole:
Description: IAM role to assume on the Organizations account to Hitman
Type: String
Default: hitman-organizations-role
HitmanConfigBucket:
Description: S3 bucket with Hitman configuration
Type: String
Resources:
SecurityGroupForInstances:
Type: AWS::EC2::SecurityGroup
Properties:
GroupName: !Sub '${TagApp}-instances'
GroupDescription: Security group for instances
VpcId: !Ref ComputeEnvVPC
Tags:
- Key: Block
Value: !Ref TagBlock
- Key: Org
Value: !Ref TagOrg
- Key: App
Value: !Ref TagApp
SpotFleetRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service:
- "spotfleet.amazonaws.com"
Action:
- "sts:AssumeRole"
ManagedPolicyArns:
- "arn:aws:iam::aws:policy/service-role/AmazonEC2SpotFleetRole"
- "arn:aws:iam::aws:policy/service-role/AmazonEC2SpotFleetTaggingRole"
Tags:
- Key: Block
Value: !Ref TagBlock
- Key: App
Value: !Ref TagApp
- Key: Org
Value: !Ref TagOrg
HitmanComputeEnv:
Type: "AWS::Batch::ComputeEnvironment"
Properties:
Type: MANAGED
ServiceRole: !Ref ComputeEnvironmentRole
ComputeResources:
MinvCpus: !Ref ComputeEnvMinCpu
MaxvCpus: !Ref ComputeEnvMaxCpu
DesiredvCpus: !Ref ComputeEnvDesiredCpu
SecurityGroupIds:
- !Ref SecurityGroupForInstances
Subnets: !Ref ComputeEnvSubnets
Type: SPOT
BidPercentage: 50
SpotIamFleetRole: !Ref SpotFleetRole
InstanceRole: !Ref EcsInstanceProfile
InstanceTypes:
- c3
Tags: {Name: !Ref TagApp, Block: !Ref TagBlock, App: !Ref TagApp, Org: !Ref TagOrg}
State: ENABLED
ComputeEnvironmentRole:
Type: AWS::IAM::Role
Properties:
Path: "/"
RoleName: !Sub "${TagApp}-compute-environment"
AssumeRolePolicyDocument:
Statement:
- Effect: Allow
Principal:
Service:
- batch.amazonaws.com
Action:
- sts:AssumeRole
ManagedPolicyArns:
- "arn:aws:iam::aws:policy/service-role/AWSBatchServiceRole"
Tags:
- Key: Block
Value: !Ref TagBlock
- Key: App
Value: !Ref TagApp
- Key: Org
Value: !Ref TagOrg
NukeJobQueue:
Type: "AWS::Batch::JobQueue"
Properties:
ComputeEnvironmentOrder:
- Order: 1
ComputeEnvironment: !Ref HitmanComputeEnv
Priority: 1
JobQueueName: !Sub "${TagApp}-queue"
EcsInstanceRole:
Type: AWS::IAM::Role
Properties:
Path: "/"
RoleName: !Sub "${TagApp}-ecsinstance"
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AmazonEC2ContainerServiceforEC2Role
AssumeRolePolicyDocument:
Statement:
- Effect: Allow
Principal:
Service:
- ec2.amazonaws.com
Action:
- sts:AssumeRole
Tags:
- Key: Block
Value: !Ref TagBlock
- Key: App
Value: !Ref TagApp
- Key: Org
Value: !Ref TagOrg
EcsInstanceProfile:
Type: "AWS::IAM::InstanceProfile"
Properties:
Path: "/"
Roles:
- !Ref EcsInstanceRole
HitmanJobDefinition:
Type: "AWS::Batch::JobDefinition"
Properties:
JobDefinitionName: !Sub "${TagApp}-job-definition"
Type: container
Parameters: {}
ContainerProperties:
Memory: !Ref JobDefinitionMemory
Privileged: false
JobRoleArn: !Ref HitmanJobRole
ReadonlyRootFilesystem: false
Vcpus: 1
Image: !Ref NukeEcrImage
Environment:
- Name: CONF_BUCKET
Value: !Ref HitmanConfigBucket
- Name: NUKE_ROLE_TO_ASSUME
Value: !Ref NukeRoleToAssume
- Name: NUKE_ROLE_EXTERNALID
Value: !Ref NukeRoleExternalId
RetryStrategy:
Attempts: 1
HitmanJobRole:
Type: AWS::IAM::Role
Properties:
Path: "/"
RoleName: !Sub "${TagApp}-jobrole"
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy
AssumeRolePolicyDocument:
Statement:
- Effect: Allow
Principal:
Service:
- ecs-tasks.amazonaws.com
Action:
- sts:AssumeRole
Policies:
- PolicyName: accessConfigBucketPolicy
PolicyDocument:
Statement:
- Effect: "Allow"
Action:
- "s3:ListBucket"
- "s3:GetObject"
Resource:
- !Sub "arn:aws:s3:::${HitmanConfigBucket}"
- !Sub "arn:aws:s3:::${HitmanConfigBucket}/*"
- PolicyName: assumeRolePolicy
PolicyDocument:
Statement:
- Effect: "Allow"
Action:
- "sts:AssumeRole"
Resource:
- !Sub "arn:aws:iam::*:role/${NukeRoleToAssume}"
Tags:
- Key: Block
Value: !Ref TagBlock
- Key: App
Value: !Ref TagApp
- Key: Org
Value: !Ref TagOrg
HitmanScheduledRule:
Type: AWS::Events::Rule
Properties:
Description: "ScheduledRule"
ScheduleExpression: !Ref HitmanFrequency
State: ENABLED
Targets:
- Id: "HitmanSaturday"
Arn: !GetAtt NukeJobLauncherLambda.Arn
Input : '{ "mode": "list" }'
PermissionForRuleToInvokeLambda:
Type: "AWS::Lambda::Permission"
Properties:
FunctionName: !Ref NukeJobLauncherLambda
Action: "lambda:InvokeFunction"
Principal: "events.amazonaws.com"
SourceArn: !GetAtt HitmanScheduledRule.Arn
NukeJobLauncherLambdaRole:
Type: AWS::IAM::Role
Properties:
RoleName: !Sub "${TagApp}-lambda-invoke"
AssumeRolePolicyDocument:
Statement:
- Effect: Allow
Principal:
Service: "lambda.amazonaws.com"
Action:
- sts:AssumeRole
Path: "/"
Policies:
- PolicyName: accessConfigBucketPolicy
PolicyDocument:
Statement:
- Effect: "Allow"
Action:
- "s3:ListBucket"
- "s3:GetObject"
Resource:
- !Sub "arn:aws:s3:::${HitmanConfigBucket}"
- !Sub "arn:aws:s3:::${HitmanConfigBucket}/*"
- PolicyName: launch-jobs-allow
PolicyDocument:
Statement:
- Effect: Allow
Action:
- logs:PutLogEvents
- logs:CreateLogGroup
- logs:CreateLogStream
Resource:
- "arn:aws:logs:*:*:*"
- Effect: Allow
Action:
- batch:DescribeJobs
- batch:ListJobs
- batch:SubmitJob
Resource:
- "*"
- PolicyName: assumeRoleOrganizationsPolicy
PolicyDocument:
Statement:
- Effect: "Allow"
Action:
- "sts:AssumeRole"
Resource:
- !Sub "arn:aws:iam::*:role/${HitmanOrganizationsRole}"
Tags:
- Key: Block
Value: !Ref TagBlock
- Key: App
Value: !Ref TagApp
- Key: Org
Value: !Ref TagOrg
HitmanLambdaLogGroup:
Type: "AWS::Logs::LogGroup"
Properties:
LogGroupName: !Sub '/aws/lambda/${NukeJobLauncherLambda}'
RetentionInDays: 30
NukeJobLauncherLambda:
Type: "AWS::Lambda::Function"
Properties:
FunctionName: !Sub '${TagApp}-launcher'
Description: "Launch aws-nuke job"
Handler: "index.lambda_handler"
Code:
ZipFile: |
import os
import json
import boto3
def lambda_handler(event, context):
print("Event received : " + json.dumps(event, indent=2))
configMode = event['mode']
if configMode == "list":
CONFIGFILE_BUCKET = os.environ['CONFIGFILE_BUCKET']
CONFIGFILE_NAME = os.environ['CONFIGFILE_NAME']
accountIds = getAccountIdsListS3(CONFIGFILE_BUCKET, CONFIGFILE_NAME)
elif configMode == "ou":
ouId = event['ouId']
ORGANIZATIONS_ROLE = os.environ['ORGANIZATIONS_ROLE']
ORGANIZATIONS_ACCOUNT = os.environ['ORGANIZATIONS_ACCOUNT']
session = get_session(role=ORGANIZATIONS_ROLE, account=ORGANIZATIONS_ACCOUNT, session_name='hitman_lambda')
accountIds = getActiveAccountIdsListOu(session, ouId)
elif configMode == "standalone":
accountIds = [event['accountId']]
else:
print("No mode detected")
accountIds = []
print("%s accounts to Nuke : %s" % (len(accountIds), accountIds))
client = boto3.client('batch')
for accountId in accountIds:
response = client.submit_job(
jobName=os.environ['JOBNAME'] + "-" + accountId,
jobQueue=os.environ['JOBQUEUE'],
jobDefinition=os.environ['JOBDEFINITION'],
containerOverrides={
'environment': [
{
'name': 'ACCOUNT_TO_NUKE',
'value': accountId
},
]
}
)
print("Job %s launched with jobId %s to nuke account %s." % (response['jobName'], response['jobId'], accountId))
def getAccountIdsListS3(configFileBucket, configFileName):
tempFile = '/tmp/accounts.list'
accountList=[]
s3client = boto3.client('s3')
s3client.download_file(configFileBucket, configFileName, tempFile)
for line in open(tempFile):
li=line.strip()
if not li.startswith("#"):
accountList.append(line.rstrip())
return accountList
def getActiveAccountIdsListOu(session, OrganizationUnit):
client = session.client('organizations')
response = client.list_accounts_for_parent(ParentId=OrganizationUnit)
accountsFromOu = response.get('Accounts', [])
while(response.get('NextToken') is not None):
response = client.list_accounts_for_parent(ParentId=OrganizationUnit, NextToken=response['NextToken'])
accountsFromOu.extend(response.get('Accounts', []))
activeAccountIds = []
activeAccountIds = [account['Id'] for account in accountsFromOu if account['Status'] == "ACTIVE"]
return activeAccountIds
def get_session(role=None, account=None, region=None, session_name='my_session'):
# If the role is given : assumes a role and returns boto3 session
# otherwise : returns a regular session with the current IAM user/role
if role:
client = boto3.client('sts')
role_arn = 'arn:aws:iam::' + account + ':role/' + role
response = client.assume_role(RoleArn=role_arn, RoleSessionName=session_name)
session = boto3.Session(
aws_access_key_id=response['Credentials']['AccessKeyId'],
aws_secret_access_key=response['Credentials']['SecretAccessKey'],
aws_session_token=response['Credentials']['SessionToken'],
region_name=region)
return session
Environment:
Variables:
JOBNAME: "hitman-job"
JOBQUEUE: !Ref NukeJobQueue
JOBDEFINITION: !Ref HitmanJobDefinition
CONFIGFILE_BUCKET: !Ref HitmanConfigBucket
CONFIGFILE_NAME: "accounts.list"
ORGANIZATIONS_ROLE: !Ref HitmanOrganizationsRole
ORGANIZATIONS_ACCOUNT: !Ref HitmanOrganizationsAccount
MemorySize: 128
Role: !GetAtt NukeJobLauncherLambdaRole.Arn
Runtime: "python3.7"
Timeout: 60
Tags:
- Key: Block
Value: !Ref TagBlock
- Key: Org
Value: !Ref TagOrg
- Key: App
Value: !Ref TagApp