Advertisement
Guest User

Untitled

a guest
Feb 18th, 2020
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.47 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. """..."""
  3.  
  4. import os
  5. import sys
  6. import argparse
  7. import subprocess as sp
  8. import getpass
  9. from pathlib import Path
  10. import textwrap
  11.  
  12. try:
  13.     import requests
  14. except ImportError:
  15.     print("Please pip3 install requests")
  16.     sys.exit(-1)
  17.  
  18. DEFAULT_REQUESTS_TIMEOUT = (3.05, 10)
  19.  
  20. SCRIPTDIR = Path(__file__).parent.resolve()
  21. os.chdir(Path(SCRIPTDIR).parent)
  22.  
  23. UK_TENANT = "08205459-3a7d-4db1-8983-239979359a91"
  24. US_TENANT = "f1aa4cec-7ed9-4c31-ab6d-780d98fef592"
  25. TENANT_NAMES = {
  26.         "08205459-3a7d-4db1-8983-239979359a91": "uk",
  27.         "f1aa4cec-7ed9-4c31-ab6d-780d98fef592": "us"}
  28.  
  29.  
  30. class BlobError(Exception):
  31.     """For all 'normal' error conditions pertaining to blobs"""
  32.  
  33.  
  34. def get_tenant_name(tenantid):
  35.     return TENANT_NAMES[tenantid]
  36.  
  37.  
  38. def get_terraform_storage_account_name(tenant, production=False):
  39.  
  40.     # the bash has the stupid newline bug in it (again)
  41.     if production:
  42.         return f"jitsuintfstate{tenant}prod"
  43.     else:
  44.         return f"jitsuintfstate{tenant}"
  45.  
  46.  
  47. def current_subscription_name():
  48.     return sp.run(
  49.         "az account show --query name -o tsv".split(),
  50.         check=True, capture_output=True, encoding='utf-8').stdout.strip()
  51.  
  52.  
  53. def get_subscription_tenant_id(subscription):
  54.     cmd = "az account show --subscription".split()
  55.     cmd.append(subscription)  # contains spaces
  56.     cmd.extend("--query tenantId -o tsv".split())
  57.     return sp.run(
  58.         cmd, check=True, capture_output=True, encoding='utf-8').stdout.strip()
  59.  
  60.  
  61. def get_blob_access_token(
  62.         subscription, blobstore, timeout=DEFAULT_REQUESTS_TIMEOUT):
  63.     """Get an access token for the blob store"""
  64.  
  65.     cmd = "az account get-access-token".split()
  66.     cmd.extend(
  67.         f"--resource https://{blobstore}.blob.core.windows.net/".split())
  68.     cmd.extend(["--subscription", subscription])  # white space
  69.     cmd.extend("--query accessToken --output tsv".split())
  70.  
  71.     return sp.run(
  72.         cmd, check=True, capture_output=True, encoding="utf-8"
  73.         ).stdout.strip()
  74.  
  75.  
  76. def get_blob(
  77.         blobstore, container, blobpath, token,
  78.         timeout=DEFAULT_REQUESTS_TIMEOUT):
  79.     """Gets a blob (without aquiring a lease)"""
  80.  
  81.     headers = {"x-ms-version": "2018-03-28"}
  82.     if token is not None:
  83.         headers["Authorization"] = f"Bearer {token}"
  84.  
  85.     resp = requests.get(
  86.         f"https://{blobstore}.blob.core.windows.net/{container}/{blobpath}",
  87.         headers=headers, timeout=timeout)
  88.  
  89.     if resp:
  90.         return resp.text
  91.     raise BlobError(str(resp))
  92.  
  93.  
  94. def get_valuechain_statefile(
  95.         valuechain, subscription=None, tenantid=None, tfstateaccount=None,
  96.         container="avid"):
  97.     """Get the terraform valuechain state blob"""
  98.  
  99.     if subscription is None:
  100.         subscription = current_subscription_name()
  101.  
  102.     if tenantid is None:
  103.         tenantid = get_subscription_tenant_id(subscription)
  104.  
  105.     tenantname = get_tenant_name(tenantid)
  106.  
  107.     production = True if tenantname == 'us' else False
  108.  
  109.     if tfstateaccount is None:
  110.         tfstateaccount = get_terraform_storage_account_name(
  111.             tenantname, production)
  112.     token = get_blob_access_token(subscription, tfstateaccount)
  113.  
  114.     blobpath = f"valuechains/{valuechain}/valuechain.tfstate"
  115.     return get_blob(tfstateaccount, container, blobpath, token)
  116.  
  117.  
  118. def cmd_valuechain_tf_blob(top, opts):
  119.     """Get value chain terraform blob"""
  120.  
  121.     blob = get_valuechain_statefile(
  122.         opts.valuechain, subscription=opts.subscription)
  123.  
  124.     print(blob)
  125.  
  126.  
  127. def run(args=None):
  128.     if args is None:
  129.         args = sys.argv[1:]
  130.  
  131.     top = argparse.ArgumentParser(
  132.         description=__doc__,
  133.         formatter_class=argparse.ArgumentDefaultsHelpFormatter)
  134.     top.set_defaults(func=lambda a, b: print("See sub commands in help"))
  135.  
  136.     subcmd = top.add_subparsers(title="Availalbe commands")
  137.  
  138.     user = getpass.getuser()
  139.     top.add_argument("--subscription")
  140.     top.add_argument("-u", "--user", default=user)
  141.     top.add_argument(
  142.         "-v", "--valuechain", default=f"value-chain-dev-{user}")
  143.  
  144.     p = subcmd.add_parser(
  145.         "vc", help=cmd_valuechain_tf_blob.__doc__)
  146.  
  147.     p.set_defaults(func=cmd_valuechain_tf_blob)
  148.  
  149.     args = top.parse_args(args)
  150.     args.func(top, args)
  151.  
  152.  
  153. if __name__ == "__main__":
  154.     try:
  155.         sys.exit(run())
  156.     except sp.CalledProcessError as cpe:
  157.         if cpe.stdout:
  158.             print(cpe.stdout)
  159.         print(cpe.stderr, file=sys.stderr)
  160.         sys.exit(cpe.returncode)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement