Skip to content

Commit

Permalink
CLI: Added remove-accounts as an command
Browse files Browse the repository at this point in the history
Will remove matching json files locally and matching service accounts from the project.
  • Loading branch information
desimaniac committed Oct 30, 2019
1 parent b35fa92 commit bc3bce7
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
44 changes: 44 additions & 0 deletions sa_maker.py
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,50 @@ def create_accounts(name, amount=1):
sys.exit(1)


@app.command(help='Remove service accounts')
@click.option('--name', '-n', required=True, help='Name prefix for service accounts')
def remove_accounts(name):
global google, cfg

service_key_folder = os.path.join(cfg.service_account_folder, name)

# remove service accounts files
if os.path.exists(service_key_folder):
logger.debug(f"Removing service key files from path: {service_key_folder!r}")
for file in os.scandir(service_key_folder):
if file.name.endswith(".json"):
os.unlink(file.path)
logger.info(f"Removed server key files from path: {service_key_folder!r}")

# retrieve service accounts
emails = []
logger.debug("Retrieving existing service accounts...")
success, service_accounts = google.get_service_accounts()
if success:
logger.debug("Retrieved existing service accounts.")
for account in service_accounts['accounts']:
if account['email'].startswith(name):
emails.append(account['email'])
if len(emails) == 0:
logger.info(f"No service account emails matched.")
sys.exit(0)
else:
logger.error(f"Failed to retrieve service accounts:\n{service_accounts}")
sys.exit(1)

# remove service accounts
for email in emails:
logger.debug(f"Removing service account: {email}")
success, resp = google.delete_service_account(email)
if not success:
logger.error(f"Failed removing service account: {email}")
logger.error(f"Unexpected response when removing service account: {email!r}:\n{resp}")
sys.exit(1)
else:
logger.info(f"Removed service account: {email}")
sys.exit(0)


@app.command(help='Retrieve existing teamdrives')
def list_teamdrives():
global google, cfg
Expand Down
4 changes: 4 additions & 0 deletions utils/google.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,10 @@ def create_service_account_key(self, name):
})
return success, resp_data

def delete_service_account(self, email):
success, resp, resp_data = self.query(f'projects/{self.project_id}/serviceAccounts/{email}', 'DELETE')
return True if resp.status_code == 200 else False, resp_data

def get_teamdrives(self):
success, resp, resp_data = self.query('https://www.googleapis.com/drive/v3/teamdrives',
params={'pageSize': 100}, fetch_all_pages=True, page_type='teamDrives')
Expand Down

0 comments on commit bc3bce7

Please sign in to comment.