用户数据的Base64编码脚本(AWS SDK for Java API)

时间:2015-06-08 05:06:41

标签: java amazon-web-services amazon-ec2 user-data

如何将bash脚本文件中的内容转换为可与Amazon的Java API一起使用的base64编码字符串?此代码表示我正在尝试执行的操作,但会导致异常:

...引起:com.amazonaws.AmazonServiceException:用户数据的BASE64编码无效(服务:AmazonEC2;状态代码:400;错误代码: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);

编辑: com.amazonaws.util.Base64.encodeAsString()会平息异常,但脚本仍然无法执行。如何格式化字符串?是否应该有回车?

3 个答案:

答案 0 :(得分:2)

使用上面的答案有问题。我的解决方案是我导入了

   23:20:32,392 ERROR [org.jboss.as.controller.management-operation] (Controller Boot Thread) WFLYCTL0013: Operation ("deploy") failed - address: ([("deployment" => "dataRecovery-0.0.1-SNAPSHOT.war")]) - failure description: {
    "WFLYCTL0412: Required services that are not installed:" => ["jboss.naming.context.java.jdbc.DataSource"],
    "WFLYCTL0180: Services with missing/unavailable dependencies" => [
        "jboss.persistenceunit.\"dataRecovery-0.0.1-SNAPSHOT.war#bdd_colis\" is missing [jboss.naming.context.java.jdbc.DataSource]",
        "jboss.persistenceunit.\"dataRecovery-0.0.1-SNAPSHOT.war#bdd_colis\".__FIRST_PHASE__ is missing [jboss.naming.context.java.jdbc.DataSource]"
    ]
}

然后

import com.amazonaws.util.Base64;

答案 1 :(得分:0)

对于编码,您需要使用亚马逊提供的编码类。

amazon.webservices.common.Encoding

它包含API EncodeBase64(),它返回编码数据。

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

答案 2 :(得分:0)

com.amazonaws.util.Base64.encodeAsString适合我。我使用\ n来分隔多林。您也可以在/var/lib/cloud/instance/user-data.txt验证相同的http://169.254.169.254/user-data返回。