0

How do I turn what was in a bash script file into a base64 encoded string that will work with Amazon's Java API? This code expresses what I'm trying to do but results in an exception:

...Caused by: com.amazonaws.AmazonServiceException: Invalid BASE64 encoding of user data (Service: AmazonEC2; Status Code: 400; Error Code: InvalidParameterValue...

String startupUserData = "#!/bin/bash cd /home/ubuntu/myTestDir; mvn test -PmyBuild";

startupUserData = org.apache.commons.codec.binary.Base64.encodeBase64String(startupUserData.getBytes());

runRqst.withImageId(_computerAmi)
        .withInstanceType(instanceSize)
        .withMinCount(hwRequest.numHwComputers)
        // .withMaxCount(Utils.MAX_EC2_INSTANCES_AT_A_TIME) // NOT THIS
        .withMaxCount(hwRequest.numHwComputers)
        .withKeyName(_keyName)
        .withSecurityGroups(_securityGroup)
        .withUserData(startupUserData);
ec2.runInstances(runRqst);

Edit: com.amazonaws.util.Base64.encodeAsString() quells the exception but the script still doesn't execute. How should the string be formatted? Should there be carriage returns?

3 Answers 3

2

Had problem to use answers above. My solution was that I imported

import com.amazonaws.util.Base64;

and then

String initScript = "sudo -i apt-get install docker.io";

RunInstancesRequest run_request = new RunInstancesRequest()
                .withImageId(ami_id)
                .withInstanceType(InstanceType.T2Micro)
                .withMaxCount(1)
                .withMinCount(1)
                .withUserData(Base64.encodeAsString(initScript.getBytes()));
Sign up to request clarification or add additional context in comments.

Comments

0

For encoding you need to use Encoding class provided by Amazon.

i.e amazon.webservices.common.Encoding

It contains API EncodeBase64() which returns you encoded data.

public static String EncodeBase64(byte[] rawData) {
 return Base64.encodeBytes(rawData);
}

2 Comments

Got a link or the full class path?
0

com.amazonaws.util.Base64.encodeAsString works for me. I use \n to separate multi-lin. You can also verify it at /var/lib/cloud/instance/user-data.txt the same http://169.254.169.254/user-data returns.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.