简体   繁体   中英

EC2 java sdk -> launching an instance with a public ip

I'm trying to launch an instance into a subnet with a default setting of not assigning public IPs.

With the aws CLI, this is done by adding --associate-public-ip-address :

aws ec2 run-instances --image-id ami-xxx --count 1 --instance-type m4.large --key-name "xxx" --subnet-id subnet-xxx --security-group-ids sg-xxx --associate-public-ip-address

How to do the same thing when launching an instance using the Java SDK?

RunInstancesRequest runInstancesRequest = new RunInstancesRequest();

runInstancesRequest.withImageId(kAmiId)
                   .withInstanceType(kInstanceType)
                   .withMinCount(1)
                   .withMaxCount(1)
                   .withKeyName(kKeyName)
                   .withSecurityGroupIds(kSecurityGroups)
                   .withMonitoring(false)
                   .withSubnetId(kSubnet);

Got it working like this:

InstanceNetworkInterfaceSpecification networkSpec = new InstanceNetworkInterfaceSpecification();
networkSpec.setDeviceIndex(0);
networkSpec.setSubnetId(kSubnet);
networkSpec.setGroups(Arrays.asList(kSecurityGroups));
networkSpec.setAssociatePublicIpAddress(true);

runInstancesRequest.withImageId(kAmiId)
                   .withInstanceType(kInstanceType)
                   .withMinCount(1)
                   .withMaxCount(1)
                   .withKeyName(kKeyName)
                   .withMonitoring(false)
                   .withNetworkInterfaces(networkSpec)
                   .withAdditionalInfo("--associate-public-ip-address");

RunInstancesResult result = mClient.runInstances(runInstancesRequest);

It looks like you have to set it by providing a InstanceNetworkInterfaceSpecification . Something like this:

List<InstanceNetworkInterfaceSpecification> interfaces = new ArrayList<InstanceNetworkInterfaceSpecification>();
interfaces.add(new InstanceNetworkInterfaceSpecification().withAssociatePublicIpAddress(true));

runInstancesRequest.withNetworkInterfaces(interfaces);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM