I am deploying an AWS stack using CloudFormation. It creates an AWS EC2 instance that runs a Java application. The Java application starts and tries to access the public IP of the AWS EC2 instance. Below is my code:
String EC2_PUBLIC_IP_URL = "http://169.254.169.254/latest/meta-data/public-ipv4";
findCurrentPublicIp(DeploymentType deployment) throws IOException {
URL publicIpUrl = new URL(EC2_PUBLIC_IP_URL);
try (BufferedReader reader = new BufferedReader(new InputStreamReader(publicIpUrl.openStream()))) {
return reader.readLine(); // The only result of the request will be the public IP on one line
}
}
My implementation works fine when the region is set to eu-central, but it fails for ap-south with the following exception:
Server returned HTTP response code: 401 for URL: http://169.254.169.254/latest/meta-data/public-ipv4
at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source) ~[?:?]
at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source) ~[?:?]
at java.base/java.net.URL.openStream(Unknown Source) ~[?:?]
I am using IMDSv2 (imds-2.20.11.jar). Does the API to fetch AWS EC2 instance public IP change depending on region?
Recognized by AWS
2