當前位置: 首頁>>代碼示例>>Java>>正文


Java Instance.getPublicIpAddress方法代碼示例

本文整理匯總了Java中com.amazonaws.services.ec2.model.Instance.getPublicIpAddress方法的典型用法代碼示例。如果您正苦於以下問題:Java Instance.getPublicIpAddress方法的具體用法?Java Instance.getPublicIpAddress怎麽用?Java Instance.getPublicIpAddress使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在com.amazonaws.services.ec2.model.Instance的用法示例。


在下文中一共展示了Instance.getPublicIpAddress方法的6個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: getOwnIP

import com.amazonaws.services.ec2.model.Instance; //導入方法依賴的package包/類
public static String getOwnIP()
{
	AWSCredentials credentials = null;
	try
	{
		credentials = new ProfileCredentialsProvider().getCredentials();
	}
	catch(Exception e){}
	
	AmazonEC2 ec2 = new AmazonEC2Client(credentials);		

	ec2.setEndpoint("ec2.eu-west-1.amazonaws.com");
	DescribeInstancesResult describeInstancesResult = ec2.describeInstances();
	List<Reservation> reservations = describeInstancesResult.getReservations();
	ArrayList<Instance> listOfInstances = new ArrayList<Instance>();
	for(Reservation reservation : reservations)
		listOfInstances.addAll(reservation.getInstances());
	
	String ownIP = null;
	String ownInstanceID = checkInstanceId();
	for(Instance instance: listOfInstances)
	{
		if(instance.getInstanceId().equals(ownInstanceID))
			ownIP = instance.getPublicIpAddress();
	}
	
	return ownIP;
}
 
開發者ID:carlosfaria94,項目名稱:CloudPrime,代碼行數:29,代碼來源:Connection.java

示例2: execute

import com.amazonaws.services.ec2.model.Instance; //導入方法依賴的package包/類
/**
 * Stop Ec2 Instance. Realease EIP for Ec2 Instance. Disassociate EIP.
 */
public int execute(Ec2CommandOptions options) throws FileNotFoundException {
	System.out.println(getClass().getName());
	String name = options.getName();
	InputStream inputStream = new FileInputStream(new File(options.getCredentialsPath()));
	ConfigProvider.loadConfigure(inputStream);
	AmazonEC2 ec2 = AwsEc2Client.getEc2();

	// Check Exists Instance
	Instance instance = AwsEc2Client.findInstanceByName(ec2, name);
	if (instance == null) {
		System.err.println("Not exists instance (name = " + name + ").");
		return 2;
	}
	String instanceId = instance.getInstanceId();
	String publicIp = instance.getPublicIpAddress();
	System.out.println("Exists instance (id = " + instanceId + ")");

	// Stop Ec2 Instance
	InstanceStateChange stateChange = AwsEc2Client.stopInstance(ec2, instanceId);
	AwsEc2Client.showStateChange(stateChange, "Stopping Instance");

	// Disassociate and Release Address
	if (publicIp != null) {
		Address address = AwsEc2Client.checkExistsAddress(ec2, publicIp);
		if (address != null) {
			AwsEc2Client.disassociateAddress(ec2, address);
			System.out.println("Disassociated Address (" + publicIp + ")");
			AwsEc2Client.releaseAddress(ec2, address);
			System.out.println("Released Address (" + publicIp + ")");
		}
	} else {
		System.out.println("No EIP.");
	}
	return 0;
}
 
開發者ID:betahikaru,項目名稱:ec2-util,代碼行數:39,代碼來源:Ec2StopCommand.java

示例3: addNewSlave

import com.amazonaws.services.ec2.model.Instance; //導入方法依賴的package包/類
private void addNewSlave(final AmazonEC2 ec2, final String instanceId) throws Exception {
    // Generate a random FS root if one isn't specified
    String fsRoot = this.fsRoot;
    if (fsRoot == null || fsRoot.equals("")) {
        fsRoot = "/tmp/jenkins-"+UUID.randomUUID().toString().substring(0, 8);
    }

    final DescribeInstancesResult result=ec2.describeInstances(
            new DescribeInstancesRequest().withInstanceIds(instanceId));
    if (result.getReservations().isEmpty()) //Can't find this instance, skip it
        return;
    final Instance instance=result.getReservations().get(0).getInstances().get(0);
    final String address = isPrivateIpUsed() ?
            instance.getPrivateIpAddress() : instance.getPublicIpAddress();

    // Check if we have the address to use. Nodes don't get it immediately.
    if (address == null)
        return; // Wait some more...

    final FleetNode slave = new FleetNode(instanceId, "Fleet slave for" + instanceId,
            fsRoot, this.numExecutors.toString(), Node.Mode.NORMAL, this.labelString, new ArrayList<NodeProperty<?>>(),
            FLEET_CLOUD_ID, computerConnector.launch(address, TaskListener.NULL));

    // Initialize our retention strategy
    if (getIdleMinutes() != null)
        slave.setRetentionStrategy(new IdleRetentionStrategy(getIdleMinutes(), this));

    final Jenkins jenkins=Jenkins.getInstance();
    //noinspection SynchronizationOnLocalVariableOrMethodParameter
    synchronized (jenkins) {
        // Try to avoid duplicate nodes
        final Node n = jenkins.getNode(instanceId);
        if (n != null)
            jenkins.removeNode(n);
        jenkins.addNode(slave);
    }

    //A new node, wheee!
    instancesSeen.add(instanceId);
    if (!plannedNodes.isEmpty())
    {
        //If we're waiting for a new node - mark it as ready
        final NodeProvisioner.PlannedNode curNode=plannedNodes.iterator().next();
        plannedNodes.remove(curNode);
        ((SettableFuture<Node>)curNode.future).set(slave);
    }
}
 
開發者ID:awslabs,項目名稱:ec2-spot-jenkins-plugin,代碼行數:48,代碼來源:EC2FleetCloud.java

示例4: getPropertyValue

import com.amazonaws.services.ec2.model.Instance; //導入方法依賴的package包/類
@Override
protected String getPropertyValue(Instance instance) {
  return instance.getPublicIpAddress();
}
 
開發者ID:cloudera,項目名稱:director-aws-plugin,代碼行數:5,代碼來源:EC2Instance.java

示例5: processInstance

import com.amazonaws.services.ec2.model.Instance; //導入方法依賴的package包/類
private void processInstance(String account, String region, Instance instance) {
    final Map<String, Object> metaData = newHashMap();
    metaData.putAll(amiDetailsProvider.getAmiDetails(account, getRegion(fromName(region)), instance.getImageId()));
    final List<String> errorMessages = newArrayList();
    final String instancePublicIpAddress = instance.getPublicIpAddress();

    if (violationService.violationExists(account, region, EVENT_ID, instance.getInstanceId(), UNSECURED_PUBLIC_ENDPOINT)) {
        return;
    }

    final Map<String, SecurityGroupCheckDetails> unsecureGroups = securityGroupsChecker.check(
            instance.getSecurityGroups().stream().map(GroupIdentifier::getGroupId).collect(toList()),
            account,
            getRegion(fromName(region)));
    if (!unsecureGroups.isEmpty()) {
        metaData.put("unsecuredSecurityGroups", unsecureGroups);
        errorMessages.add("Unsecured security group! Only ports 80 and 443 are allowed");
    }

    if (errorMessages.size() > 0) {
        metaData.put("errorMessages", errorMessages);
        writeViolation(account, region, metaData, instance.getInstanceId());

        // skip http response check, as we are already having a violation here
        return;
    }

    // skip check for publicly available apps
    if (awsApplications.isPubliclyAccessible(account, region, newArrayList(instance.getInstanceId())).orElse(false)) {
        return;
    }

    for (final Integer allowedPort : jobsProperties.getEc2AllowedPorts()) {

        if (allowedPort == 22) {
            continue;
        }

        final HttpGetRootCall httpCall = new HttpGetRootCall(httpClient, instancePublicIpAddress, allowedPort);
        final ListenableFuture<HttpCallResult> listenableFuture = threadPoolTaskExecutor.submitListenable(
                httpCall);
        listenableFuture.addCallback(
                httpCallResult -> {
                    log.debug("address: {} and port: {}", instancePublicIpAddress, allowedPort);
                    if (httpCallResult.isOpen()) {
                        final Map<String, Object> md = ImmutableMap.<String, Object>builder()
                                .putAll(metaData)
                                .put("instancePublicIpAddress", instancePublicIpAddress)
                                .put("Port", allowedPort)
                                .put("Error", httpCallResult.getMessage()).build();
                        writeViolation(account, region, md, instance.getInstanceId());
                    }
                }, ex -> log.warn("Could not call " + instancePublicIpAddress, ex));

        log.debug("Active threads in pool: {}/{}", threadPoolTaskExecutor.getActiveCount(), threadPoolTaskExecutor.getMaxPoolSize());
    }
}
 
開發者ID:zalando-stups,項目名稱:fullstop,代碼行數:58,代碼來源:FetchEC2Job.java

示例6: connectToWinRM

import com.amazonaws.services.ec2.model.Instance; //導入方法依賴的package包/類
private WinConnection connectToWinRM(EC2Computer computer, PrintStream logger) throws AmazonClientException,
InterruptedException {
    final long timeout = computer.getNode().getLaunchTimeoutInMillis();
    final long startTime = System.currentTimeMillis();
    
    logger.println(computer.getNode().getDisplayName() + " booted at " + computer.getNode().getCreatedTime());
    boolean alreadyBooted = (startTime - computer.getNode().getCreatedTime()) > TimeUnit.MINUTES.toMillis(3);
    while (true) {
        try {
            long waitTime = System.currentTimeMillis() - startTime;
            if (waitTime > timeout) {
                throw new AmazonClientException("Timed out after " + (waitTime / 1000)
                        + " seconds of waiting for winrm to be connected");
            }
            Instance instance = computer.updateInstanceDescription();
            String vpc_id = instance.getVpcId();
            String ip, host;

            if (computer.getNode().usePrivateDnsName) {
                host = instance.getPrivateDnsName();
                ip = instance.getPrivateIpAddress(); // SmbFile doesn't quite work with hostnames
            } else {
                host = instance.getPublicDnsName();
                if (host == null || host.equals("")) {
                    host = instance.getPrivateDnsName();
                    ip = instance.getPrivateIpAddress(); // SmbFile doesn't quite work with hostnames
                }
                else {
                    host = instance.getPublicDnsName();
                    ip = instance.getPublicIpAddress(); // SmbFile doesn't quite work with hostnames
                }
            }

            if ("0.0.0.0".equals(host)) {
                logger.println("Invalid host 0.0.0.0, your host is most likely waiting for an ip address.");
                throw new IOException("goto sleep");
            }

            logger.println("Connecting to " + host + "(" + ip + ") with WinRM as " + computer.getNode().remoteAdmin);

            WinConnection connection = new WinConnection(ip, computer.getNode().remoteAdmin, computer.getNode().getAdminPassword());
            connection.setUseHTTPS(computer.getNode().isUseHTTPS());
            if (!connection.ping()) {
                logger.println("Waiting for WinRM to come up. Sleeping 10s.");
                Thread.sleep(sleepBetweenAttemps);
                continue;
            }
            
            if (!alreadyBooted || computer.getNode().stopOnTerminate) {
                logger.println("WinRM service responded. Waiting for WinRM service to stabilize on " + computer.getNode().getDisplayName());
                Thread.sleep(computer.getNode().getBootDelay());
                alreadyBooted = true;
                logger.println("WinRM should now be ok on " + computer.getNode().getDisplayName());
                if (!connection.ping()) {
                    logger.println("WinRM not yet up. Sleeping 10s.");
                    Thread.sleep(sleepBetweenAttemps);
                    continue;
                }
            }

            logger.println("Connected with WinRM.");
            return connection; // successfully connected
        } catch (IOException e) {
            logger.println("Waiting for WinRM to come up. Sleeping 10s.");
            Thread.sleep(sleepBetweenAttemps);
        }
    }
}
 
開發者ID:hudson3-plugins,項目名稱:ec2-plugin,代碼行數:69,代碼來源:EC2WindowsLauncher.java


注:本文中的com.amazonaws.services.ec2.model.Instance.getPublicIpAddress方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。