|
| 1 | +from utils import build_client, wait_for_active |
| 2 | +from googleapiclient.errors import HttpError |
| 3 | +import httplib2 |
| 4 | +import random |
| 5 | +import argparse |
| 6 | +import json |
| 7 | + |
| 8 | +def create_project(name, id, **labels): |
| 9 | + return client.projects().create(body={ |
| 10 | + 'projectId': pid_candidate, |
| 11 | + 'name': name |
| 12 | + 'labels': labels |
| 13 | + }).execute() |
| 14 | + |
| 15 | + |
| 16 | +def run(name, id=None, **labels): |
| 17 | + project = None |
| 18 | + if id is None: |
| 19 | + while project is None: |
| 20 | + id = "{}-{}-{}".format(*rw.random_words(count=2), random.randint(100, 999))[:30] |
| 21 | + try: |
| 22 | + project = create_project(client, name, id, **labels) |
| 23 | + except HttpError as e: |
| 24 | + code, uri, reason = str(e).parse('<HttpError %s when requesting %s returned "%s">') |
| 25 | + if not reason=="Requested entity already exists": |
| 26 | + raise e |
| 27 | + else: |
| 28 | + project = create_project(client, name, id, **labels) |
| 29 | + |
| 30 | + return wait_for_active(project) |
| 31 | + |
| 32 | +parser = argparse.ArgumentParser(description='Create a Google Cloud Project') |
| 33 | +parser.add_argument('--name', type=str, help='Human readable name of the project', required=True) |
| 34 | +parser.add_argument('--id', type=str, help='Unique ID of the project. Max 30 Characters. Only hyphens, digits, and lower case letters. Leave blank to have a memorable string generated for you') |
| 35 | +parser.add_argument('--labels', type=json.loads, help='Json formatted dictionary of labels to apply to the project') |
| 36 | + |
| 37 | +if __name__=='__main__': |
| 38 | + args = parser.parse_args() |
| 39 | + if args.labels: |
| 40 | + run(args.name, id=args.id, **args.labels) |
| 41 | + else: |
| 42 | + run(args.name, id=args.id) |
0 commit comments