Thursday, March 17, 2022

[SOLVED] Let ec2 which is made cdk exec start script like Dockerfile

Issue

I made ec2 instance with this code.

const ec2Instance = new ec2.Instance(this, "Instance", {
  vpc,
  instanceType: ec2.InstanceType.of(
    ec2.InstanceClass.T2,
    ec2.InstanceSize.MICRO
  ),
  machineImage: new ec2.AmazonLinuxImage({
    generation: ec2.AmazonLinuxGeneration.AMAZON_LINUX_2,
    cpuType: ec2.AmazonLinuxCpuType.X86_64,
  }),
  securityGroup: securityGroup,
  keyName: "default_aws"
});

ec2 is correctly made but ,there is no application in int ( That's of course)

Normally, after starting the ec2 I log-in and do some commands such as

sudo yum update 
sudo yum install wget
sudo yum install emacs 

I want to exec these command as default when ec 2 is built.

For Docker image I can write the command in Dockerfile

Is there any equivalent things to do?

  1. I checked the ec2 aws UI and found some images and template, is it relevant?

2)Or Can I have something like start scripts in cdk??

I guess It might be common requirement, though, I can't find good information yet.

My final goal is making mysql installed ec2 with cdk, but at first I need to understand the basic idea of ec2 start script


Solution

You can put those commands in a file and read that file in the script like so:

const userDataScript = readFileSync('./lib/user-data.sh', 'utf8');
 // add user data to the EC2 instance
 ec2Instance.addUserData(userDataScript);


Answered By - Devang Sanghani
Answer Checked By - Clifford M. (WPSolving Volunteer)