Created
February 29, 2024 06:18
-
-
Save xluffy/912127c03298a6ca2ff090a3d11e3daa to your computer and use it in GitHub Desktop.
Revisions
-
xluffy created this gist
Feb 29, 2024 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,72 @@ #!/usr/bin/python3 # # Query and display GCE metadata, clone from ec2metadata.py # from urllib import request as urllib_request metadata_url = "http://metadata.google.internal/computeMetadata/v1/instance/" METAOPTS = ["cpu-platform", "machine-type", "service-accounts", "tags", "zone"] class Error(Exception): pass def _get(uri, decode=True): url = "%s/%s" % (metadata_url, uri) request = urllib_request.Request(url) request.add_header("Metadata-Flavor", "Google") resp = urllib_request.urlopen(request) value = resp.read() if decode: value = value.decode() return value def get(metaopt): """ Return value of metaops """ if metaopt not in METAOPTS: raise Error("Unknow metaopt", metaopt, METAOPTS) if metaopt == "service-accounts": return _get("service-accounts/default/email") if metaopt in ["machine-type", "zone"]: return _get(metaopt, True).split("/")[-1] return _get(metaopt) def display(metaopts, prefix=True): """ Display metaopts (list) values in optional prefix """ for metaopt in metaopts: value = get(metaopt) if not value: value = "unavailable" if prefix: print("%s: %s" % (metaopt, value)) else: print(value) def main(): display(METAOPTS) if __name__ == "__main__": main()