1#!/usr/bin/python 2 3import commands 4import sys 5 6 7def run_command(command): 8 return_code, output = commands.getstatusoutput(command) 9 if return_code != 0: 10 raise ValueError("Failed to execute command: %s" % command) 11 return output 12 13 14def list_key_ids_for_service_account(service_account): 15 return parse_list_key_output( 16 run_command("gcloud iam service-accounts keys list --iam-account %s" % service_account) 17 ) 18 19def parse_list_key_output(output): 20 for line in [l for l in output.splitlines() if l][1:-1]: 21 key_id, created_at, expires_at = line.split() 22 yield key_id 23 24 25def delete_keys(key_ids, service_account): 26 for key_id in key_ids: 27 run_command( 28 "gcloud iam service-accounts keys delete %s --iam-account %s --quiet" % (key_id, service_account), 29 ) 30 print "Deleted key %s" % key_id 31 32 33if __name__ == "__main__": 34 service_account = sys.argv[1] 35 delete_keys( 36 list_key_ids_for_service_account(service_account), 37 service_account, 38 ) 39