AWS CDK EC2 user data - copy local file to EC2 instance

419 Views Asked by At

In my AWS CDK code for setting up EC2, I’m trying to put a local file to a certain location in my instance.

The only overcomplicated way I can think of is to upload it to s3 in the CDK code, and then

// download from s3 to instance
const localPath = instance.userData.addS3DownloadCommand({
  bucket:asset.bucket,
  bucketKey:asset.s3ObjectKey

// move
instance.user_data.add_commands(
        "#!/bin/bash",
        "mv {localPath} dst”
    )
1

There are 1 best solutions below

0
On

You can use cloudInit

this.instance = new Instance(this, 'Instance', {
  vpc: props.vpc,
  instanceType: InstanceType.of(instanceClass, instanceSize),
  machineImage: MachineImage.latestAmazonLinux2023({
    cachedInContext: false,
    cpuType: cpuType,
  }),
  userData: userData,
  securityGroup: ec2InstanceSecurityGroup,
  init: CloudFormationInit.fromConfigSets({
    configSets: {
      default: ['config'],
    },
    configs: {
      config: new InitConfig([
        InitFile.fromObject('/etc/config.json', {
          // Use CloudformationInit to create an object on the EC2 instance
          STACK_ID: Stack.of(this).artifactId,
        }),
        InitFile.fromFileInline(
          // Use CloudformationInit to copy a file to the EC2 instance
          '/tmp/amazon-cloudwatch-agent.json',
          './src/resources/server/config/amazon-cloudwatch-agent.json',
        ),
        InitFile.fromFileInline(
          '/etc/config.sh',
          'src/resources/server/config/config.sh',
        ),
        InitFile.fromString(
          // Use CloudformationInit to write a string to the EC2 instance
          '/home/ec2-user/.ssh/authorized_keys',
          props.sshPubKey + '\n',
        ),
        InitCommand.shellCommand('chmod +x /etc/config.sh'), // Use CloudformationInit to run a shell command on the EC2 instance
        InitCommand.shellCommand('/etc/config.sh'),
      ]),
    },
  }),