Java Code Examples for com.amazonaws.util.EC2MetadataUtils#getUserData()

The following examples show how to use com.amazonaws.util.EC2MetadataUtils#getUserData() . 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: ServerInstanceContext.java    From chassis with Apache License 2.0 5 votes vote down vote up
private ServerInstanceContext(){
    amazonElasticLoadBalancing = new AmazonElasticLoadBalancingClient();
    amazonEC2 = new AmazonEC2Client();

    ec2MetadataClient = new Ec2MetadataClient() {
        @Override
        public String getAvailabilityZone() {
            return EC2MetadataUtils.getAvailabilityZone();
        }

        @Override
        public String getInstanceId() {
            return EC2MetadataUtils.getInstanceId();
        }

        @Override
        public String getUserData() {
            return EC2MetadataUtils.getUserData();
        }

        @Override
        public String getPrivateIpAddress() {
            return EC2MetadataUtils.getPrivateIpAddress();
        }

        @Override
        public String getPublicIpAddress() {
            for (EC2MetadataUtils.NetworkInterface net : EC2MetadataUtils.getNetworkInterfaces()) {
                List<String> ips = net.getPublicIPv4s();
                if (ips != null && ips.size() > 0) {
                    return ips.get(0);
                }
            }
            return null;
        }
    };

    init();
}
 
Example 2
Source File: AmazonEc2InstanceDataPropertySource.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
private Map<String, String> getUserData() {
	if (this.cachedUserData == null) {
		Map<String, String> userDataMap = new LinkedHashMap<>();
		String userData = null;
		try {
			userData = EC2MetadataUtils.getUserData();
		}
		catch (AmazonClientException e) {
			// Suppress exception if we are not able to contact the service,
			// because that is quite often the case if we run in unit tests outside
			// the environment.
			LOGGER.warn("Error getting instance user-data error message is '{}'",
					e.getMessage());
		}
		if (StringUtils.hasText(userData)) {
			String[] userDataAttributes = userData
					.split(this.userDataAttributeSeparator);
			for (String userDataAttribute : userDataAttributes) {
				String[] userDataAttributesParts = StringUtils
						.split(userDataAttribute, this.userDataValueSeparator);
				if (userDataAttributesParts != null
						&& userDataAttributesParts.length > 0) {
					String key = userDataAttributesParts[0];

					String value = null;
					if (userDataAttributesParts.length > 1) {
						value = userDataAttributesParts[1];
					}

					userDataMap.put(key, value);
				}
			}
		}
		this.cachedUserData = Collections.unmodifiableMap(userDataMap);
	}

	return this.cachedUserData;
}