EC2 Java SDK - User data script
I'm looking for a way to attach a user data script to an EC2 RunRequest in the Java SDK (the equivalent of ec2-run-instances ami-1234567 -f startup-script.zip for the command line tool).
Several things I've read indicate that anything user data string with "#! " will execute, but this doesn't seem to be the case.
Is this even possible?
FYI: here's my test class:
public开发者_如何学JAVA class AWSTest {
public static void main(String[] args) {
AWSCredentials credentials = new BasicAWSCredentials("access-key","secret-access-key");
AmazonEC2Client ec2 = new AmazonEC2Client(credentials);
RunInstancesRequest request = new RunInstancesRequest();
request.setInstanceType(InstanceType.M1Small.toString());
request.setMinCount(1);
request.setMaxCount(1);
request.setImageId("ami-84db39ed");
request.setKeyName("linux-keypair");
request.setUserData(getUserDataScript());
ec2.runInstances(request);
}
private static String getUserDataScript(){
ArrayList<String> lines = new ArrayList<String>();
lines.add("#! /bin/bash");
lines.add("curl http://www.google.com > google.html");
lines.add("shutdown -h 0");
String str = new String(Base64.encodeBase64(join(lines, "\n").getBytes()));
return str;
}
static String join(Collection<String> s, String delimiter) {
StringBuilder builder = new StringBuilder();
Iterator<String> iter = s.iterator();
while (iter.hasNext()) {
builder.append(iter.next());
if (!iter.hasNext()) {
break;
}
builder.append(delimiter);
}
return builder.toString();
}
}
Unfortunately, after I run this, I'm able to SSH into the box, and confirm that
- It hasn't shut down and
- It didn't download the file
Any assistance is greatly appreciated.
Best,
Zach
This works to insert user data in an instance run request, in this case specifically to join an ECS cluster:
private static String getECSuserData(String clusterName) {
String userData = "";
userData = userData + "#!/bin/bash" + "\n";
userData = userData + "echo ECS_CLUSTER=" + clusterName + " ";
userData = userData + ">> /etc/ecs/ecs.config";
String base64UserData = null;
try {
base64UserData = new String( Base64.encodeBase64( userData.getBytes( "UTF-8" )), "UTF-8" );
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return base64UserData;
}
It could be possible that the AMI your using does not support user-data script? Please use the AMI's found at www.alestic.com.
A good reference also http://alestic.com/2009/06/ec2-user-data-scripts
精彩评论