Skip to content

Instantly share code, notes, and snippets.

@jesus-sayar
Created January 29, 2018 18:38
Show Gist options
  • Save jesus-sayar/dde3e9d035860b3d103fa211a6ad346f to your computer and use it in GitHub Desktop.
Save jesus-sayar/dde3e9d035860b3d103fa211a6ad346f to your computer and use it in GitHub Desktop.
Inventory for servers in Google Cloud
#!/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