| 1 |
#!/usr/bin/python3 |
| 2 |
# |
| 3 |
# Query and display EC2 metadata related to the AMI instance |
| 4 |
# Copyright (c) 2009 Canonical Ltd. (Canonical Contributor Agreement 2.5) |
| 5 |
# |
| 6 |
# Author: Alon Swartz <[email protected]> |
| 7 |
# |
| 8 |
# This program is free software; you can redistribute it and/or modify |
| 9 |
# it under the terms of the GNU General Public License as published by |
| 10 |
# the Free Software Foundation; either version 2 of the License, or |
| 11 |
# (at your option) any later version. |
| 12 |
# |
| 13 |
# This program is distributed in the hope that it will be useful, |
| 14 |
# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 15 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 16 |
# GNU General Public License for more details. |
| 17 |
# |
| 18 |
# You should have received a copy of the GNU General Public License |
| 19 |
# along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 20 |
|
| 21 |
import sys |
| 22 |
import time |
| 23 |
import getopt |
| 24 |
import socket |
| 25 |
import os |
| 26 |
|
| 27 |
try: |
| 28 |
from urllib import request as urllib_request |
| 29 |
from urllib import error as urllib_error |
| 30 |
from urllib import parse as urllib_parse |
| 31 |
except ImportError: |
| 32 |
# python2 |
| 33 |
import urllib2 as urllib_request |
| 34 |
import urllib2 as urllib_error |
| 35 |
import urlparse as urllib_parse |
| 36 |
|
| 37 |
|
| 38 |
instdata_host = "169.254.169.254" |
| 39 |
instdata_ver = "2009-04-04" |
| 40 |
instdata_url = f"http://{instdata_host}/{instdata_ver}" |
| 41 |
|
| 42 |
TOKEN_TTL_SECONDS = 21600 |
| 43 |
TOKEN_HEADER = "X-aws-ec2-metadata-token" |
| 44 |
TOKEN_HEADER_TTL = "X-aws-ec2-metadata-token-ttl-seconds" |
| 45 |
|
| 46 |
session_token_url = f"http://{instdata_host}/latest/api/token" |
| 47 |
|
| 48 |
__doc__ = f""" |
| 49 |
Query and display EC2 metadata. |
| 50 |
|
| 51 |
If no options are provided, all options will be displayed |
| 52 |
|
| 53 |
Options: |
| 54 |
-h --help show this help |
| 55 |
|
| 56 |
--kernel-id display the kernel id |
| 57 |
--ramdisk-id display the ramdisk id |
| 58 |
--reservation-id display the reservation id |
| 59 |
|
| 60 |
--ami-id display the ami id |
| 61 |
--ami-launch-index display the ami launch index |
| 62 |
--ami-manifest-path display the ami manifest path |
| 63 |
--ancestor-ami-ids display the ami ancestor id |
| 64 |
--product-codes display the ami associated product codes |
| 65 |
--availability-zone display the ami placement zone name |
| 66 |
--availability-zone-id display the ami placement zone id |
| 67 |
--region display the ami placement region name |
| 68 |
--group-name display the ami placement group name |
| 69 |
--host-id display the dedicated host id |
| 70 |
--partition-number display the partition instance was launched from |
| 71 |
|
| 72 |
--instance-id display the instance id |
| 73 |
--instance-type display the instance type |
| 74 |
|
| 75 |
--local-hostname display the local hostname |
| 76 |
--public-hostname display the public hostname |
| 77 |
|
| 78 |
--local-ipv4 display the local ipv4 ip address |
| 79 |
--public-ipv4 display the public ipv4 ip address |
| 80 |
|
| 81 |
--block-device-mapping display the block device id |
| 82 |
--security-groups display the security groups |
| 83 |
|
| 84 |
--mac display the instance mac address |
| 85 |
--profile display the instance profile |
| 86 |
--instance-action display the instance-action |
| 87 |
|
| 88 |
--public-keys display the openssh public keys |
| 89 |
--user-data display the user data (not actually metadata) |
| 90 |
|
| 91 |
-u | --url URL use URL (default: {instdata_url}) |
| 92 |
|
| 93 |
""" |
| 94 |
|
| 95 |
|
| 96 |
METAOPTS = [ |
| 97 |
"ami-id", |
| 98 |
"ami-launch-index", |
| 99 |
"ami-manifest-path", |
| 100 |
"ancestor-ami-ids", |
| 101 |
"availability-zone", |
| 102 |
"block-device-mapping", |
| 103 |
"instance-action", |
| 104 |
"instance-id", |
| 105 |
"instance-type", |
| 106 |
"local-hostname", |
| 107 |
"local-ipv4", |
| 108 |
"kernel-id", |
| 109 |
"mac", |
| 110 |
"profile", |
| 111 |
"product-codes", |
| 112 |
"public-hostname", |
| 113 |
"public-ipv4", |
| 114 |
"public-keys", |
| 115 |
"ramdisk-id", |
| 116 |
"reservation-id", |
| 117 |
"security-groups", |
| 118 |
"user-data", |
| 119 |
"availability-zone-id", |
| 120 |
"region", |
| 121 |
"host-id", |
| 122 |
"group-name", |
| 123 |
"partition-number", |
| 124 |
] |
| 125 |
|
| 126 |
binstdout = os.fdopen(sys.stdout.fileno(), "wb") |
| 127 |
|
| 128 |
|
| 129 |
def print_binary(data): |
| 130 |
if not isinstance(data, bytes): |
| 131 |
data = data.encode() |
| 132 |
binstdout.write(data) |
| 133 |
binstdout.flush() |
| 134 |
|
| 135 |
|
| 136 |
class Error(Exception): |
| 137 |
pass |
| 138 |
|
| 139 |
|
| 140 |
class EC2Metadata: # pylint: disable=R0903 |
| 141 |
"""Class for querying metadata from EC2""" |
| 142 |
|
| 143 |
def __init__(self, burl=instdata_url): |
| 144 |
self.burl = burl |
| 145 |
|
| 146 |
s = urllib_parse.urlsplit(burl) |
| 147 |
addr = s.netloc.split(":")[0] |
| 148 |
port = s.port |
| 149 |
if s.port is None: |
| 150 |
port = 80 |
| 151 |
if not self._test_connectivity(addr, port): |
| 152 |
raise Error(f"could not establish connection to: {addr}:{port}") |
| 153 |
self._imdsv2_ensure_token() |
| 154 |
|
| 155 |
@staticmethod |
| 156 |
def _test_connectivity(addr, port): |
| 157 |
for _ in range(6): |
| 158 |
s = socket.socket() |
| 159 |
try: |
| 160 |
s.connect((addr, port)) |
| 161 |
s.close() |
| 162 |
return True |
| 163 |
except socket.error: |
| 164 |
time.sleep(1) |
| 165 |
|
| 166 |
return False |
| 167 |
|
| 168 |
def _imdsv2_ensure_token(self): |
| 169 |
# Get IMDSv2 session token |
| 170 |
request = urllib_request.Request( |
| 171 |
session_token_url, |
| 172 |
method="PUT", |
| 173 |
headers={TOKEN_HEADER_TTL: TOKEN_TTL_SECONDS}, |
| 174 |
) |
| 175 |
resp = urllib_request.urlopen(request) |
| 176 |
self.session_token = resp.read() |
| 177 |
|
| 178 |
def _get(self, uri, decode=True): |
| 179 |
url = f"{self.burl}/{uri}" |
| 180 |
try: |
| 181 |
resp = urllib_request.urlopen( |
| 182 |
urllib_request.Request(url, headers={TOKEN_HEADER: self.session_token}) |
| 183 |
) |
| 184 |
value = resp.read() |
| 185 |
if decode: |
| 186 |
value = value.decode() |
| 187 |
except urllib_error.HTTPError as e: |
| 188 |
if e.code == 404: |
| 189 |
return None |
| 190 |
# Eucalyptus may raise a 500 (Internal Server Error) |
| 191 |
if e.code == 500: |
| 192 |
return None |
| 193 |
raise |
| 194 |
|
| 195 |
return value |
| 196 |
|
| 197 |
def get(self, metaopt): |
| 198 |
"""return value of metaopt""" |
| 199 |
|
| 200 |
if metaopt not in METAOPTS: |
| 201 |
raise Error("unknown metaopt", metaopt, METAOPTS) |
| 202 |
|
| 203 |
if metaopt in [ |
| 204 |
"availability-zone", |
| 205 |
"availability-zone-id", |
| 206 |
"region", |
| 207 |
"host-id", |
| 208 |
"group-name", |
| 209 |
"partition-number", |
| 210 |
]: |
| 211 |
return self._get("meta-data/placement/" + metaopt) |
| 212 |
|
| 213 |
if metaopt == "public-keys": |
| 214 |
data = self._get("meta-data/public-keys") |
| 215 |
if data is None: |
| 216 |
return None |
| 217 |
|
| 218 |
keyids = [line.split("=")[0] for line in data.splitlines()] |
| 219 |
|
| 220 |
public_keys = [] |
| 221 |
for keyid in keyids: |
| 222 |
uri = f"meta-data/public-keys/{int(keyid)}/openssh-key" |
| 223 |
public_keys.append(self._get(uri).rstrip()) |
| 224 |
|
| 225 |
return public_keys |
| 226 |
|
| 227 |
if metaopt == "user-data": |
| 228 |
return self._get("user-data", decode=False) |
| 229 |
|
| 230 |
return self._get("meta-data/" + metaopt) |
| 231 |
|
| 232 |
|
| 233 |
def get(metaopt): |
| 234 |
"""primitive: return value of metaopt""" |
| 235 |
|
| 236 |
m = EC2Metadata() |
| 237 |
return m.get(metaopt) |
| 238 |
|
| 239 |
|
| 240 |
def display(metaopts, burl, prefix=False): |
| 241 |
"""primitive: display metaopts (list) values with optional prefix""" |
| 242 |
|
| 243 |
m = EC2Metadata(burl) |
| 244 |
for metaopt in metaopts: |
| 245 |
value = m.get(metaopt) |
| 246 |
if not value: |
| 247 |
value = "unavailable" |
| 248 |
|
| 249 |
if prefix: |
| 250 |
print(f"{metaopt}: {value}") |
| 251 |
elif metaopt == "user-data": |
| 252 |
# We want to avoid binary blob corruption while printing as string |
| 253 |
print_binary(value) |
| 254 |
else: |
| 255 |
print(value) |
| 256 |
|
| 257 |
|
| 258 |
def usage(s=None): |
| 259 |
"""display usage and exit""" |
| 260 |
|
| 261 |
msg = "" |
| 262 |
if s: |
| 263 |
msg = f"Error: {s}\n" |
| 264 |
msg += f"Syntax: {sys.argv[0]} [options]\n" |
| 265 |
msg += __doc__ |
| 266 |
sys.stderr.write(msg + "\n") |
| 267 |
sys.exit(1) |
| 268 |
|
| 269 |
|
| 270 |
def main(): |
| 271 |
"""handle cli options""" |
| 272 |
|
| 273 |
try: |
| 274 |
getopt_metaopts = METAOPTS[:] |
| 275 |
getopt_metaopts.append("help") |
| 276 |
getopt_metaopts.append("url=") |
| 277 |
opts, _ = getopt.gnu_getopt(sys.argv[1:], "hu:", getopt_metaopts) |
| 278 |
except getopt.GetoptError as e: |
| 279 |
usage(e) |
| 280 |
|
| 281 |
burl = instdata_url |
| 282 |
|
| 283 |
metaopts = [] |
| 284 |
prefix = False |
| 285 |
for opt, val in opts: |
| 286 |
if opt in ("-h", "--help"): |
| 287 |
usage() |
| 288 |
if opt in ("-u", "--url"): |
| 289 |
burl = val |
| 290 |
continue |
| 291 |
|
| 292 |
metaopts.append(opt.replace("--", "")) |
| 293 |
|
| 294 |
if len(metaopts) == 0: |
| 295 |
prefix = True |
| 296 |
metaopts = METAOPTS |
| 297 |
|
| 298 |
display(metaopts, burl, prefix) |
| 299 |
|
| 300 |
|
| 301 |
if __name__ == "__main__": |
| 302 |
main() |
| 303 |
|
| 304 |
# vi: ts=4 expandtab |