简体   繁体   中英

Typescript CDK, how to add files to ec2 instance?

I know how to use Here docs to run scripts on a newly launched instance such as

instance.addUserData(
      bash << EOF
      #!/usr/bin/bash 
      ...
      EOF,
);

but I do not not want to do this for configuration files since they are git managed.

So how do I include text files in a newly launched instance? Amazon seems to want you to use S3 according to the Assets documentation here https://docs.aws.amazon.com/cdk/latest/guide/assets.html but I think there should be a way in native CDK to do this I just can't find it in the API docs.

Ec2 construct has an init parameter that you can exploit as described here

In order to do that you have to leverage both the CloudFormationInit class and the InitFile class .

This will allow you to provide files while your instance is being started from a number of sources. In order to to contain the size of your template is recommended to store assets in an S3 bucket if the file is too big.

Putting it all together you should write down something like this:

    // prepare the file as an s3 asset
     const s3Asset = new Asset(this, 'SampleSingleFileAsset', {
        path: './local/path/tofile/file.extension',
    });

    // prepare the file as an asset and put it in the cfinit
    const initData = CloudFormationInit.fromElements(
InitFile.fromExistingAsset('/destination/path/filename.extension', s3Asset, {})
);

    // create the EC2 Instance with the initData parameter
    const ec2Instance = new Instance(this, 'ec2-instance', {
                   
        //other parameters...

        init: initData
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM