Created
January 29, 2018 18:38
-
-
Save jesus-sayar/dde3e9d035860b3d103fa211a6ad346f to your computer and use it in GitHub Desktop.
Inventory for servers in Google Cloud
This file contains 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 characters
#!/usr/bin/env python | |
import requests | |
import subprocess | |
import json | |
STAGE = 'production' | |
def use_internal(instance): | |
if in_gce: | |
return True | |
return False | |
in_gce = True | |
try: | |
requests.get('http://169.254.169.254/computeMetadata/v1/',timeout=2) | |
except: | |
in_gce = False | |
groups = {} | |
instances = json.loads(subprocess.check_output(["gcloud","compute","instances","list","--format","json"])) | |
for instance in instances: | |
if STAGE not in instance['tags']['items']: | |
continue | |
for item in instance['tags']['items']: | |
if not groups.get(item): | |
groups[item] = [] | |
if use_internal(instance): | |
groups[item].append(instance['networkInterfaces'][0]['networkIP']) | |
else: | |
groups[item].append(instance['networkInterfaces'][0]['accessConfigs'][0]['natIP']) | |
print json.dumps(groups, indent=4) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment