Skip to content

Instantly share code, notes, and snippets.

@Scarysize
Last active March 13, 2018 14:00
Show Gist options
  • Save Scarysize/9f42c558a91d50cf9caa2636bc90d95d to your computer and use it in GitHub Desktop.
Save Scarysize/9f42c558a91d50cf9caa2636bc90d95d to your computer and use it in GitHub Desktop.
Run 'gcloud' commands and look for a "gcloud.yaml" file relative to the command to automatically set the commands project id
#!/usr/bin/env python
import re
from pathlib import Path
from subprocess import call
from sys import argv
from yaml import load, YAMLError
config_file_path = Path("gcloud.yaml")
def project_is_defined(args):
for arg in args:
if re.match('--project=.*', arg):
return True
return False
def get_config():
with open("gcloud.yaml", 'r') as stream:
try:
config = load(stream)
return config
except YAMLError as exc:
print(exc)
return None
def get_project_id(config):
try:
project_id = config['project-id']
return project_id
except KeyError:
return None
def exec_command():
del argv[0]
arguments = argv
def pass_through():
call(["gcloud"] + arguments)
exit
if not config_file_path.is_file() or project_is_defined(arguments):
pass_through()
config = get_config()
if not config:
pass_through()
project_id = get_project_id(config)
if not project_id:
pass_through()
print(f"Selected project: {project_id}")
call(["gcloud", f"--project={project_id}"] + arguments)
exec_command()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment