当前位置: 首页>>代码示例>>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;未经允许,请勿转载。