|
| 1 | +import { RemovalPolicy, Duration, Stack } from 'aws-cdk-lib'; |
| 2 | +import { |
| 3 | + Vpc, |
| 4 | + SecurityGroup, |
| 5 | + Instance, |
| 6 | + InstanceType, |
| 7 | + InstanceClass, |
| 8 | + InstanceSize, |
| 9 | + CloudFormationInit, |
| 10 | + InitConfig, |
| 11 | + InitFile, |
| 12 | + InitCommand, |
| 13 | + UserData, |
| 14 | + MachineImage, |
| 15 | + AmazonLinuxCpuType, |
| 16 | +} from 'aws-cdk-lib/aws-ec2'; |
| 17 | +import { |
| 18 | + Role, |
| 19 | + ServicePrincipal, |
| 20 | + ManagedPolicy, |
| 21 | + PolicyDocument, |
| 22 | + PolicyStatement, |
| 23 | +} from 'aws-cdk-lib/aws-iam'; |
| 24 | +import { Bucket, ObjectOwnership } from 'aws-cdk-lib/aws-s3'; |
| 25 | +import { Source, BucketDeployment } from 'aws-cdk-lib/aws-s3-deployment'; |
| 26 | +import { Construct } from 'constructs'; |
| 27 | + |
| 28 | +interface ServerProps { |
| 29 | + vpc: Vpc; |
| 30 | + sshSecurityGroup: SecurityGroup; |
| 31 | + logLevel: string; |
| 32 | + sshPubKey: string; |
| 33 | + cpuType: string; |
| 34 | + instanceSize: string; |
| 35 | +} |
| 36 | + |
| 37 | +let cpuType: AmazonLinuxCpuType; |
| 38 | +let instanceClass: InstanceClass; |
| 39 | +let instanceSize: InstanceSize; |
| 40 | + |
| 41 | +export class ServerResources extends Construct { |
| 42 | + public instance: Instance; |
| 43 | + |
| 44 | + constructor(scope: Construct, id: string, props: ServerProps) { |
| 45 | + super(scope, id); |
| 46 | + |
| 47 | + // Create an Asset Bucket for the Instance. Assets in this bucket will be downloaded to the EC2 during deployment |
| 48 | + const assetBucket = new Bucket(this, 'assetBucket', { |
| 49 | + publicReadAccess: false, |
| 50 | + removalPolicy: RemovalPolicy.DESTROY, |
| 51 | + objectOwnership: ObjectOwnership.BUCKET_OWNER_PREFERRED, |
| 52 | + autoDeleteObjects: true, |
| 53 | + }); |
| 54 | + |
| 55 | + // Deploy the local assets to the Asset Bucket during the CDK deployment |
| 56 | + new BucketDeployment(this, 'assetBucketDeployment', { |
| 57 | + sources: [Source.asset('lib/resources/server/assets')], |
| 58 | + destinationBucket: assetBucket, |
| 59 | + retainOnDelete: false, |
| 60 | + exclude: ['**/node_modules/**', '**/dist/**'], |
| 61 | + memoryLimit: 512, |
| 62 | + }); |
| 63 | + |
| 64 | + // Create a role for the EC2 instance to assume. This role will allow the instance to put log events to CloudWatch Logs |
| 65 | + const serverRole = new Role(this, 'serverEc2Role', { |
| 66 | + assumedBy: new ServicePrincipal('ec2.amazonaws.com'), |
| 67 | + inlinePolicies: { |
| 68 | + ['RetentionPolicy']: new PolicyDocument({ |
| 69 | + statements: [ |
| 70 | + new PolicyStatement({ |
| 71 | + resources: ['*'], |
| 72 | + actions: ['logs:PutRetentionPolicy'], |
| 73 | + }), |
| 74 | + ], |
| 75 | + }), |
| 76 | + }, |
| 77 | + managedPolicies: [ |
| 78 | + ManagedPolicy.fromAwsManagedPolicyName('AmazonSSMManagedInstanceCore'), |
| 79 | + ManagedPolicy.fromAwsManagedPolicyName('CloudWatchAgentServerPolicy'), |
| 80 | + ], |
| 81 | + }); |
| 82 | + |
| 83 | + // Grant the EC2 role access to the bucket |
| 84 | + assetBucket.grantReadWrite(serverRole); |
| 85 | + |
| 86 | + const userData = UserData.forLinux(); |
| 87 | + |
| 88 | + // Add user data that is used to configure the EC2 instance |
| 89 | + userData.addCommands( |
| 90 | + 'yum update -y', |
| 91 | + 'curl -sL https://dl.yarnpkg.com/rpm/yarn.repo | sudo tee /etc/yum.repos.d/yarn.repo', |
| 92 | + 'curl -sL https://rpm.nodesource.com/setup_18.x | sudo -E bash - ', |
| 93 | + 'yum install -y amazon-cloudwatch-agent nodejs python3-pip zip unzip docker yarn', |
| 94 | + 'sudo systemctl enable docker', |
| 95 | + 'sudo systemctl start docker', |
| 96 | + 'mkdir -p /home/ec2-user/sample', |
| 97 | + 'aws s3 cp s3://' + |
| 98 | + assetBucket.bucketName + |
| 99 | + '/sample /home/ec2-user/sample --recursive', |
| 100 | + ); |
| 101 | + |
| 102 | + // Create a Security Group for the EC2 instance. This group will allow SSH access to the EC2 instance |
| 103 | + const ec2InstanceSecurityGroup = new SecurityGroup( |
| 104 | + this, |
| 105 | + 'ec2InstanceSecurityGroup', |
| 106 | + { vpc: props.vpc, allowAllOutbound: true }, |
| 107 | + ); |
| 108 | + |
| 109 | + // Determine the correct CPUType and Instance Class based on the props passed in |
| 110 | + if (props.cpuType == 'ARM64') { |
| 111 | + cpuType = AmazonLinuxCpuType.ARM_64; |
| 112 | + instanceClass = InstanceClass.M7G; |
| 113 | + } else { |
| 114 | + cpuType = AmazonLinuxCpuType.X86_64; |
| 115 | + instanceClass = InstanceClass.M5; |
| 116 | + } |
| 117 | + |
| 118 | + // Determine the correct InstanceSize based on the props passed in |
| 119 | + switch (props.instanceSize) { |
| 120 | + case 'large': |
| 121 | + instanceSize = InstanceSize.LARGE; |
| 122 | + break; |
| 123 | + case 'xlarge': |
| 124 | + instanceSize = InstanceSize.XLARGE; |
| 125 | + break; |
| 126 | + case 'xlarge2': |
| 127 | + instanceSize = InstanceSize.XLARGE2; |
| 128 | + break; |
| 129 | + case 'xlarge4': |
| 130 | + instanceSize = InstanceSize.XLARGE4; |
| 131 | + break; |
| 132 | + default: |
| 133 | + instanceSize = InstanceSize.LARGE; |
| 134 | + } |
| 135 | + |
| 136 | + // Create the EC2 instance |
| 137 | + this.instance = new Instance(this, 'Instance', { |
| 138 | + vpc: props.vpc, |
| 139 | + instanceType: InstanceType.of(instanceClass, instanceSize), |
| 140 | + machineImage: MachineImage.latestAmazonLinux2023({ |
| 141 | + cachedInContext: false, |
| 142 | + cpuType: cpuType, |
| 143 | + }), |
| 144 | + userData: userData, |
| 145 | + securityGroup: ec2InstanceSecurityGroup, |
| 146 | + init: CloudFormationInit.fromConfigSets({ |
| 147 | + configSets: { |
| 148 | + default: ['config'], |
| 149 | + }, |
| 150 | + configs: { |
| 151 | + config: new InitConfig([ |
| 152 | + InitFile.fromObject('/etc/config.json', { |
| 153 | + // Use CloudformationInit to create an object on the EC2 instance |
| 154 | + STACK_ID: Stack.of(this).artifactId, |
| 155 | + }), |
| 156 | + InitFile.fromFileInline( |
| 157 | + // Use CloudformationInit to copy a file to the EC2 instance |
| 158 | + '/tmp/amazon-cloudwatch-agent.json', |
| 159 | + './lib/resources/server/config/amazon-cloudwatch-agent.json', |
| 160 | + ), |
| 161 | + InitFile.fromFileInline( |
| 162 | + '/etc/config.sh', |
| 163 | + 'lib/resources/server/config/config.sh', |
| 164 | + ), |
| 165 | + InitFile.fromString( |
| 166 | + // Use CloudformationInit to write a string to the EC2 instance |
| 167 | + '/home/ec2-user/.ssh/authorized_keys', |
| 168 | + props.sshPubKey + '\n', |
| 169 | + ), |
| 170 | + InitCommand.shellCommand('chmod +x /etc/config.sh'), // Use CloudformationInit to run a shell command on the EC2 instance |
| 171 | + InitCommand.shellCommand('/etc/config.sh'), |
| 172 | + ]), |
| 173 | + }, |
| 174 | + }), |
| 175 | + |
| 176 | + initOptions: { |
| 177 | + timeout: Duration.minutes(10), |
| 178 | + includeUrl: true, |
| 179 | + includeRole: true, |
| 180 | + printLog: true, |
| 181 | + }, |
| 182 | + role: serverRole, |
| 183 | + }); |
| 184 | + |
| 185 | + // Add the SSH Security Group to the EC2 instance |
| 186 | + this.instance.addSecurityGroup(props.sshSecurityGroup); |
| 187 | + } |
| 188 | +} |
0 commit comments