-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcloud9-stack.yaml
258 lines (249 loc) · 8.38 KB
/
cloud9-stack.yaml
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
Parameters:
AutomaticStopTimeMinutes:
Description: How many minutes idle before stopping Cloud9. Options, 30min, 1hr, 4hr, 1day, 1week, Never (0)
Type: Number
Default: 30
AllowedValues:
- 30
- 60
- 240
- 1440
- 10080
- 0
EC2InstanceType:
Description: EC2 instance type on which IDE runs
Type: String
Default: t2.micro
AllowedValues:
- t2.nano
- t2.micro
- t2.small
- t2.medium
- t2.large
- t2.xlarge
- t2.2xlarge
- m3.medium
- m3.large
- m3.xlarge
- m3.2xlarge
- m4.large
- m4.xlarge
- m4.2xlarge
- m4.4xlarge
- m4.10xlarge
- m4.16xlarge
- c3.large
- c3.xlarge
- c3.2xlarge
- c3.4xlarge
- c3.8xlarge
- c4.large
- c4.xlarge
- c4.2xlarge
- c4.4xlarge
- c4.8xlarge
SubnetId:
Description: The ID of a public subnet into which Cloud9 should be launched.
Type: AWS::EC2::Subnet::Id
Resources:
Cloud9:
Type: "AWS::Cloud9::EnvironmentEC2"
Properties:
Name:
Fn::Join:
- "-"
- - "Neptune-Cloud9"
- Fn::Select:
- 4
- Fn::Split:
- "-"
- Fn::Select:
- 2
- Fn::Split:
- /
- Ref: AWS::StackId
Description: Neptune Cloud9
ConnectionType: CONNECT_SSM
AutomaticStopTimeMinutes: !Ref "AutomaticStopTimeMinutes"
SubnetId: !Ref SubnetId
InstanceType: !Ref "EC2InstanceType"
DependsOn: CreateCloud9ServiceRoles
Cloud9InstanceProfile:
Type: "AWS::IAM::InstanceProfile"
Properties:
Path: "/"
Roles:
- Ref: "Cloud9InstanceNeptuneRole"
Cloud9InstanceNeptuneRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument: >
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": [
"ec2.amazonaws.com",
"cloud9.amazonaws.com"
]
},
"Action": "sts:AssumeRole"
}
]
}
ManagedPolicyArns:
- arn:aws:iam::aws:policy/AWSCloud9SSMInstanceProfile
- arn:aws:iam::aws:policy/ReadOnlyAccess
Cloud9LambdaHelperRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument: >
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": [
"lambda.amazonaws.com"
]
},
"Action": "sts:AssumeRole"
}
]
}
Policies:
- PolicyName: cloudformation
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- "cloudformation:DescribeStackResources"
- "cloudformation:ListStacks"
- "ec2:DisassociateIamInstanceProfile"
- "ec2:AssociateIamInstanceProfile"
- "ec2:DescribeIamInstanceProfileAssociations"
- "iam:PassRole"
- "iam:CreateRole"
- "iam:CreateInstanceProfile"
- "iam:AddRoleToInstanceProfile"
- "iam:CreateServiceLinkedRole"
- "iam:AttachRolePolicy"
Resource: "*"
- Effect: Allow
Action:
- "logs:CreateLogGroup"
- "logs:CreateLogStream"
- "logs:PutLogEvents"
Resource: "arn:aws:logs:*:*:*"
Cloud9HelperLambda:
Type: AWS::Lambda::Function
Properties:
Runtime: python3.9
Timeout: 15
Role: !GetAtt "Cloud9LambdaHelperRole.Arn"
Handler: index.lambda_handler
Code:
ZipFile: |
import boto3
import jmespath
import cfnresponse
import json
from botocore.exceptions import ClientError
def create_cloud9_roles(input):
if "createCloud9Roles" not in input:
print(f"createCloud9Roles not in {input}")
return
iam = boto3.client("iam")
assume_role_policy = json.dumps({
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": [
"ec2.amazonaws.com",
"cloud9.amazonaws.com"
]
},
"Action": "sts:AssumeRole"
}
]
})
try:
iam.create_role(
Path="/service-role/",
RoleName="AWSCloud9SSMAccessRole",
AssumeRolePolicyDocument=assume_role_policy
)
iam.create_instance_profile(
InstanceProfileName="AWSCloud9SSMInstanceProfile",
Path="/cloud9/"
)
iam.add_role_to_instance_profile(
InstanceProfileName="AWSCloud9SSMInstanceProfile",
RoleName="AWSCloud9SSMAccessRole"
)
iam.attach_role_policy(
RoleName="AWSCloud9SSMAccessRole",
PolicyArn="arn:aws:iam::aws:policy/AWSCloud9SSMInstanceProfile"
)
except ClientError as ex:
if ex.response['Error']['Code'] == 'EntityAlreadyExists':
print("No need to create AWSServiceRoleForAWSCloud9, it already exists")
else:
raise
try:
iam.create_service_linked_role(
AWSServiceName="cloud9.amazonaws.com",
)
except ClientError as ex:
if ex.response['Error']['Code'] == 'InvalidInput':
print("No need to create cloud9.amazonaws.com service linked role, it already exists.")
return
raise
def swap_instance_profile(input):
if "Cloud9Id" not in input:
print(f"Cloud9Id not found in {input}")
return
cfn = boto3.client('cloudformation')
ec2 = boto3.client('ec2')
stacks = [stack for page in cfn.get_paginator('list_stacks').paginate() for stack in page['StackSummaries']]
stack = next(stack for stack in stacks if input['Cloud9Id'] in stack['StackName'])
result = cfn.describe_stack_resources(StackName=stack['StackName'])
instance_id = jmespath.search("StackResources[?LogicalResourceId==`Instance`].PhysicalResourceId", result) [0]
security_group = jmespath.search("StackResources[?LogicalResourceId==`InstanceSecurityGroup`].PhysicalResourceId", result)[0]
result = ec2.describe_iam_instance_profile_associations(Filters=[{"Name": "instance-id", "Values":[instance_id]}])
instance_profile_association_id = jmespath.search('IamInstanceProfileAssociations[0].AssociationId', result)
ec2.disassociate_iam_instance_profile(AssociationId=instance_profile_association_id)
ec2.associate_iam_instance_profile(InstanceId=instance_id, IamInstanceProfile={"Name": input['CorrectInstanceProfile']})
def lambda_handler(event, context):
print(json.dumps(event))
try:
create_cloud9_roles(event["ResourceProperties"])
swap_instance_profile(event["ResourceProperties"])
cfnresponse.send(event, context, cfnresponse.SUCCESS, {})
except Exception as ex:
raise ex
cfnresponse.send(event, context, cfnresponse.FAILED, {})
Description: Associate cloud9 instance with correct profile
TracingConfig:
Mode: Active
SwapInstanceProfile:
Type: Custom::SwapInstanceProfile
Properties:
ServiceToken: !GetAtt Cloud9HelperLambda.Arn
Cloud9Id: !Ref Cloud9
CorrectInstanceProfile: !Ref Cloud9InstanceProfile
CreateCloud9ServiceRoles:
Type: Custom::SwapInstanceProfile
Properties:
ServiceToken: !GetAtt Cloud9HelperLambda.Arn
createCloud9Roles: true
Outputs:
Cloud9Id:
Description: The ID of the Cloud9 ide
Value: !Ref Cloud9