Is it possible to pass a script while I'm starting an instance? So that the instance will execute that script once its initialized?
public static void startInstance(final String instanceId) {
StartInstancesRequest startRequest = new StartInstancesRequest().withInstanceIds(instanceId);
logger.info(String.format("Starting instance '%s':...", instanceId));
ec2.startInstances(startRequest);
}
Any idea? Script will be kind of startup script which I need to execute as soon as the instance is ready. Thanks in advance.
I introduced the concept of user-data scripts in the community Ubuntu AMIs in 2009 (simplified version of some ideas from RightScale):
http://alestic.com/2009/06/ec2-user-data-scripts
It boils down to:
If the instance user-data starts with the two characters #!
then the instance runs it as the root user on the first boot.
This feature was later included in the official Ubuntu AMIs in the CloudInit package:
https://help.ubuntu.com/community/CloudInit
Amazon now includes the CloudInit package in their own Amazon Linux AMIs:
http://docs.amazonwebservices.com/AWSEC2/latest/UserGuide/AmazonLinuxAMIBasics.html
Other distros are welcome to (and may already) include this feature in their AMIs.
You can use the Userdata to pass a script to a new EC2 Instance although I dont know if you can start a pre existing instance and pass it data.
I have a pre configured AMI that has a script saved on the root drive, this script is used to configure the server and download the latest source.
So your request could look like the following:
var runInstance = new RunInstancesRequest();
runInstance.WithImageId("{ami-id}")
.WithInstanceType("{size}")
.WithMaxCount(1)
.WithMinCount(1)
.WithSecurityGroup("{the security group}")
.WithKeyName("{your key}")
.WithUserData(Convert.ToBase64String(Encoding.ASCII.GetBytes(userData)));
ec2.RunInstances(runInstance);
The user data can contain either a reference to a script or the script itself.