-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode-server.yaml
More file actions
689 lines (636 loc) · 24 KB
/
code-server.yaml
File metadata and controls
689 lines (636 loc) · 24 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
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
AWSTemplateFormatVersion: "2010-09-09"
Description: Saltware Immersion Day with Amazon Q
Parameters:
CodeServerVersion:
Type: String
Description: Default code-server version to use
Default: "4.104.2"
InstanceName:
Type: String
Description: Name of the VS Code EC2 Instance Name
Default: VSCodeServer
AmiParameterStoreName:
Type: "AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>"
Default: "/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-6.1-x86_64"
Mappings:
PrefixListID:
ap-northeast-2:
PrefixList: pl-22a6434b
us-east-1:
PrefixList: pl-3b927c52
us-west-2:
PrefixList: pl-82a045eb
Resources:
## NETWORK
# VPC
VPC:
Type: AWS::EC2::VPC
Properties:
CidrBlock: 10.0.0.0/16
EnableDnsSupport: true
EnableDnsHostnames: true
InternetGateway:
Type: AWS::EC2::InternetGateway
GatewayAttachment:
Type: AWS::EC2::VPCGatewayAttachment
Properties:
VpcId: !Ref VPC
InternetGatewayId: !Ref InternetGateway
# PUBLIC SUBNET
PublicSubnet1:
Type: AWS::EC2::Subnet
Properties:
CidrBlock: 10.0.0.0/24
VpcId: !Ref VPC
MapPublicIpOnLaunch: true
AvailabilityZone: !Select [0, !GetAZs ""]
Tags:
- Key: kubernetes.io/role/elb
Value: 1
PublicSubnetRouteTable:
Type: AWS::EC2::RouteTable
Properties:
VpcId: !Ref VPC
PublicSubnetRoute:
Type: AWS::EC2::Route
DependsOn: GatewayAttachment
Properties:
RouteTableId: !Ref PublicSubnetRouteTable
DestinationCidrBlock: 0.0.0.0/0
GatewayId: !Ref InternetGateway
PublicSubnetRouteTableAssoc1:
Type: AWS::EC2::SubnetRouteTableAssociation
Properties:
RouteTableId: !Ref PublicSubnetRouteTable
SubnetId: !Ref PublicSubnet1
# VS CODE SERVER
SecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: SG for IDE
SecurityGroupIngress:
- Description: Allow HTTP from CloudFront
IpProtocol: tcp
FromPort: 80
ToPort: 80
SourcePrefixListId: !FindInMap [PrefixListID, !Ref "AWS::Region", PrefixList]
SecurityGroupEgress:
- Description: Allow all outbound traffic
IpProtocol: -1
CidrIp: 0.0.0.0/0
VpcId: !Ref VPC
SecretPlaintextLambdaRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service:
- !Sub lambda.${AWS::URLSuffix}
Action:
- sts:AssumeRole
Path: /
ManagedPolicyArns:
- !Sub arn:${AWS::Partition}:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
Policies:
- PolicyName: AwsSecretsManager
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- secretsmanager:GetSecretValue
Resource: !Ref VSCodeSecret
SecretPlaintextLambda:
Type: AWS::Lambda::Function
# Metadata:
# cfn_nag:
# rules_to_suppress:
# - id: W58
# reason: Cloud9LambdaExecutionRole has the AWSLambdaBasicExecutionRole managed policy attached, allowing writing to CloudWatch logs
# - id: W89
# reason: Bootstrap function does not need the scaffolding of a VPC or provisioned concurrency
# - id: W92
# reason: Bootstrap function does not need provisioned concurrency
Properties:
Description: Return the value of the secret
Handler: index.lambda_handler
Runtime: python3.11
MemorySize: 128
Timeout: 10
Architectures:
- arm64
Role: !GetAtt SecretPlaintextLambdaRole.Arn
Code:
ZipFile: |
import boto3
import json
import cfnresponse
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def is_valid_json(json_string):
logger.debug('Calling is_valid_jason: %s', json_string)
try:
json.loads(json_string)
logger.info('Secret is in json format')
return True
except json.JSONDecodeError:
logger.info('Secret is in string format')
return False
def lambda_handler(event, context):
try:
if event['RequestType'] == 'Delete':
cfnresponse.send(event, context, cfnresponse.SUCCESS, responseData={}, reason='No action to take')
else:
secret_name = (event['ResourceProperties']['SecretArn'])
secrets_mgr = boto3.client('secretsmanager')
secret = secrets_mgr.get_secret_value(SecretId = secret_name)
logger.info('Getting secret from %s', secret_name)
secret_value = secret['SecretString']
logger.debug('secret_value: %s', secret_value)
responseData = {}
if is_valid_json(secret_value):
responseData = secret_value
else:
responseData = {'secret': secret_value}
logger.debug('responseData: %s', responseData)
logger.debug('type(responseData): %s', type(responseData))
cfnresponse.send(event, context, cfnresponse.SUCCESS, responseData=json.loads(responseData), reason='OK', noEcho=True)
except Exception as e:
cfnresponse.send(event, context, cfnresponse.FAILED, responseData={}, reason=str(e))
########### Secret Resources ###########
VSCodeSecret:
# Metadata:
# cfn_nag:
# rules_to_suppress:
# - id: W77
# reason: Secrets Manager Secret should explicitly specify KmsKeyId to allow secret to be shared cross-account - this is not required for this secret as it is generated per-account.
Type: AWS::SecretsManager::Secret
DeletionPolicy: Delete
UpdateReplacePolicy: Delete
Properties:
Name: !Ref InstanceName
Description: VSCode user details
GenerateSecretString:
PasswordLength: 16
SecretStringTemplate: !Sub '{"username":"ec2-user"}'
GenerateStringKey: 'password'
ExcludePunctuation: true
SecretPlaintext:
Type: AWS::CloudFormation::CustomResource
Properties:
ServiceToken: !GetAtt SecretPlaintextLambda.Arn
ServiceTimeout: 20
SecretArn: !Ref VSCodeSecret
WorkshopIdeLambdaExecutionRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- sts:AssumeRole
Path: "/"
Policies:
- PolicyName: !Join ["", [WorkshopIdeLambdaPolicy-, !Ref AWS::Region]]
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
Resource: arn:aws:logs:*:*:*
- Effect: Allow
Action:
- iam:PassRole
- ssm:SendCommand
- ssm:GetCommandInvocation
Resource: "*"
WorkshopIdeBootstrapInstanceLambda:
Type: Custom::WorkshopIdeBootstrapInstanceLambda
DependsOn:
- WorkshopIdeLambdaExecutionRole
Properties:
ServiceToken: !GetAtt WorkshopIdeBootstrapInstanceLambdaFunction.Arn
REGION:
Ref: AWS::Region
InstanceId:
Ref: WorkshopIdeInstance
SsmDocument:
Ref: WorkshopIdeSSMDocument
WorkshopIdeBootstrapInstanceLambdaFunction:
Type: AWS::Lambda::Function
Properties:
Handler: index.lambda_handler
Role: !GetAtt WorkshopIdeLambdaExecutionRole.Arn
Runtime: python3.12
MemorySize: 256
Timeout: "900"
Code:
ZipFile: |
from __future__ import print_function
import json
import logging
import os
import time
import traceback
import boto3
import cfnresponse
logger = logging.getLogger(__name__)
def lambda_handler(event, context):
print(event.values())
print(f"context: {context}")
responseData = {}
status = cfnresponse.SUCCESS
if event["RequestType"] == "Delete":
responseData = {"Success": "Custom Resource removed"}
cfnresponse.send(
event, context, status, responseData, "CustomResourcePhysicalID"
)
else:
try:
ssm = boto3.client("ssm")
instance_id = event["ResourceProperties"]["InstanceId"]
ssm_document = event["ResourceProperties"]["SsmDocument"]
print("Sending SSM command...")
response = ssm.send_command(
InstanceIds=[instance_id], DocumentName=ssm_document
)
command_id = response["Command"]["CommandId"]
waiter = ssm.get_waiter("command_executed")
waiter.wait(
CommandId=command_id,
InstanceId=instance_id,
WaiterConfig={"Delay": 10, "MaxAttempts": 60},
)
responseData = {
"Success": "Started bootstrapping for instance: " + instance_id
}
cfnresponse.send(
event, context, status, responseData, "CustomResourcePhysicalID"
)
except Exception as e:
status = cfnresponse.FAILED
print(traceback.format_exc())
responseData = {"Error": traceback.format_exc(e)}
finally:
cfnresponse.send(
event, context, status, responseData, "CustomResourcePhysicalID"
)
WorkshopIdeSSMDocument:
Type: AWS::SSM::Document
Properties:
DocumentType: Command
DocumentFormat: YAML
Content:
schemaVersion: "2.2"
description: Bootstrap VS Code server Instance
mainSteps:
- action: aws:runShellScript
name: WorkshopIdebootstrap
inputs:
runCommand:
- !Sub |
set -e
dnf install -y git tar gzip vim nodejs npm make gcc g++ argon2
dnf copr enable -y @caddy/caddy epel-9-x86_64
dnf install -y caddy
systemctl enable --now caddy
tee /etc/caddy/Caddyfile <<EOF
http://${WorkshopIdeCloudFrontDistribution.DomainName} {
reverse_proxy 127.0.0.1:8889
}
EOF
systemctl restart caddy
tee /etc/profile.d/custom_prompt.sh <<EOF
#!/bin/sh
export PROMPT_COMMAND='export PS1="\u:\w:$ "'
EOF
export AWS_REGION="${AWS::Region}"
cat <<"EOT" | sudo -E -H -u ec2-user bash
set -e
mkdir -p ~/develop
curl -Ls -o /tmp/uv_install.sh https://astral.sh/uv/install.sh
sudo -u ec2-user sh /tmp/uv_install.sh
curl -Ls -o /tmp/coder.rpm https://github.com/coder/code-server/releases/download/v${CodeServerVersion}/code-server-${CodeServerVersion}-amd64.rpm
sudo rpm -U "/tmp/coder.rpm"
sudo systemctl enable --now code-server@ec2-user
mkdir -p ~/.config/code-server
touch ~/.config/code-server/config.yaml
tee /home/ec2-user/.config/code-server/config.yaml <<EOF
bind-addr: 127.0.0.1:8889
auth: password
hashed-password: "$(echo -n ${SecretPlaintext.password} | argon2 $(openssl rand -base64 12) -e)"
cert: false
EOF
mkdir -p ~/.local/share/code-server/User
touch ~/.local/share/code-server/User/settings.json
cat << EOF > ~/.local/share/code-server/User/settings.json
{
"extensions.autoUpdate": false,
"extensions.autoCheckUpdates": false,
"security.workspace.trust.enabled": false,
"task.allowAutomaticTasks": "on",
"telemetry.telemetryLevel": "off",
"workbench.startupEditor": "none"
}
EOF
mkdir -p ~/develop/.vscode
mkdir -p ~/develop/sample
cat << EOF > ~/develop/sample/sample_python_code.py
import boto3
from PIL import Image
import io
s3 = boto3.client('s3')
def lambda_handler(event, context):
"""
Resizes an image uploaded to an S3 bucket and saves the resized version
to another S3 bucket.
"""
try:
# Get the source bucket and key from the S3 event
source_bucket_name = event['Records'][0]['s3']['bucket']['name']
object_key = event['Records'][0]['s3']['object']['key']
# Define the destination bucket name
destination_bucket_name = '${WorkshopBucket}'
# Get the image from the source S3 bucket
response = s3.get_object(Bucket=source_bucket_name, Key=object_key)
original_image_body = response['Body'].read()
# Open the image using Pillow
image = Image.open(io.BytesIO(original_image_body))
# Define the desired size for the resized image
# You can adjust these values as needed
target_width = 200
target_height = 200
resized_image = image.resize((target_width, target_height))
# Save the resized image to a BytesIO object
buffer = io.BytesIO()
resized_image.save(buffer, format=image.format or 'JPEG') # Use original format or default to JPEG
buffer.seek(0)
# Upload the resized image to the destination S3 bucket
s3.put_object(
Bucket=destination_bucket_name,
Key=object_key, # You might want to modify the key for resized images
Body=buffer,
ContentType=f'image/{image.format.lower()}' if image.format else 'image/jpeg'
)
print(f"Successfully resized {object_key} from {source_bucket_name} to {destination_bucket_name}")
return {
'statusCode': 200,
'body': 'Image resized successfully'
}
except Exception as e:
print(f"Error processing image: {e}")
return {
'statusCode': 500,
'body': f'Error resizing image: {str(e)}'
}
EOF
echo '{ "query": { "folder": "/home/ec2-user/develop" } }' > ~/.local/share/code-server/coder.json
echo 'export AWS_REGION=${AWS::Region}' >> ~/.bashrc
echo 'export AWS_ACCOUNT_ID=${AWS::AccountId}' >> ~/.bashrc
echo 'git config --global credential.helper store' >>~/.bashrc
EOT
systemctl restart code-server@ec2-user
sudo -u ec2-user --login code-server --install-extension AmazonWebServices.amazon-q-vscode --force
WorkshopIdeRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service:
- ec2.amazonaws.com
Action:
- sts:AssumeRole
ManagedPolicyArns:
- arn:aws:iam::aws:policy/AdministratorAccess
Path: "/"
WorkshopIdeInstanceProfile:
Type: AWS::IAM::InstanceProfile
Properties:
Path: "/"
Roles:
- Ref: WorkshopIdeRole
WorkshopIdeInstance:
Type: AWS::EC2::Instance
Properties:
ImageId: !Ref AmiParameterStoreName
InstanceType: t3.medium
BlockDeviceMappings:
- Ebs:
VolumeSize: 20
VolumeType: gp3
DeleteOnTermination: true
Encrypted: true
DeviceName: /dev/xvda
SubnetId: !Ref PublicSubnet1
SecurityGroupIds:
- !Ref SecurityGroup
IamInstanceProfile: !Ref WorkshopIdeInstanceProfile
Tags:
- Key: Name
Value: !Ref InstanceName
# CLOUDFRONT
WorkshopIdeCachePolicy:
Type: AWS::CloudFront::CachePolicy
Properties:
CachePolicyConfig:
DefaultTTL: 86400
MaxTTL: 31536000
MinTTL: 1
Name: !Ref AWS::StackName
ParametersInCacheKeyAndForwardedToOrigin:
CookiesConfig:
CookieBehavior: all
EnableAcceptEncodingGzip: False
HeadersConfig:
HeaderBehavior: whitelist
Headers:
- Accept-Charset
- Authorization
- Origin
- Accept
- Referer
- Host
- Accept-Language
- Accept-Encoding
- Accept-Datetime
QueryStringsConfig:
QueryStringBehavior: all
WorkshopIdeCloudFrontDistribution:
Type: AWS::CloudFront::Distribution
Properties:
DistributionConfig:
Enabled: True
HttpVersion: http2
CacheBehaviors:
- AllowedMethods:
- GET
- HEAD
- OPTIONS
- PUT
- PATCH
- POST
- DELETE
CachePolicyId: 4135ea2d-6df8-44a3-9df3-4b5a84be39ad
Compress: False
OriginRequestPolicyId: 216adef6-5c7f-47e4-b989-5492eafa07d3
TargetOriginId: !Sub CloudFront-${AWS::StackName}
ViewerProtocolPolicy: allow-all
PathPattern: "/proxy/*"
DefaultCacheBehavior:
AllowedMethods:
- GET
- HEAD
- OPTIONS
- PUT
- PATCH
- POST
- DELETE
CachePolicyId: !Ref WorkshopIdeCachePolicy
OriginRequestPolicyId: 216adef6-5c7f-47e4-b989-5492eafa07d3
TargetOriginId: !Sub CloudFront-${AWS::StackName}
ViewerProtocolPolicy: allow-all
Origins:
- DomainName: !GetAtt WorkshopIdeInstance.PublicDnsName
Id: !Sub CloudFront-${AWS::StackName}
CustomOriginConfig:
OriginProtocolPolicy: http-only
# Random String for S3 Bucket
RandomStringLambdaRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: sts:AssumeRole
ManagedPolicyArns:
- !Sub "arn:${AWS::Partition}:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
RandomStringLambdaFunction:
Type: AWS::Lambda::Function
Properties:
Handler: index.lambda_handler
Role: !GetAtt RandomStringLambdaRole.Arn
Runtime: python3.12
Code:
ZipFile: |
import cfnresponse
import random
import string
def lambda_handler(event, context):
response_data = {}
status = cfnresponse.SUCCESS
physical_resource_id = event.get('PhysicalResourceId')
if event['RequestType'] == 'Create':
random_suffix = ''.join(random.choices(string.ascii_lowercase + string.digits, k=8))
response_data['RandomString'] = random_suffix
physical_resource_id = random_suffix
elif event['RequestType'] == 'Update':
random_suffix = physical_resource_id
response_data['RandomString'] = random_suffix
cfnresponse.send(event, context, status, response_data, physical_resource_id)
RandomString:
Type: Custom::RandomString
Properties:
ServiceToken: !GetAtt RandomStringLambdaFunction.Arn
# S3
S3BucketCleanerRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: sts:AssumeRole
ManagedPolicyArns:
- !Sub "arn:${AWS::Partition}:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
Policies:
- PolicyName: S3BucketEmptyPolicy
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- s3:ListBucket
- s3:DeleteObject
- s3:ListBucketVersions
- s3:DeleteObjectVersion
Resource:
- !GetAtt WorkshopBucket.Arn
- !Sub "${WorkshopBucket.Arn}/*"
S3BucketCleanerFunction:
Type: AWS::Lambda::Function
Properties:
Handler: index.lambda_handler
Role: !GetAtt S3BucketCleanerRole.Arn
Runtime: python3.12
Timeout: 300
Code:
ZipFile: |
import boto3
import cfnresponse
import logging
from botocore.exceptions import ClientError
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def lambda_handler(event, context):
try:
if event['RequestType'] == 'Delete':
s3 = boto3.resource('s3')
bucket_name = event['ResourceProperties']['BucketName']
logger.info(f"Emptying bucket: {bucket_name}")
try:
bucket = s3.Bucket(bucket_name)
bucket.object_versions.all().delete()
logger.info(f"All objects deleted from bucket {bucket_name}")
except ClientError as e:
if e.response['Error']['Code'] == 'NoSuchBucket':
logger.info(f"Bucket {bucket_name} already deleted.")
else:
raise
cfnresponse.send(event, context, cfnresponse.SUCCESS, {})
except Exception as e:
logger.error(f"Error: {e}")
cfnresponse.send(event, context, cfnresponse.FAILED, {"Error": str(e)})
WorkshopBucket:
Type: AWS::S3::Bucket
DeletionPolicy: Delete
Properties:
BucketName: !Sub "immersion-day-gallery-${RandomString.RandomString}"
PublicAccessBlockConfiguration:
BlockPublicAcls: true
BlockPublicPolicy: true
IgnorePublicAcls: true
RestrictPublicBuckets: true
S3BucketCleaner:
Type: Custom::S3BucketCleaner
Properties:
ServiceToken: !GetAtt S3BucketCleanerFunction.Arn
BucketName: !Ref WorkshopBucket
Outputs:
URL:
Description: VSCode-Server URL
Value: !Sub https://${WorkshopIdeCloudFrontDistribution.DomainName}
Password:
Description: VSCode-Server Password
Value: !GetAtt SecretPlaintext.password
BucketName:
Description: S3 Bucket Name
Value: !Ref WorkshopBucket