Example usage for com.amazonaws.services.ec2.model DescribeTagsRequest DescribeTagsRequest

List of usage examples for com.amazonaws.services.ec2.model DescribeTagsRequest DescribeTagsRequest

Introduction

In this page you can find the example usage for com.amazonaws.services.ec2.model DescribeTagsRequest DescribeTagsRequest.

Prototype

public DescribeTagsRequest() 

Source Link

Document

Default constructor for DescribeTagsRequest object.

Usage

From source file:com.amazon.kinesis.streaming.agent.processing.processors.AddEC2MetadataConverter.java

License:Open Source License

private void refreshEC2Metadata() {
    LOGGER.info("Refreshing EC2 metadata");

    metadataTimestamp = System.currentTimeMillis();

    try {// www  .j  a v  a2 s  .c om
        EC2MetadataUtils.InstanceInfo info = EC2MetadataUtils.getInstanceInfo();

        metadata = new LinkedHashMap<String, Object>();
        metadata.put("privateIp", info.getPrivateIp());
        metadata.put("availabilityZone", info.getAvailabilityZone());
        metadata.put("instanceId", info.getInstanceId());
        metadata.put("instanceType", info.getInstanceType());
        metadata.put("accountId", info.getAccountId());
        metadata.put("amiId", info.getImageId());
        metadata.put("region", info.getRegion());
        metadata.put("metadataTimestamp",
                new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").format(new Date(metadataTimestamp)));

        final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient();
        DescribeTagsResult result = ec2.describeTags(new DescribeTagsRequest()
                .withFilters(new Filter().withName("resource-id").withValues(info.getInstanceId())));
        List<TagDescription> tags = result.getTags();

        Map<String, Object> metadataTags = new LinkedHashMap<String, Object>();
        for (TagDescription tag : tags) {
            metadataTags.put(tag.getKey().toLowerCase(), tag.getValue());
        }
        metadata.put("tags", metadataTags);
    } catch (Exception ex) {
        LOGGER.warn("Error while updating EC2 metadata - " + ex.getMessage() + ", ignoring");
    }
}

From source file:com.hazelcast.samples.amazon.elasticbeanstalk.HazelcastInstanceFactory.java

License:Open Source License

protected Properties getAwsProperties() {
    EC2MetadataUtils.InstanceInfo instanceInfo = EC2MetadataUtils.getInstanceInfo();
    String instanceId = instanceInfo.getInstanceId();

    // EB sets the environment ID and name as the elasticbeanstalk:environment-id and
    // elasticbeanstalk:environment-name EC2 tags on all of the parts of an EB app environment: load balancer,
    // EC2 instances, security groups, etc. Surprisingly, EC2 tags aren't available to instances through the
    // instance metadata interface, but they are available through the normal AWS APIs DescribeTags call.
    Collection<Filter> filters = new ArrayList<Filter>();
    filters.add(new Filter("resource-type").withValues("instance"));
    filters.add(new Filter("resource-id").withValues(instanceId));
    filters.add(new Filter("key").withValues(ELASTICBEANSTALK_ENVIRONMENT_NAME));

    DescribeTagsRequest describeTagsRequest = new DescribeTagsRequest();
    describeTagsRequest.setFilters(filters);
    DescribeTagsResult describeTagsResult = amazonEC2.describeTags(describeTagsRequest);

    if (describeTagsResult == null || describeTagsResult.getTags().isEmpty()) {
        throw new IllegalStateException(
                "No tag " + ELASTICBEANSTALK_ENVIRONMENT_NAME + " found for instance " + instanceId + ".");
    }/* www  .  j a v a2s .c o m*/

    String environmentName = describeTagsResult.getTags().get(0).getValue();
    String environmentPassword = MD5Util.toMD5String(environmentName);

    Properties properties = new Properties();
    properties.setProperty(HAZELCAST_ENVIRONMENT_NAME, environmentName);
    properties.setProperty(HAZELCAST_ENVIRONMENT_PASSWORD, environmentPassword);
    properties.setProperty(HAZELCAST_AWS_IAM_ROLE, ELASTICBEANSTALK_EC2_ROLE_NAME);
    properties.setProperty(HAZELCAST_AWS_REGION, instanceInfo.getRegion());

    return properties;
}

From source file:com.kixeye.chassis.bootstrap.aws.AwsUtils.java

License:Apache License

/**
 * Fetches and instance's name Tag or null if it does not have one
 * @param instanceId/*from   w  w w.  ja va  2s .co  m*/
 * @param amazonEC2
 * @return
 */
public static String getInstanceName(String instanceId, AmazonEC2 amazonEC2) {
    DescribeTagsResult result = amazonEC2.describeTags(
            new DescribeTagsRequest().withFilters(new Filter().withName("resource-id").withValues(instanceId),
                    new Filter().withName("resource-type").withValues("instance"),
                    new Filter().withName("key").withValues(TAG_KEY_NAME)));
    if (result.getTags().isEmpty()) {
        return null;
    }
    String name = result.getTags().get(0).getValue();
    return name == null || name.trim().equals("") ? null : name;
}

From source file:com.vmware.photon.controller.model.adapters.awsadapter.AWSUtils.java

License:Open Source License

public static List<TagDescription> getResourceTags(String resourceID, AmazonEC2AsyncClient client) {
    Filter resource = new Filter().withName(AWS_FILTER_RESOURCE_ID).withValues(resourceID);
    DescribeTagsRequest req = new DescribeTagsRequest().withFilters(resource);
    DescribeTagsResult result = client.describeTags(req);
    return result.getTags();
}

From source file:fr.xebia.training.troubleshooting.TroubleshootingTrainingInfrastructureCreator.java

License:Apache License

public void generateDocs() {
    Filter filter = new Filter("tag:TrainingSession", Lists.newArrayList("Troubleshooting"));
    List<Reservation> reservations = ec2.describeInstances(new DescribeInstancesRequest().withFilters(filter))
            .getReservations();/*  w  w  w  .j av a 2  s . co  m*/
    Iterable<Instance> instances = AmazonAwsUtils.toEc2Instances(reservations);

    Iterable<Instance> runningInstances = Iterables.filter(instances,
            AmazonAwsUtils.PREDICATE_RUNNING_OR_PENDING_INSTANCE);
    runningInstances = AmazonAwsUtils.awaitForEc2Instances(runningInstances, ec2);

    Map<String, Instance> runningInstancesByInstanceId = Maps.uniqueIndex(runningInstances,
            AmazonAwsFunctions.EC2_INSTANCE_TO_INSTANCE_ID);

    List<String> runningInstanceIds = Lists.newArrayList(
            Iterables.transform(runningInstances, AmazonAwsFunctions.EC2_INSTANCE_TO_INSTANCE_ID));

    List<TagDescription> tags = ec2
            .describeTags(new DescribeTagsRequest().withFilters(new Filter("resource-id", runningInstanceIds)))
            .getTags();
    Map<String, Map<String, String>> tagsByInstanceId = new MapMaker()
            .makeComputingMap(new Function<String, Map<String, String>>() {
                @Override
                public Map<String, String> apply(String instanceId) {
                    return Maps.newHashMap();
                }
            });

    for (TagDescription tag : tags) {
        tagsByInstanceId.get(tag.getResourceId()).put(tag.getKey(), tag.getValue());
    }

    Map<String, Map<String, Object>> tomcatTagsPerTeamIdentifier = Maps.newHashMap();

    for (Map.Entry<String, Map<String, String>> entry : tagsByInstanceId.entrySet()) {
        String instanceId = entry.getKey();
        Map<String, String> instanceTags = entry.getValue();

        String teamIdentifier = instanceTags.get("TeamIdentifier");
        Instance tomcatInstance = runningInstancesByInstanceId.get(instanceId);

        Map<String, Object> tomcatTags = Maps.newHashMap();
        tomcatTags.putAll(instanceTags);
        tomcatTags.put("PublicDnsName", tomcatInstance.getPublicDnsName());
        tomcatTags.put("Instance", tomcatInstance);

        tomcatTagsPerTeamIdentifier.put(teamIdentifier, tomcatTags);
    }

    Map<String, Object> rootMap = Maps.newHashMap();
    rootMap.put("infrastructures", tomcatTagsPerTeamIdentifier);
    String wikiPage = FreemarkerUtils.generate(rootMap, "/fr/xebia/training/troubleshooting/wiki-page.ftl");
    System.out.println(wikiPage);
}

From source file:fr.xebia.workshop.continuousdelivery.InfrastructureTopologyScanner.java

License:Apache License

public Collection<TeamInfrastructure> scan() {
    Filter filter = new Filter("tag:Workshop", newArrayList("continuous-delivery-workshop"));
    List<Reservation> reservations = ec2.describeInstances(new DescribeInstancesRequest().withFilters(filter))
            .getReservations();//from   w  ww.j  av a2  s  .  c  o m

    Iterable<Instance> instances = AmazonAwsUtils.toEc2Instances(reservations);

    Iterable<Instance> runningInstances = Iterables.filter(instances,
            AmazonAwsUtils.PREDICATE_RUNNING_OR_PENDING_INSTANCE);
    runningInstances = AmazonAwsUtils.awaitForEc2Instances(runningInstances, ec2);

    Map<String, Instance> runningInstancesByInstanceId = Maps.uniqueIndex(runningInstances,
            AmazonAwsFunctions.EC2_INSTANCE_TO_INSTANCE_ID);

    List<String> runningInstanceIds = newArrayList(
            Iterables.transform(runningInstances, AmazonAwsFunctions.EC2_INSTANCE_TO_INSTANCE_ID));

    List<TagDescription> tags = ec2
            .describeTags(new DescribeTagsRequest().withFilters(new Filter("resource-id", runningInstanceIds)))
            .getTags();
    Map<String, Map<String, String>> tagsByInstanceId = new MapMaker()
            .makeComputingMap(new Function<String, Map<String, String>>() {
                @Override
                public Map<String, String> apply(String instanceId) {
                    return Maps.newHashMap();
                }
            });

    for (TagDescription tag : tags) {
        tagsByInstanceId.get(tag.getResourceId()).put(tag.getKey(), tag.getValue());
    }

    Map<String, TeamInfrastructure> teamInfrastructureByTeamIdentifier = new MapMaker()
            .makeComputingMap(new Function<String, TeamInfrastructure>() {
                @Override
                public TeamInfrastructure apply(String teamIdentifier) {
                    return new TeamInfrastructure(workshopInfrastructure, teamIdentifier);
                }
            });

    Instance nexusServer = null;

    for (Map.Entry<String, Map<String, String>> entry : tagsByInstanceId.entrySet()) {
        Map<String, String> instanceTags = entry.getValue();
        String instanceId = entry.getKey();
        Instance instance = runningInstancesByInstanceId.get(instanceId);
        String teamIdentifier = instanceTags.get("TeamIdentifier");

        if (teamIdentifier == null) {
            if (TeamInfrastructure.ROLE_NEXUS.equals(instanceTags.get("Role"))) {
                nexusServer = instance;
            } else {
                // not a per team server (e.g. Nexus server)
            }
        } else {

            TeamInfrastructure teamInfrastructure = teamInfrastructureByTeamIdentifier.get(teamIdentifier);
            teamInfrastructure.addInstance(instance, instanceTags);
        }
    }
    Collection<TeamInfrastructure> teamInfrastructures = teamInfrastructureByTeamIdentifier.values();
    for (TeamInfrastructure teamInfrastructure : teamInfrastructures) {
        teamInfrastructure.setNexus(nexusServer);
    }
    return teamInfrastructures;
}

From source file:fr.xebia.workshop.monitoring.InfrastructureTopologyScanner.java

License:Apache License

public Collection<TeamInfrastructure> scan() {
    Filter filter = new Filter("tag:Workshop", newArrayList("monitoring"));
    List<Reservation> reservations = ec2.describeInstances(new DescribeInstancesRequest().withFilters(filter))
            .getReservations();//www.  j av  a 2 s  .c  o m

    Iterable<Instance> instances = AmazonAwsUtils.toEc2Instances(reservations);

    Iterable<Instance> runningInstances = Iterables.filter(instances,
            AmazonAwsUtils.PREDICATE_RUNNING_OR_PENDING_INSTANCE);
    runningInstances = AmazonAwsUtils.awaitForEc2Instances(runningInstances, ec2);

    Map<String, Instance> runningInstancesByInstanceId = Maps.uniqueIndex(runningInstances,
            AmazonAwsFunctions.EC2_INSTANCE_TO_INSTANCE_ID);

    List<String> runningInstanceIds = newArrayList(
            Iterables.transform(runningInstances, AmazonAwsFunctions.EC2_INSTANCE_TO_INSTANCE_ID));

    List<TagDescription> tags = ec2
            .describeTags(new DescribeTagsRequest().withFilters(new Filter("resource-id", runningInstanceIds)))
            .getTags();
    Map<String, Map<String, String>> tagsByInstanceId = new MapMaker()
            .makeComputingMap(new Function<String, Map<String, String>>() {
                @Override
                public Map<String, String> apply(String instanceId) {
                    return Maps.newHashMap();
                }
            });

    for (TagDescription tag : tags) {
        tagsByInstanceId.get(tag.getResourceId()).put(tag.getKey(), tag.getValue());
    }

    Map<String, TeamInfrastructure> teamInfrastructureByTeamIdentifier = new MapMaker()
            .makeComputingMap(new Function<String, TeamInfrastructure>() {
                @Override
                public TeamInfrastructure apply(String teamIdentifier) {
                    return new TeamInfrastructure(workshopInfrastructure, teamIdentifier);
                }
            });

    Instance nexusServer = null;

    for (Map.Entry<String, Map<String, String>> entry : tagsByInstanceId.entrySet()) {
        Map<String, String> instanceTags = entry.getValue();
        String instanceId = entry.getKey();
        Instance instance = runningInstancesByInstanceId.get(instanceId);
        String teamIdentifier = instanceTags.get("TeamIdentifier");

        if (teamIdentifier == null) {

            // not a per team server (e.g. Nexus server)

        } else {

            TeamInfrastructure teamInfrastructure = teamInfrastructureByTeamIdentifier.get(teamIdentifier);
            teamInfrastructure.addInstance(instance, instanceTags);
        }
    }
    Collection<TeamInfrastructure> teamInfrastructures = teamInfrastructureByTeamIdentifier.values();
    return teamInfrastructures;
}

From source file:org.cloudifysource.esc.driver.provisioning.privateEc2.PrivateEC2CloudifyDriver.java

License:Open Source License

private String createNewName(final TagResourceType resourceType, final String prefix)
        throws CloudProvisioningException {
    String newName = null;//w w  w  . j  a  v a  2 s .com
    int attempts = 0;
    boolean foundFreeName = false;

    while (attempts < MAX_SERVERS_LIMIT) {
        // counter = (counter + 1) % MAX_SERVERS_LIMIT;
        ++attempts;

        switch (resourceType) {
        case INSTANCE:
            newName = prefix + counter.incrementAndGet();
            break;
        case VOLUME:
            newName = prefix + volumeCounter.incrementAndGet();
            break;
        default:
            // not possible
            throw new CloudProvisioningException("ResourceType not supported");
        }

        // verifying this server name is not already used
        final DescribeTagsRequest tagRequest = new DescribeTagsRequest();
        tagRequest.withFilters(new Filter("resource-type", Arrays.asList(resourceType.getValue())));
        tagRequest.withFilters(new Filter("value", Arrays.asList(newName)));
        final DescribeTagsResult describeTags = ec2.describeTags(tagRequest);
        final List<TagDescription> tags = describeTags.getTags();
        if (tags == null || tags.isEmpty()) {
            foundFreeName = true;
            break;
        }
    }

    if (!foundFreeName) {
        throw new CloudProvisioningException(
                "Number of servers has exceeded allowed server limit (" + MAX_SERVERS_LIMIT + ")");
    }
    return newName;
}

From source file:org.plukh.fluffymeow.aws.AWSInstanceInfoProviderImpl.java

License:Open Source License

@Override
public InstanceInfo getInstanceInfo() {
    if (instanceInfo == null) {
        try {// w w w  . jav a 2  s . co  m
            AmazonEC2 ec2 = new AmazonEC2Client();

            String instanceId = Request.Get("http://169.254.169.254/latest/meta-data/instance-id").execute()
                    .returnContent().asString();
            if (log.isDebugEnabled())
                log.debug("Instance Id: " + instanceId);

            DescribeTagsRequest tagsRequest = new DescribeTagsRequest().withFilters(
                    new Filter().withName("resource-id").withValues(instanceId),
                    new Filter().withName("key").withValues(NAME_TAG, DEPLOYMENT_ID_TAG));

            DescribeTagsResult tagsResult = ec2.describeTags(tagsRequest);

            String name = getTag(tagsResult, NAME_TAG);
            if (log.isDebugEnabled())
                log.debug("Instance name: " + name);

            String deploymentId = getTag(tagsResult, DEPLOYMENT_ID_TAG);
            if (log.isDebugEnabled())
                log.debug("Deployment: " + deploymentId);

            instanceInfo = new InstanceInfo().withInstanceId(instanceId).withName(name)
                    .withDeploymentId(deploymentId);
        } catch (IOException e) {
            throw new AWSInstanceInfoException("Error retrieving AWS instance info", e);
        }
    }

    return instanceInfo;
}

From source file:org.springframework.cloud.aws.core.env.ec2.AmazonEc2InstanceUserTagsFactoryBean.java

License:Apache License

@Override
protected Map<String, String> createInstance() throws Exception {
    LinkedHashMap<String, String> properties = new LinkedHashMap<>();
    DescribeTagsResult tags = this.amazonEc2.describeTags(new DescribeTagsRequest().withFilters(
            new Filter("resource-id", Collections.singletonList(this.idProvider.getCurrentInstanceId())),
            new Filter("resource-type", Collections.singletonList("instance"))));
    for (TagDescription tag : tags.getTags()) {
        properties.put(tag.getKey(), tag.getValue());
    }//from w w  w .java2 s .  co  m
    return properties;
}