Java Code Examples for com.amazonaws.services.ec2.model.Instance#getPublicIpAddress()

The following examples show how to use com.amazonaws.services.ec2.model.Instance#getPublicIpAddress() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AWSProvider.java    From testgrid with Apache License 2.0 6 votes vote down vote up
/**
 * Generates a ssh login command for *nix to access the given ec2 instance.
 *
 * @param instance the ec2 instance
 * @return ssh login command.
 */
private String getLoginCommand(Instance instance) {
    final String privateIpAddress = instance.getPrivateIpAddress();
    String publicAddress = instance.getPublicDnsName();
    publicAddress = publicAddress == null ? instance.getPublicIpAddress() : publicAddress;
    final String keyName = instance.getKeyName();
    String instanceName = instance.getTags().stream()
            .filter(t -> t.getKey().equals("Name"))
            .map(com.amazonaws.services.ec2.model.Tag::getValue)
            .findAny().orElse("");
    instanceName = instanceName.isEmpty() ? "" : "# name: " + instanceName;
    String platform = instance.getPlatform();
    platform = platform == null || platform.isEmpty() ? "" : "# platform: " + platform;

    String ip;
    if (publicAddress != null && !publicAddress.isEmpty()) {
        ip = publicAddress;
    } else {
        ip = privateIpAddress;
    }

    //root user is assumed. EC2 instances print the actual user name when tried to log-in as the root user.
    return "ssh -i " + keyName + " root@" + ip + ";   " + instanceName + platform;
}
 
Example 2
Source File: AwsMetadataCollector.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
private void addFromUnknownMap(CloudInstance cloudInstance, Multimap<String, Instance> unknownMap,
        List<CloudVmMetaDataStatus> collectedCloudVmMetaDataStatuses) {
    LOGGER.debug("Collect from unknown map, cloudInstance: {}, unknownMap: {}", cloudInstance.getInstanceId(), unknownMap.keySet());
    String groupName = cloudInstance.getTemplate().getGroupName();
    Collection<Instance> unknownInstancesForGroup = unknownMap.get(groupName);
    if (!unknownInstancesForGroup.isEmpty()) {
        Optional<Instance> found = unknownInstancesForGroup.stream().findFirst();
        Instance foundInstance = found.get();
        CloudInstance newCloudInstance = new CloudInstance(foundInstance.getInstanceId(), cloudInstance.getTemplate(),
                cloudInstance.getAuthentication(), cloudInstance.getParameters());
        CloudInstanceMetaData cloudInstanceMetaData = new CloudInstanceMetaData(
                foundInstance.getPrivateIpAddress(),
                foundInstance.getPublicIpAddress(),
                awsLifeCycleMapper.getLifeCycle(foundInstance));
        CloudVmInstanceStatus cloudVmInstanceStatus = new CloudVmInstanceStatus(newCloudInstance, InstanceStatus.CREATED);
        CloudVmMetaDataStatus newMetadataStatus = new CloudVmMetaDataStatus(cloudVmInstanceStatus, cloudInstanceMetaData);
        collectedCloudVmMetaDataStatuses.add(newMetadataStatus);
        unknownMap.remove(groupName, found.get());
    }
}
 
Example 3
Source File: RunnerInstance.java    From usergrid with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings( "UnusedDeclaration" )
public RunnerInstance( Instance instance, int port ) {
    this.instance = instance;
    this.port = port;
    this.hostname = instance.getPublicDnsName();
    this.ipv4Address = instance.getPublicIpAddress();
    this.url = "https://" + instance.getPublicDnsName() + ":" + port + "/";
}
 
Example 4
Source File: EC2FleetCloud.java    From ec2-spot-jenkins-plugin with Apache License 2.0 4 votes vote down vote up
/**
 * https://github.com/jenkinsci/ec2-plugin/blob/master/src/main/java/hudson/plugins/ec2/EC2Cloud.java#L640
 *
 * @param ec2      ec2 client
 * @param instance instance
 */
private void addNewSlave(final AmazonEC2 ec2, final Instance instance, FleetStateStats stats) throws Exception {
    final String instanceId = instance.getInstanceId();

    // instance state check enabled and not running, skip adding
    if (addNodeOnlyIfRunning && InstanceStateName.Running != InstanceStateName.fromValue(instance.getState().getName()))
        return;

    final String address = privateIpUsed ? instance.getPrivateIpAddress() : instance.getPublicIpAddress();
    // Check if we have the address to use. Nodes don't get it immediately.
    if (address == null) {
        if (!privateIpUsed) {
            info("%s instance public IP address not assigned, it could take some time or" +
                    " Spot Request is not configured to assign public IPs", instance.getInstanceId());
        }
        return; // wait more time, probably IP address not yet assigned
    }

    // Generate a random FS root if one isn't specified
    final String effectiveFsRoot;
    if (StringUtils.isBlank(fsRoot)) {
        effectiveFsRoot = "/tmp/jenkins-" + UUID.randomUUID().toString().substring(0, 8);
    } else {
        effectiveFsRoot = fsRoot;
    }

    final Double instanceTypeWeight = stats.getInstanceTypeWeights().get(instance.getInstanceType());
    final int effectiveNumExecutors;
    if (scaleExecutorsByWeight && instanceTypeWeight != null) {
        effectiveNumExecutors = (int) Math.max(Math.round(numExecutors * instanceTypeWeight), 1);
    } else {
        effectiveNumExecutors = numExecutors;
    }

    final EC2FleetAutoResubmitComputerLauncher computerLauncher = new EC2FleetAutoResubmitComputerLauncher(
            computerConnector.launch(address, TaskListener.NULL));
    final Node.Mode nodeMode = restrictUsage ? Node.Mode.EXCLUSIVE : Node.Mode.NORMAL;
    final EC2FleetNode node = new EC2FleetNode(instanceId, "Fleet slave for " + instanceId,
            effectiveFsRoot, effectiveNumExecutors, nodeMode, labelString, new ArrayList<NodeProperty<?>>(),
            this, computerLauncher);

    // Initialize our retention strategy
    node.setRetentionStrategy(new IdleRetentionStrategy());

    final Jenkins jenkins = Jenkins.getInstance();
    // jenkins automatically remove old node with same name if any
    jenkins.addNode(node);

    final SettableFuture<Node> future;
    if (plannedNodesCache.isEmpty()) {
        future = SettableFuture.create();
    } else {
        final NodeProvisioner.PlannedNode plannedNode = plannedNodesCache.iterator().next();
        plannedNodesCache.remove(plannedNode);
        future = ((SettableFuture<Node>) plannedNode.future);
    }

    // use getters for timeout and interval as they provide default value
    // when user just install new version and did't recreate fleet
    EC2FleetOnlineChecker.start(node, future,
            TimeUnit.SECONDS.toMillis(getInitOnlineTimeoutSec()),
            TimeUnit.SECONDS.toMillis(getInitOnlineCheckIntervalSec()));
}
 
Example 5
Source File: FetchEC2Job.java    From fullstop with Apache License 2.0 4 votes vote down vote up
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());
    }
}
 
Example 6
Source File: EC2Instance.java    From billow with Apache License 2.0 4 votes vote down vote up
public EC2Instance(Instance instance) {
    this.id = instance.getInstanceId();
    this.type = instance.getInstanceType();
    this.lifecycle = instance.getInstanceLifecycle();
    this.hypervisor = instance.getHypervisor();
    this.az = instance.getPlacement().getAvailabilityZone();
    this.group = instance.getPlacement().getGroupName();
    this.tenancy = instance.getPlacement().getTenancy();
    this.vpc = instance.getVpcId();
    this.platform = instance.getPlatform();
    this.kernel = instance.getKernelId();
    this.key = instance.getKeyName();
    this.image = instance.getImageId();
    this.privateIP = instance.getPrivateIpAddress();
    this.publicIP = instance.getPublicIpAddress();
    this.publicHostname = instance.getPublicDnsName();
    this.privateHostname = instance.getPrivateDnsName();
    this.architecture = instance.getArchitecture();
    this.state = instance.getState().getName();
    this.ramdisk = instance.getRamdiskId();
    this.subnet = instance.getSubnetId();
    this.rootDeviceName = instance.getRootDeviceName();
    this.rootDeviceType = instance.getRootDeviceType();
    this.stateTransitionReason = instance.getStateTransitionReason();
    this.spotInstanceRequest = instance.getSpotInstanceRequestId();
    this.virtualizationType = instance.getVirtualizationType();
    this.sourceDestCheck = instance.getSourceDestCheck();
    this.launchTime = new DateTime(instance.getLaunchTime());

    if (instance.getIamInstanceProfile() != null) {
        this.iamInstanceProfile = instance.getIamInstanceProfile().getArn().toString();
    } else {
        this.iamInstanceProfile = null;
    }

    final StateReason stateReason = instance.getStateReason();
    if (stateReason != null)
        this.stateReason = stateReason.getMessage();
    else
        this.stateReason = null;

    this.securityGroups = new ArrayList<>();
    for (GroupIdentifier identifier : instance.getSecurityGroups()) {
        this.securityGroups.add(new SecurityGroup(identifier));
    }

    this.tags = new HashMap<>();
    for (Tag tag : instance.getTags()) {
        this.tags.put(tag.getKey(), tag.getValue());
    }
}
 
Example 7
Source File: RunnerInstance.java    From usergrid with Apache License 2.0 4 votes vote down vote up
public RunnerInstance( Instance instance ) {
    this.instance = instance;
    this.hostname = instance.getPublicDnsName();
    this.ipv4Address = instance.getPublicIpAddress();
    this.url = "https://" + instance.getPublicDnsName() + ":" + Runner.DEFAULT_SERVER_PORT + "/";
}