Guest User

Untitled

a guest
Jul 15th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.71 KB | None | 0 0
  1. import subprocess
  2. import json
  3. import shlex
  4.  
  5. output = []
  6. output_row = []
  7. header_row = "project_id,name,labels-app-name,labels-biz-unit,labels-env-name,metadata-server-role,metadata-server-type,metadata-os-image"
  8.  
  9. # Execute the gcloud command to get a list of projects in json format
  10. # and load data in JSON format for further processing
  11. project_list_command = "gcloud projects list --format json"
  12. project_output = subprocess.check_output(shlex.split(project_list_command))
  13. project_output_json = json.loads(project_output)
  14.  
  15. # For each project id in the list, get the instance details and load in JSON information
  16. for project_row in project_output_json:
  17. instance_list_command = "gcloud compute instances list --format json --project "+ project_row["projectId"]
  18. instance_output_josn = json.loads(subprocess.check_output(shlex.split(instance_list_command)))
  19. # For every instance in the list get the labels and metadata
  20. for instance_row in instance_output_josn:
  21. output_row = []
  22. metadata_dict = {}
  23. output_row.append(project_row["projectId"]) # Add project id to the begining of the output row
  24. output_row.extend([instance_row["name"],instance_row["labels"]["app-name"],instance_row["labels"]["biz-unit"],instance_row["labels"]["env-name"]])
  25. for metadata_entry in instance_row["metadata"]["items"]: #Metadata is nested field so would need further processing
  26. metadata_dict[metadata_entry['key']] = metadata_entry['value']
  27. output_row.extend([metadata_dict['server-role'], metadata_dict['server-type'], metadata_dict['os-image']])
  28. output.append(output_row)
  29.  
  30. # Print the header row and the instance data rows to stdout
  31. print header_row
  32. for row in output:
  33. print ','.join(row)
Add Comment
Please, Sign In to add comment