Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- """..."""
- import os
- import sys
- import argparse
- import subprocess as sp
- import getpass
- from pathlib import Path
- import textwrap
- try:
- import requests
- except ImportError:
- print("Please pip3 install requests")
- sys.exit(-1)
- DEFAULT_REQUESTS_TIMEOUT = (3.05, 10)
- SCRIPTDIR = Path(__file__).parent.resolve()
- os.chdir(Path(SCRIPTDIR).parent)
- UK_TENANT = "08205459-3a7d-4db1-8983-239979359a91"
- US_TENANT = "f1aa4cec-7ed9-4c31-ab6d-780d98fef592"
- TENANT_NAMES = {
- "08205459-3a7d-4db1-8983-239979359a91": "uk",
- "f1aa4cec-7ed9-4c31-ab6d-780d98fef592": "us"}
- class BlobError(Exception):
- """For all 'normal' error conditions pertaining to blobs"""
- def get_tenant_name(tenantid):
- return TENANT_NAMES[tenantid]
- def get_terraform_storage_account_name(tenant, production=False):
- # the bash has the stupid newline bug in it (again)
- if production:
- return f"jitsuintfstate{tenant}prod"
- else:
- return f"jitsuintfstate{tenant}"
- def current_subscription_name():
- return sp.run(
- "az account show --query name -o tsv".split(),
- check=True, capture_output=True, encoding='utf-8').stdout.strip()
- def get_subscription_tenant_id(subscription):
- cmd = "az account show --subscription".split()
- cmd.append(subscription) # contains spaces
- cmd.extend("--query tenantId -o tsv".split())
- return sp.run(
- cmd, check=True, capture_output=True, encoding='utf-8').stdout.strip()
- def get_blob_access_token(
- subscription, blobstore, timeout=DEFAULT_REQUESTS_TIMEOUT):
- """Get an access token for the blob store"""
- cmd = "az account get-access-token".split()
- cmd.extend(
- f"--resource https://{blobstore}.blob.core.windows.net/".split())
- cmd.extend(["--subscription", subscription]) # white space
- cmd.extend("--query accessToken --output tsv".split())
- return sp.run(
- cmd, check=True, capture_output=True, encoding="utf-8"
- ).stdout.strip()
- def get_blob(
- blobstore, container, blobpath, token,
- timeout=DEFAULT_REQUESTS_TIMEOUT):
- """Gets a blob (without aquiring a lease)"""
- headers = {"x-ms-version": "2018-03-28"}
- if token is not None:
- headers["Authorization"] = f"Bearer {token}"
- resp = requests.get(
- f"https://{blobstore}.blob.core.windows.net/{container}/{blobpath}",
- headers=headers, timeout=timeout)
- if resp:
- return resp.text
- raise BlobError(str(resp))
- def get_valuechain_statefile(
- valuechain, subscription=None, tenantid=None, tfstateaccount=None,
- container="avid"):
- """Get the terraform valuechain state blob"""
- if subscription is None:
- subscription = current_subscription_name()
- if tenantid is None:
- tenantid = get_subscription_tenant_id(subscription)
- tenantname = get_tenant_name(tenantid)
- production = True if tenantname == 'us' else False
- if tfstateaccount is None:
- tfstateaccount = get_terraform_storage_account_name(
- tenantname, production)
- token = get_blob_access_token(subscription, tfstateaccount)
- blobpath = f"valuechains/{valuechain}/valuechain.tfstate"
- return get_blob(tfstateaccount, container, blobpath, token)
- def cmd_valuechain_tf_blob(top, opts):
- """Get value chain terraform blob"""
- blob = get_valuechain_statefile(
- opts.valuechain, subscription=opts.subscription)
- print(blob)
- def run(args=None):
- if args is None:
- args = sys.argv[1:]
- top = argparse.ArgumentParser(
- description=__doc__,
- formatter_class=argparse.ArgumentDefaultsHelpFormatter)
- top.set_defaults(func=lambda a, b: print("See sub commands in help"))
- subcmd = top.add_subparsers(title="Availalbe commands")
- user = getpass.getuser()
- top.add_argument("--subscription")
- top.add_argument("-u", "--user", default=user)
- top.add_argument(
- "-v", "--valuechain", default=f"value-chain-dev-{user}")
- p = subcmd.add_parser(
- "vc", help=cmd_valuechain_tf_blob.__doc__)
- p.set_defaults(func=cmd_valuechain_tf_blob)
- args = top.parse_args(args)
- args.func(top, args)
- if __name__ == "__main__":
- try:
- sys.exit(run())
- except sp.CalledProcessError as cpe:
- if cpe.stdout:
- print(cpe.stdout)
- print(cpe.stderr, file=sys.stderr)
- sys.exit(cpe.returncode)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement