Created
December 3, 2018 23:01
-
-
Save djaboxx/b9cfe2b87735957af86dcdd24fac491a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/local/bin/python | |
import requests | |
import os | |
import json | |
import sys | |
import hcl | |
def hcl_config(api, config): | |
with open(os.path.abspath(config), 'r') as fp: | |
obj = hcl.load(fp) | |
return obj.get('credentials').get(api).get('token') | |
def find_by_user(user): | |
resp = session.get( | |
"{0}/api/v2/organizations/{1}/oauth-tokens".format( | |
base_url, | |
org | |
) | |
) | |
for token in resp.json().get("data"): | |
if user == token.get("attributes").get("service-provider-user"): | |
return token | |
def find_by_provider_with_token(service_provider, token): | |
url = "{0}/{1}".format( | |
base_url, | |
token.get("relationships").get("oauth-client").get("links").get("related") | |
) | |
resp = session.get(url) | |
return resp.json().get("data").get("relationships").get("oauth-tokens").get("data")[0].get("id") | |
def oauth_token_search(user=None, provider=None): | |
token = find_by_user(user) | |
token = find_by_provider_with_token(provider, token) | |
return token | |
def find_first_token(): | |
resp = session.get( | |
"{0}/api/v2/organizations/{1}/oauth-tokens".format( | |
base_url, | |
org | |
) | |
) | |
data = resp.json() | |
return data.get("data")[0].get("id") | |
def main(opt, args): | |
# stdin_json = json.loads(sys.stdin.read()) | |
global session | |
session = requests.Session() | |
global base_url | |
base_url = "https://{0}".format(opt.api) | |
try: | |
global org | |
org = args.pop() | |
except: | |
print("Not enough arguments. Please provide TFE OrgName") | |
atlas_token = hcl_config(opt.api, opt.config) | |
session.headers = {"Authorization": "Bearer {0}".format(atlas_token)} | |
try: | |
if opt.user and opt.provider: | |
token = oauth_token_search(opt.user, opt.provider) | |
else: | |
token = find_first_token() | |
print(token) | |
except: | |
sys.stderr.write("Could not find Token. Have you connected your VCS?\n") | |
sys.stderr.write("Please go to: https://{1}/app/{0}/settings/version-control\n".format(opt.api, org)) | |
if "y" in raw_input("Open Browser? "): | |
os.system("open https://{0}/app/{1}/settings/version-control".format(opt.api, org)) | |
if __name__ == '__main__': | |
from optparse import OptionParser | |
parser = OptionParser() | |
parser.add_option('--config', default=os.path.expanduser("~/.terraformrc")) | |
parser.add_option('--api', default="app.terraform.io") | |
parser.add_option('--user') | |
parser.add_option('--provider') | |
opt, args = parser.parse_args() | |
main(opt, args) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment