Skip to content

Instantly share code, notes, and snippets.

@FilBot3
Created October 23, 2020 16:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FilBot3/911c076a6e3daf55f3edef4476622c9f to your computer and use it in GitHub Desktop.
Save FilBot3/911c076a6e3daf55f3edef4476622c9f to your computer and use it in GitHub Desktop.
Create a Service Principal using Python (may use the azure-cli as well.)
#!/usr/bin/env python
"""Create service principals with the azure-cli, for now.
Once I figure out the Python Library or the REST API, I'll use that.
"""
import argparse
import json
import logging
import subprocess
import sys
def create_service_principal(sp_name: str, sub_id: str):
"""Creates a Service Principal
"""
logging.info('Creating %s in %s subscription.', sp_name, sub_id)
if sys.platform in ['win32', 'win64']:
az_output = subprocess.run(['az', 'ad', 'sp', 'create-for-rbac',
'--name', sp_name,
'--role', 'Contributor',
'--scopes', f'/subscriptions/{sub_id}',
'--sdk-auth', 'true'],
check=True, shell=True, capture_output=True)
else:
az_output = subprocess.run(['az', 'ad', 'sp', 'create-for-rbac',
'--name', sp_name,
'--role', 'Contributor',
'--scopes', f'/subscriptions/{sub_id}',
'--sdk-auth', 'true'],
check=True, capture_output=True)
az_output = json.loads(az_output.stdout)
logging.info('Writing to sp_%s_credentials.json', sp_name)
with open(f'sp_{sp_name}_credentials.json', 'w') as json_file:
json.dump(az_output, json_file, indent=4, sort_keys=True)
def parsing_args() -> argparse.Namespace:
""" Parse our command-line arguments
"""
parser = argparse.ArgumentParser(description='Create Service Principals')
parser.add_argument('sp_name', metavar='SPN', type=str,
help='Desired name of Service Principal.')
parser.add_argument('sub_id', metavar='SID', type=str,
help='Subscription ID to add Service Principal to.')
return parser.parse_args()
def main():
"""Main Function
"""
args = parsing_args()
create_service_principal(args.sp_name, args.sub_id)
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment