使用 API 创建 Amazon EC2 实例

2022-09-01 13:40:20

com.amazonaws.services.ec2 是否包含从现有 AMI 创建全新 EC2 实例的方法?我希望从Java SDK而不是Web管理控制台执行此操作。


答案 1

以下是使用适用于 Java 的 Amazon AWS 开发工具包创建 EC2 实例的示例:

// CONNECT TO EC2

InputStream credentialsAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("AwsCredentials.properties");
Preconditions.checkNotNull(credentialsAsStream, "File 'AwsCredentials.properties' NOT found in the classpath");
AWSCredentials credentials = new PropertiesCredentials(credentialsAsStream);

AmazonEC2 ec2 = new AmazonEC2Client(credentials);
ec2.setEndpoint("ec2.eu-west-1.amazonaws.com");

// CREATE EC2 INSTANCES
RunInstancesRequest runInstancesRequest = new RunInstancesRequest()
    .withInstanceType("t1.micro")
    .withImageId("ami-62201116")
    .withMinCount(2)
    .withMaxCount(2)
    .withSecurityGroupIds("tomcat")
    .withKeyName("xebia-france")
    .withUserData(Base64.encodeBase64String(myUserData.getBytes()))
;

RunInstancesResult runInstances = ec2.runInstances(runInstancesRequest);

// TAG EC2 INSTANCES
List<Instance> instances = runInstances.getReservation().getInstances();
int idx = 1;
for (Instance instance : instances) {
  CreateTagsRequest createTagsRequest = new CreateTagsRequest();
  createTagsRequest.withResources(instance.getInstanceId()) //
      .withTags(new Tag("Name", "travel-ecommerce-" + idx));
  ec2.createTags(createTagsRequest);

  idx++;
}

源代码(创建 RDS、EC2 和 ELB 实例)可在 http://code.google.com/p/xebia-france/source/browse/training/xebia-spring-travel/trunk/xebia-spring-travel-amazon-aws/src/main/java/fr/xebia/demo/amazon/aws/AmazonAwsInfrastructureMaker.java?spec=svn1781&r=1781

希望这有帮助,

西里尔


答案 2

RunInstances是方法,它应该在SDK中。


推荐