/** * Create a NAT Gateway * It waits for the NAT gateway to become available before returning the gateway id. */ public DeferredResult<String> createNatGateway(String publicSubnetId, String allocationId, TaskManager taskManager, long taskExpirationMicros) { CreateNatGatewayRequest req = new CreateNatGatewayRequest() .withSubnetId(publicSubnetId) .withAllocationId(allocationId); String message = "Create AWS NAT Gateway for subnet [" + publicSubnetId + "] with elastic IP allocation id [" + allocationId + "]."; AWSDeferredResultAsyncHandler<CreateNatGatewayRequest, CreateNatGatewayResult> handler = new AWSDeferredResultAsyncHandler<>(this.service, message); this.client.createNatGatewayAsync(req, handler); return handler.toDeferredResult() .thenApply(CreateNatGatewayResult::getNatGateway) .thenApply(NatGateway::getNatGatewayId) .thenCompose(natGatewayId -> waitForNatGatewayState(natGatewayId, taskManager, taskExpirationMicros, AWSTaskStatusChecker.AWS_AVAILABLE_NAME)); }
public NatGateway createNATGateway(String subnetId, String ip) { logger.info("create nat gateway, subnetId={}, ip={}", subnetId, ip); List<Address> addresses = AWS.vpc.ec2.describeAddresses(new DescribeAddressesRequest().withPublicIps(ip)).getAddresses(); if (addresses.isEmpty()) throw new Error("cannot find eip, ip=" + ip); Address address = addresses.get(0); if (address.getAssociationId() != null) throw new Error("eip must not associated with other resource, ip=" + ip); CreateNatGatewayRequest request = new CreateNatGatewayRequest() .withSubnetId(subnetId) .withAllocationId(address.getAllocationId()); String gatewayId = ec2.createNatGateway(request).getNatGateway().getNatGatewayId(); NatGateway gateway; while (true) { Threads.sleepRoughly(Duration.ofSeconds(30)); gateway = describeNATGateway(gatewayId); String state = gateway.getState(); if ("pending".equals(state)) continue; if ("available".equals(state)) { break; } else { throw new Error("failed to create nat gateway, gatewayId=" + gatewayId + ", state=" + state); } } return gateway; }
@Override public CreateNatGatewayResult createNatGateway(CreateNatGatewayRequest createNatGatewayRequest) { throw new UnsupportedOperationException("Not supported in mock"); }