Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright 2013-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
   *
   * Licensed under the Apache License, Version 2.0 (the "License").
   * You may not use this file except in compliance with the License.
   * A copy of the License is located at
   *
   *  http://aws.amazon.com/apache2.0
   *
  * or in the "license" file accompanying this file. This file is distributed
  * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
  * express or implied. See the License for the specific language governing
  * permissions and limitations under the License.
  */
 package com.amazonaws.util;
 
 import java.util.List;
 import java.util.Map;
 
 
Utility class for retrieving Amazon EC2 instance metadata.
You can use the data to build more generic AMIs that can be modified by configuration files supplied at launch time. For example, if you run web servers for various small businesses, they can all use the same AMI and retrieve their content from the Amazon S3 bucket you specify at launch. To add a new customer at any time, simply create a bucket for the customer, add their content, and launch your AMI.
More information about Amazon EC2 Metadata

See also:
Amazon EC2 User Guide: Instance Metadata
 
 public class EC2MetadataUtils {
 
     private static final String REGION = "region";
     private static final String INSTANCE_IDENTITY_DOCUMENT = "instance-identity/document";
     private static final String EC2_METADATA_ROOT = "/latest/meta-data";
     private static final String EC2_USERDATA_ROOT = "/latest/user-data/";
     private static final String EC2_DYNAMICDATA_ROOT = "/latest/dynamic/";
 
     private static final int DEFAULT_QUERY_RETRIES = 3;
     private static final int MINIMUM_RETRY_WAIT_TIME_MILLISECONDS = 250;
     private static Map<StringStringcache = new ConcurrentHashMap<StringString>();
     private static EC2MetadataClient ec2MetadataClient = new EC2MetadataClient();
 
     private static final ObjectMapper mapper = new ObjectMapper();
     static {
         .configure(
                 .false);
 
         
     }
 
     private static final Log log = LogFactory.getLog(EC2MetadataUtils.class);

    
Get the AMI ID used to launch the instance.
 
     public static String getAmiId() {
         return fetchData( + "/ami-id");
     }

    
Get the index of this instance in the reservation.
 
     public static String getAmiLaunchIndex() {
         return fetchData( + "/ami-launch-index");
     }

    
Get the manifest path of the AMI with which the instance was launched.
 
     public static String getAmiManifestPath() {
         return fetchData( + "/ami-manifest-path");
     }

    
Get the list of AMI IDs of any instances that were rebundled to created this AMI. Will only exist if the AMI manifest file contained an ancestor-amis key.
    public static List<StringgetAncestorAmiIds() {
        return getItems( + "/ancestor-ami-ids");
    }

    
Notifies the instance that it should reboot in preparation for bundling. Valid values: none | shutdown | bundle-pending.
    public static String getInstanceAction() {
        return fetchData( + "/instance-action");
    }

    
Get the ID of this instance.
    public static String getInstanceId() {
        return fetchData( + "/instance-id");
    }

    
Get the type of the instance.
    public static String getInstanceType() {
        return fetchData( + "/instance-type");
    }

    
Get the local hostname of the instance. In cases where multiple network interfaces are present, this refers to the eth0 device (the device for which device-number is 0).
    public static String getLocalHostName() {
        return fetchData( + "/local-hostname");
    }

    
Get the MAC address of the instance. In cases where multiple network interfaces are present, this refers to the eth0 device (the device for which device-number is 0).
    public static String getMacAddress() {
        return fetchData( + "/mac");
    }

    
Get the private IP address of the instance. In cases where multiple network interfaces are present, this refers to the eth0 device (the device for which device-number is 0).
    public static String getPrivateIpAddress() {
        return fetchData( + "/local-ipv4");
    }

    
Get the Availability Zone in which the instance launched.
    public static String getAvailabilityZone() {
        return fetchData( + "/placement/availability-zone");
    }

    
Get the list of product codes associated with the instance, if any.
    public static List<StringgetProductCodes() {
        return getItems( + "/product-codes");
    }

    
Get the public key. Only available if supplied at instance launch time.
    public static String getPublicKey() {
        return fetchData( + "/public-keys/0/openssh-key");
    }

    
Get the ID of the RAM disk specified at launch time, if applicable.
    public static String getRamdiskId() {
        return fetchData( + "/ramdisk-id");
    }

    
Get the ID of the reservation.
    public static String getReservationId() {
        return fetchData( + "/reservation-id");
    }

    
Get the list of names of the security groups applied to the instance.
    public static List<StringgetSecurityGroups() {
        return getItems( + "/security-groups");
    }

    
Get information about the last time the instance profile was updated, including the instance's LastUpdated date, InstanceProfileArn, and InstanceProfileId.
    public static IAMInfo getIAMInstanceProfileInfo() {
        String json = getData( + "/iam/info");
        if (null == json) {
            return null;
        }
        try {
            return .readValue(jsonIAMInfo.class);
        } catch (Exception e) {
            .warn("Unable to parse IAM Instance profile info (" + json
                    + "): " + e.getMessage(), e);
            return null;
        }
    }

    
The instance info is only guaranteed to be a JSON document per http://docs .aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html

This method is only a best attempt to capture the instance info as a typed object.

Get an InstanceInfo object with dynamic information about this instance.

    public static InstanceInfo getInstanceInfo() {
        return doGetInstanceInfo(getData(
                 + ));
    }
    static InstanceInfo doGetInstanceInfo(String json) {
        if (null != json) {
            try {
                InstanceInfo instanceInfo = Jackson.fromJsonString(json,
                        InstanceInfo.class);
                return instanceInfo;
            } catch (Exception e) {
                .warn("Unable to parse dynamic EC2 instance info (" + json
                        + ") : " + e.getMessage(), e);
            }
        }
        return null;
    }

    
Returns the current region of this running EC2 instance; or null if it is unable to do so. The method avoids interpreting other parts of the instance info JSON document to minimize potential failure.

The instance info is only guaranteed to be a JSON document per http://docs .aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html

    public static String getEC2InstanceRegion() {
        return doGetEC2InstanceRegion(getData(
                 + ));
    }
    static String doGetEC2InstanceRegion(final String json) {
        if (null != json) {
            try {
                JsonNode node = .readTree(json.getBytes(.));
                JsonNode region = node.findValue();
                return region.asText();
            } catch (Exception e) {
                .warn("Unable to parse EC2 instance info (" + json
                        + ") : " + e.getMessage(), e);
            }
        }
        return null;
    }

    
Returns the temporary security credentials (AccessKeyId, SecretAccessKey, SessionToken, and Expiration) associated with the IAM roles on the instance.
        Map<StringIAMSecurityCredentialcredentialsInfoMap = new HashMap<StringIAMSecurityCredential>();
        List<Stringcredentials = getItems(
                + "/iam/security-credentials");
        if (null != credentials) {
            for (String credential : credentials) {
                String json = getData(
                        + "/iam/security-credentials/" + credential);
                try {
                    IAMSecurityCredential credentialInfo = 
                            .readValue(jsonIAMSecurityCredential.class);
                    credentialsInfoMap.put(credentialcredentialInfo);
                } catch (Exception e) {
                    .warn("Unable to process the credential (" + credential
                            + "). " + e.getMessage(), e);
                }
            }
        }
        return credentialsInfoMap;
    }

    
Get the virtual devices associated with the ami, root, ebs, and swap.
    public static Map<StringStringgetBlockDeviceMapping() {
        Map<StringStringblockDeviceMapping = new HashMap<StringString>();
        List<Stringdevices = getItems(
                + "/block-device-mapping");
        for (String device : devices) {
            blockDeviceMapping.put(devicegetData(
                    + "/block-device-mapping/" + device));
        }
        return blockDeviceMapping;
    }

    
Get the list of network interfaces on the instance.
    public static List<NetworkInterfacegetNetworkInterfaces() {
        List<NetworkInterfacenetworkInterfaces = new LinkedList<NetworkInterface>();
        List<Stringmacs = getItems(
                + "/network/interfaces/macs/");
        for (String mac : macs) {
            String key = mac.trim();
            if (key.endsWith("/"))
                key = key.substring(0, key.length() - 1);
            networkInterfaces.add(new NetworkInterface(key));
        }
        return networkInterfaces;
    }

    
Get the metadata sent to the instance
    public static String getUserData() {
        return getData();
    }
    public static String getData(String path) {
        return getData(path);
    }
    public static String getData(String pathint tries) {
        List<Stringitems = getItems(pathtriestrue);
        if (null != items && items.size() > 0)
            return items.get(0);
        return null;
    }
    public static List<StringgetItems(String path) {
        return getItems(pathfalse);
    }
    public static List<StringgetItems(String pathint tries) {
        return getItems(pathtriesfalse);
    }
    private static List<StringgetItems(String pathint triesboolean slurp) {
        if (tries == 0)
            throw new AmazonClientException(
                    "Unable to contact EC2 metadata service.");
        List<Stringitems;
        try {
            String response = .readResource(path);
            if (slurp)
                items = Collections.singletonList(response);
            else
                items = Arrays.asList(response.split("\n"));
            return items;
        } catch (AmazonClientException ace) {
            .warn("Unable to retrieve the requested metadata.");
            return null;
        } catch (Exception e) {
            // Retry on any other exceptions
            int pause = (int) (Math.pow(2,  - tries) * );
            try {
                Thread.sleep(pause <  ? 
                        : pause);
            } catch (InterruptedException e1) {
                Thread.currentThread().interrupt();
            }
            return getItems(pathtries - 1, slurp);
        }
    }
    private static String fetchData(String path) {
        return fetchData(pathfalse);
    }
    private static String fetchData(String pathboolean force) {
        try {
            if (force || !.containsKey(path))
                .put(pathgetData(path));
            return .get(path);
        } catch (Exception e) {
            return null;
        }
    }

    
Information about the last time the instance profile was updated, including the instance's LastUpdated date, InstanceProfileArn, and InstanceProfileId.
    public static class IAMInfo {
        public String code;
        public String message;
        public String lastUpdated;
        public String instanceProfileArn;
        public String instanceProfileId;
    }

    
The temporary security credentials (AccessKeyId, SecretAccessKey, SessionToken, and Expiration) associated with the IAM role.
    public static class IAMSecurityCredential {
        public String code;
        public String message;
        public String lastUpdated;
        public String type;
        public String accessKeyId;
        public String secretAccessKey;
        public String token;
        public String expiration;

        

Deprecated:
because it is spelled incorrectly
See also:
accessKeyId
        @Deprecated
        public String secretAcessKey;
    }

    
This POJO is a best attempt to capture the instance info which is only guaranteed to be a JSON document per http://docs.aws.amazon.com/AWSEC2/latest /UserGuide/ec2-instance-metadata.html Instance info includes dynamic information about the current instance such as region, instanceId, private IP address, etc.
    public static class InstanceInfo {
        private final String pendingTime;
        private final String instanceType;
        private final String imageId;
        private final String instanceId;
        private final String[] billingProducts;
        private final String architecture;
        private final String accountId;
        private final String kernelId;
        private final String ramdiskId;
        private final String region;
        private final String version;
        private final String availabilityZone;
        private final String privateIp;
        private final String[] devpayProductCodes;
        @JsonCreator
        public InstanceInfo(
                @JsonProperty(value = "pendingTime", required = trueString pendingTime,
                @JsonProperty(value = "instanceType", required = trueString instanceType,
                @JsonProperty(value = "imageId", required = trueString imageId,
                @JsonProperty(value = "instanceId", required = trueString instanceId,
                @JsonProperty(value = "billingProducts", required = falseString[] billingProducts,
                @JsonProperty(value = "architecture", required = trueString architecture,
                @JsonProperty(value = "accountId", required = trueString accountId,
                @JsonProperty(value = "kernelId", required = trueString kernelId,
                @JsonProperty(value = "ramdiskId", required = falseString ramdiskId,
                @JsonProperty(value = , required = trueString region,
                @JsonProperty(value = "version", required = trueString version,
                @JsonProperty(value = "availabilityZone", required = trueString availabilityZone,
                @JsonProperty(value = "privateIp", required = trueString privateIp,
                @JsonProperty(value = "devpayProductCodes", required = falseString[] devpayProductCodes) {
            this. = pendingTime;
            this. = instanceType;
            this. = imageId;
            this. = instanceId;
            this. = billingProducts == null
                    ? null : billingProducts.clone();
            this. = architecture;
            this. = accountId;
            this. = kernelId;
            this. = ramdiskId;
            this. = region;
            this. = version;
            this. = availabilityZone;
            this. = privateIp;
            this. = devpayProductCodes == null
                    ? null : devpayProductCodes.clone();
        }
        public String getPendingTime() {
            return ;
        }
        public String getInstanceType() {
            return ;
        }
        public String getImageId() {
            return ;
        }
        public String getInstanceId() {
            return ;
        }
        public String[] getBillingProducts() {
            return  == null ? null : .clone();
        }
        public String getArchitecture() {
            return ;
        }
        public String getAccountId() {
            return ;
        }
        public String getKernelId() {
            return ;
        }
        public String getRamdiskId() {
            return ;
        }
        public String getRegion() {
            return ;
        }
        public String getVersion() {
            return ;
        }
        public String getAvailabilityZone() {
            return ;
        }
        public String getPrivateIp() {
            return ;
        }
        public String[] getDevpayProductCodes() {
            return  == null ? null : .clone();
        }
    }

    
All of the metada associated with a network interface on the instance.
    public static class NetworkInterface {
        private String path;
        private String mac;
        private List<StringavailableKeys;
        private Map<StringStringdata = new HashMap<StringString>();
        public NetworkInterface(String macAddress) {
             = macAddress;
             = "/network/interfaces/macs/" +  + "/";
        }

        
The interface's Media Acess Control (mac) address
        public String getMacAddress() {
            return ;
        }

        
The ID of the owner of the network interface.
In multiple-interface environments, an interface can be attached by a third party, such as Elastic Load Balancing. Traffic on an interface is always billed to the interface owner.
        public String getOwnerId() {
            return getData("owner-id");
        }

        
The interface's profile.
        public String getProfile() {
            return getData("profile");
        }

        
The interface's local hostname.
        public String getHostname() {
            return getData("local-hostname");
        }

        
The private IP addresses associated with the interface.
        public List<StringgetLocalIPv4s() {
            return getItems("local-ipv4s");
        }

        
The interface's public hostname.
        public String getPublicHostname() {
            return getData("public-hostname");
        }

        
The elastic IP addresses associated with the interface.
There may be multiple IP addresses on an instance.
        public List<StringgetPublicIPv4s() {
            return getItems("public-ipv4s");
        }

        
Security groups to which the network interface belongs.
        public List<StringgetSecurityGroups() {
            return getItems("security-groups");
        }

        
IDs of the security groups to which the network interface belongs. Returned only for Amazon EC2 instances launched into a VPC.
        public List<StringgetSecurityGroupIds() {
            return getItems("security-group-ids");
        }

        
The CIDR block of the Amazon EC2-VPC subnet in which the interface resides.
Returned only for Amazon EC2 instances launched into a VPC.
        public String getSubnetIPv4CidrBlock() {
            return getData("subnet-ipv4-cidr-block");
        }

        
ID of the subnet in which the interface resides.
Returned only for Amazon EC2 instances launched into a VPC.
         public String getSubnetId() {
             return getData("subnet-id");
         }

        
The CIDR block of the Amazon EC2-VPC in which the interface resides.
Returned only for Amazon EC2 instances launched into a VPC.
         public String getVpcIPv4CidrBlock() {
             return getData("vpc-ipv4-cidr-block");
         }

        
ID of the Amazon EC2-VPC in which the interface resides.
Returned only for Amazon EC2 instances launched into a VPC.
        public String getVpcId() {
            return getData("vpc-id");
        }

        
Get the private IPv4 address(es) that are associated with the public-ip address and assigned to that interface.

Parameters:
publicIp The public IP address
Returns:
Private IPv4 address(es) associated with the public IP address.
        public List<StringgetIPv4Association(String publicIp) {
            return EC2MetadataUtils.getItems( + 
                    + "ipv4-associations/" + publicIp);
        }
        private String getData(String key) {
            if (.containsKey(key))
                return .get(key);
            // Since the keys are variable, cache a list of which ones are
            // available
            // to prevent unnecessary trips to the service.
            if (null == )
                 = EC2MetadataUtils.getItems(
                        + );
            if (.contains(key)) {
                .put(key, EC2MetadataUtils.getData( + 
                        + key));
                return .get(key);
            } else
                return null;
        }
        private List<StringgetItems(String key) {
            if (null == )
                 = EC2MetadataUtils.getItems(
                        + );
            if (.contains(key))
                return EC2MetadataUtils
                        .getItems( +  + key);
            else
                return new LinkedList<String>();
        }
    }
New to GrepCode? Check out our FAQ X