-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPassword Generator lambda.yaml
More file actions
99 lines (85 loc) · 3.39 KB
/
Password Generator lambda.yaml
File metadata and controls
99 lines (85 loc) · 3.39 KB
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
AWSTemplateFormatVersion: 2010-09-09
Parameters:
LabUserRoleName:
Type: String
Resources:
AttachPolicies:
Type: Custom::AttachPolicies
Properties:
ServiceToken: !GetAtt AttachPoliciesFunction.Arn
DeleteFunctions:
- !Ref AttachPoliciesFunction
DeleteRoles:
- !Ref AttachPoliciesRole
PolicyArns:
- arn:aws:iam::aws:policy/ReadOnlyAccess
RoleName: !Ref LabUserRoleName
AttachPoliciesFunction:
Type: AWS::Lambda::Function
Properties:
Handler: index.handler
MemorySize: 128
Timeout: 180
Role: !GetAtt AttachPoliciesRole.Arn
Runtime: python3.8
Code:
ZipFile: |
import boto3
import cfnresponse
import json
_iam = boto3.resource("iam")
_lambda = boto3.client("lambda")
def delete_resources(event):
for role_name in event.get("ResourceProperties").get("DeleteRoles"):
role = _iam.Role(name=role_name)
for role_policy in role.policies.all():
role_policy.delete()
role.delete()
for function_name in event.get("ResourceProperties").get("DeleteFunctions"):
_lambda.delete_function(FunctionName=function_name)
def handler(event, context):
try:
# Only handle 'Create' requests.
if event.get("RequestType") == "Create":
role = _iam.Role(name=event.get("ResourceProperties").get("RoleName"))
for policy_arn in event.get("ResourceProperties").get("PolicyArns"):
role.attach_policy(PolicyArn=policy_arn)
cfnresponse.send(event, context, cfnresponse.SUCCESS, {}, reason="Policies Attached")
else:
cfnresponse.send(event, context, cfnresponse.SUCCESS, {}, reason="No Action Performed")
except Exception as exception:
cfnresponse.send(event, context, cfnresponse.FAILED, {}, reason=str(exception))
finally:
delete_resources(event)
AttachPoliciesRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Action: sts:AssumeRole
Effect: Allow
Principal:
Service: lambda.amazonaws.com
Policies:
- PolicyName: AttachPolicies
PolicyDocument:
Version: 2012-10-17
Statement:
- Action:
- iam:AttachRolePolicy
Effect: Allow
Resource:
- !Sub arn:${AWS::Partition}:iam::${AWS::AccountId}:role/${LabUserRoleName}
- Action:
- iam:DeleteRole
- iam:DeleteRolePolicy
- iam:ListRolePolicies
Effect: Allow
Resource:
- !Sub arn:${AWS::Partition}:iam::${AWS::AccountId}:role/*-AttachPoliciesRole-*
- Action:
- lambda:DeleteFunction
Effect: Allow
Resource:
- !Sub arn:${AWS::Partition}:lambda:${AWS::Region}:${AWS::AccountId}:function:*-AttachPoliciesFunction-*