Skip to content

Commit

Permalink
added EC2MetaData
Browse files Browse the repository at this point in the history
  • Loading branch information
wizzardo committed Jun 2, 2024
1 parent dbc0ee4 commit deb9906
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 10 deletions.
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
package com.wizzardo.tools.aws;

import com.wizzardo.tools.http.Request;
import com.wizzardo.tools.http.Response;
import com.wizzardo.tools.json.JsonTools;
import com.wizzardo.tools.misc.Unchecked;

Expand Down Expand Up @@ -45,17 +43,11 @@ static Optional<CredentialsProvider> createFromEnvironmentVariables() {

static Optional<CredentialsProvider> createFromMetaData() {
return Unchecked.ignore(() -> {
String metaDataUrl = "http://169.254.169.254/latest/meta-data/iam/security-credentials/";
Response response = new Request(metaDataUrl).get();
if (response.getResponseCode() != 200)
throw new IllegalStateException(response.asString());

String role = response.asString();
String role = EC2MetaData.get("/iam/security-credentials/");
String[] rolePath = role.split("\\n", 2);
if (rolePath.length == 0)
throw new IllegalStateException("Can parse role: " + role);

String json = new Request(metaDataUrl + rolePath[0]).get().asString();
String json = EC2MetaData.get("/iam/security-credentials/" + rolePath[0]);
AwsCredentials credentials = JsonTools.parse(json, AwsCredentials.class);
return Optional.of(() -> credentials);
}, Optional.empty());
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package com.wizzardo.tools.aws;

import com.wizzardo.tools.http.Request;
import com.wizzardo.tools.http.Response;

import java.io.IOException;

public class EC2MetaData {

public static String get(String path) throws IOException {
return get(path, 3000);
}

public static String get(String path, int timeout) throws IOException {
String url = "http://169.254.169.254/latest/meta-data" + path;
Response response = new Request(url)
.timeout(timeout)
.get();

if (response.getResponseCode() == 401) {
String token = new Request("http://169.254.169.254/latest/api/token")
.header("X-aws-ec2-metadata-token-ttl-seconds", "60")
.timeout(timeout)
.get()
.asString();

response = new Request(url)
.header("X-aws-ec2-metadata-token", token)
.timeout(timeout)
.get();
}

return response.asString();
}
}

0 comments on commit deb9906

Please sign in to comment.