Example usage for com.amazonaws.services.ec2.model TagDescription getKey

List of usage examples for com.amazonaws.services.ec2.model TagDescription getKey

Introduction

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

Prototype


public String getKey() 

Source Link

Document

The tag key.

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 {//w w w .j  a v a 2  s . co m
        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:fr.xebia.demo.amazon.aws.AmazonAwsShutdowner.java

License:Apache License

public void test() {
    String ownerId = "self";

    boolean dryRun = true;

    // RETRIEVE TAGS
    Map<String, Map<String, String>> tagsByResourceId = new MapMaker()
            .makeComputingMap(new Function<String, Map<String, String>>() {
                @Override//ww  w  . j  a v a  2 s .  com
                public Map<String, String> apply(String input) {
                    return Maps.newHashMap();
                }
            });

    for (TagDescription tagDescription : ec2.describeTags().getTags()) {
        tagsByResourceId.get(tagDescription.getResourceId()).put(tagDescription.getKey(),
                tagDescription.getValue());
    }

    // RDS INSTANCEs
    for (DBInstance dbInstance : rds.describeDBInstances().getDBInstances()) {
        Map<String, String> instanceTags = tagsByResourceId.get(dbInstance.getDBInstanceIdentifier());
        logger.debug("Tags for " + dbInstance + ": " + instanceTags);

    }

    // EC2 INSTANCES
    List<Instance> instancesAlreadyNotStarted = Lists.newArrayList();
    List<Instance> instancesToStop = Lists.newArrayList();
    List<Instance> instancesToTerminate = Lists.newArrayList();
    List<Instance> instancesToKeepUnchanged = Lists.newArrayList();
    for (Reservation reservation : ec2.describeInstances().getReservations()) {
        for (Instance instance : reservation.getInstances()) {
            Map<String, String> instanceTags = tagsByResourceId.get(instance.getInstanceId());
            logger.debug("Tags for {}: {}", instance, instanceTags);
            if ("terminated".equals(instance.getState().getName())) {
                instancesToKeepUnchanged.add(instance);
            } else if (instanceTags.containsKey(TAG_DO_NOT_STOP)) {
                instancesToKeepUnchanged.add(instance);
            } else if (instanceTags.containsKey(TAG_DO_NOT_TERMINATE)) {
                if ("started".equals(instance.getState().getName())) {
                    instancesToStop.add(instance);
                } else {
                    instancesAlreadyNotStarted.add(instance);
                }
            } else {
                instancesToTerminate.add(instance);
            }
        }
    }
    System.out.println("EC2 INSTANCES");
    if (dryRun) {
        System.out.println("DRY RUN Terminate:" + instancesToTerminate);
        System.out.println("DRY RUN Stop:" + instancesToStop);
        System.out.println("DRY RUN No need to stop:" + instancesAlreadyNotStarted);
        System.out.println("DRY RUN Keep unchanged:" + instancesToKeepUnchanged);
    } else {
        System.out.println("Terminate:" + instancesToTerminate);
        if (!instancesToTerminate.isEmpty()) {
            ec2.terminateInstances(new TerminateInstancesRequest(
                    Lists.transform(instancesToTerminate, TO_INSTANCE_ID_FUNCTION)));
        }
        System.out.println("Stop:" + instancesToStop);
        if (!instancesToStop.isEmpty()) {
            ec2.stopInstances(
                    new StopInstancesRequest(Lists.transform(instancesToStop, TO_INSTANCE_ID_FUNCTION)));
        }
        System.out.println("No need to stop:" + instancesAlreadyNotStarted);
        System.out.println("Keep unchanged:" + instancesToKeepUnchanged);
    }

    // AMIs
    System.out.println("AMIs");
    List<Image> imagesToDeRegister = Lists.newArrayList();
    List<Image> imagesToKeep = Lists.newArrayList();
    for (Image image : ec2.describeImages(new DescribeImagesRequest().withOwners(ownerId)).getImages()) {
        Map<String, String> imageTags = tagsByResourceId.get(image.getImageId());
        logger.debug("Tags for {}: {}", image, imageTags);
        if (imageTags.containsKey(TAG_DO_NOT_DEREGISTER)) {
            imagesToKeep.add(image);
        } else {
            imagesToDeRegister.add(image);
        }
    }
    if (dryRun) {
        System.out.println("DRY RUN Deregister:" + imagesToDeRegister);
        System.out.println("DRY RUN Keep:" + imagesToKeep);

    } else {
        System.out.println("Deregister:" + imagesToDeRegister);
        for (Image image : imagesToDeRegister) {
            ec2.deregisterImage(new DeregisterImageRequest(image.getImageId()));
        }
        System.out.println("Keep:" + imagesToKeep);
    }

    List<String> imageIdsToKeep = Lists.transform(imagesToKeep, TO_IMAGE_ID_FUNCTION);

    // SNAPSHOTS
    System.out.println("SNAPSHOTs");
    for (Snapshot snapshot : ec2.describeSnapshots(new DescribeSnapshotsRequest().withOwnerIds(ownerId))
            .getSnapshots()) {

        if (snapshot.getDescription().contains("Created by CreateImage")) {
            boolean associatedWithAnImageToKeep = false;
            for (String imageIdToKeep : imageIdsToKeep) {
                if (snapshot.getDescription().contains(imageIdToKeep)) {
                    associatedWithAnImageToKeep = true;
                    break;
                }
            }
            if (associatedWithAnImageToKeep) {
                System.out.println("Keep: " + snapshot);
            } else {
                if (dryRun) {
                    System.out.println("DRY RUN delete: " + snapshot);
                } else {
                    System.out.println("Delete: " + snapshot);
                    ec2.deleteSnapshot(new DeleteSnapshotRequest(snapshot.getSnapshotId()));
                }
            }
        }
    }
    // ELASTIC LOAD BALANCERs
    // no tags on elb
}

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 ww . ja  va2  s  .com
    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  w  w .j a v 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 = 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();/*from  www  .j av  a2 s .  c om*/

    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.plukh.fluffymeow.aws.AWSInstanceInfoProviderImpl.java

License:Open Source License

private String getTag(DescribeTagsResult tagsResult, String tagName) {
    for (TagDescription tag : tagsResult.getTags()) {
        if (tag.getKey().equals(tagName))
            return tag.getValue();
    }//from w w w . jav a 2 s .  co m
    return null;
}

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 ww w  .  java  2s .com
    return properties;
}