1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
extern crate json;
extern crate ureq;
#[derive(Clone, Copy)]
enum MetadataUrls {
InstanceId,
AmiId,
AccountId,
AvailabilityZone,
}
impl Into<&'static str> for MetadataUrls {
fn into(self) -> &'static str {
match self {
MetadataUrls::InstanceId => "http://169.254.169.254/latest/meta-data/instance-id",
MetadataUrls::AmiId => "http://169.254.169.254/latest/meta-data/ami-id",
MetadataUrls::AccountId => {
"http://169.254.169.254/latest/meta-data/identity-credentials/ec2/info"
}
MetadataUrls::AvailabilityZone => {
"http://169.254.169.254/latest/meta-data/placement/availability-zone"
}
}
}
}
fn identity_credentials_to_account_id(ident_creds: &str) -> String {
let parsed = json::parse(ident_creds).unwrap();
parsed["AccountId"].to_string()
}
fn availability_zone_to_region(availability_zone: &str) -> Result<&'static str> {
const REGIONS: &[&str] = &[
"ap-south-1",
"eu-west-3",
"eu-north-1",
"eu-west-2",
"eu-west-1",
"ap-northeast-3",
"ap-northeast-2",
"ap-northeast-1",
"sa-east-1",
"ca-central-1",
"ap-southeast-1",
"ap-southeast-2",
"eu-central-1",
"us-east-1",
"us-east-2",
"us-west-1",
"us-west-2",
"cn-north-1",
"cn-northwest-1",
];
for region in REGIONS {
if availability_zone.starts_with(region) {
return Ok(region);
}
}
Err(Error::UnknownAvailabilityZone(
availability_zone.to_string(),
))
}
type Result<T> = std::result::Result<T, Error>;
#[derive(Clone, Debug)]
pub enum Error {
HttpRequest(String),
IoError(String),
UnknownAvailabilityZone(String),
}
impl From<ureq::Error> for Error {
fn from(error: ureq::Error) -> Error {
Error::HttpRequest(format!("{:?}", error))
}
}
impl From<std::io::Error> for Error {
fn from(error: std::io::Error) -> Error {
Error::IoError(format!("{:?}", error))
}
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
Error::HttpRequest(s) => write!(f, "Http Request Error: {}", s),
Error::IoError(s) => write!(f, "IO Error: {}", s),
Error::UnknownAvailabilityZone(s) => write!(f, "Unknown AvailabilityZone: {}", s),
}
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
None
}
}
#[derive(Debug, Default)]
pub struct InstanceMetadataClient;
impl InstanceMetadataClient {
pub fn new() -> Self {
Self {}
}
fn get_token(&self) -> Result<String> {
const TOKEN_API_URL: &str = "http://169.254.169.254/latest/api/token";
let resp = ureq::put(TOKEN_API_URL)
.set("X-aws-ec2-metadata-token-ttl-seconds", "21600")
.call();
let token = resp.into_string()?;
Ok(token)
}
pub fn get(&self) -> Result<InstanceMetadata> {
let token = self.get_token()?;
let instance_id = ureq::get(MetadataUrls::InstanceId.into())
.set("X-aws-ec2-metadata-token", &token)
.call()
.into_string()?;
let ident_creds = ureq::get(MetadataUrls::AccountId.into())
.set("X-aws-ec2-metadata-token", &token)
.call()
.into_string()?;
let account_id = identity_credentials_to_account_id(&ident_creds);
let ami_id = ureq::get(MetadataUrls::AmiId.into())
.set("X-aws-ec2-metadata-token", &token)
.call()
.into_string()?;
let availability_zone = ureq::get(MetadataUrls::AvailabilityZone.into())
.set("X-aws-ec2-metadata-token", &token)
.call()
.into_string()?;
let region = availability_zone_to_region(&availability_zone)?;
let metadata = InstanceMetadata {
region,
availability_zone,
instance_id,
account_id,
ami_id,
};
Ok(metadata)
}
}
#[derive(Debug, Clone)]
pub struct InstanceMetadata {
pub region: &'static str,
pub availability_zone: String,
pub instance_id: String,
pub account_id: String,
pub ami_id: String,
}
impl std::fmt::Display for InstanceMetadata {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{:?}", self)
}
}
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
}