code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
'''Updates a load balancer model, i.e. PUT an updated LB body. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. lb_name (str): Name of the new load balancer. body (str): JSON body of an updated load balancer. Returns: HTTP response. Load Balancer JSON body. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/Microsoft.Network/loadBalancers/', lb_name, '?api-version=', NETWORK_API]) return do_put(endpoint, body, access_token)
def update_load_balancer(access_token, subscription_id, resource_group, lb_name, body)
Updates a load balancer model, i.e. PUT an updated LB body. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. lb_name (str): Name of the new load balancer. body (str): JSON body of an updated load balancer. Returns: HTTP response. Load Balancer JSON body.
3.161488
1.774559
1.781562
'''Print the Compute usage quota for a specific region''' print(region + ':') quota = azurerm.get_compute_usage(access_token, sub_id, region) if SUMMARY is False: print(json.dumps(quota, sort_keys=False, indent=2, separators=(',', ': '))) try: for resource in quota['value']: if resource['name']['value'] == 'cores': print(' Current: ' + str(resource['currentValue']) + ', limit: ' + str(resource['limit'])) break except KeyError: print('Invalid data for region: ' + region)
def print_region_quota(access_token, sub_id, region)
Print the Compute usage quota for a specific region
3.623587
3.329485
1.088332
'''Main routine.''' # check for single command argument if len(sys.argv) != 2: region = 'all' else: region = sys.argv[1] # Load Azure app defaults try: with open('azurermconfig.json') as config_file: config_data = json.load(config_file) except FileNotFoundError: sys.exit('Error: Expecting azurermconfig.json in current folder') tenant_id = config_data['tenantId'] app_id = config_data['appId'] app_secret = config_data['appSecret'] sub_id = config_data['subscriptionId'] access_token = azurerm.get_access_token(tenant_id, app_id, app_secret) # print quota if region == 'all': # list locations locations = azurerm.list_locations(access_token, sub_id) for location in locations['value']: print_region_quota(access_token, sub_id, location['name']) else: print_region_quota(access_token, sub_id, region)
def main()
Main routine.
2.04972
2.039717
1.004904
'''Main routine.''' # Load Azure app defaults try: with open('azurermconfig.json') as config_file: config_data = json.load(config_file) except FileNotFoundError: sys.exit("Error: Expecting azurermonfig.json in current folder") tenant_id = config_data['tenantId'] app_id = config_data['appId'] app_secret = config_data['appSecret'] subscription_id = config_data['subscriptionId'] access_token = azurerm.get_access_token(tenant_id, app_id, app_secret) ''' pubs = azurerm.list_publishers(access_token, subscription_id, 'southeastasia') for pub in pubs: # print(json.dumps(pub, sort_keys=False, indent=2, separators=(',', ': '))) print(pub['name']) offers = azurerm.list_offers(access_token, subscription_id, 'southeastasia', 'rancher') for offer in offers: print(json.dumps(offer, sort_keys=False, indent=2, separators=(',', ': '))) skus = azurerm.list_skus(access_token, subscription_id, 'southeastasia', 'rancher', 'rancheros') for sku in skus: print(sku['name']) ''' #print('Versions for CoreOS:') # versions = azurerm.list_sku_versions(access_token, subscription_id, 'eastasia', 'CoreOS', # 'CoreOS', 'Stable') versions = azurerm.list_sku_versions(access_token, subscription_id, 'eastus2', 'Canonical', 'UbuntuServer', '16.04-LTS') for version in versions: print(version['name'])
def main()
Main routine.
2.161045
2.172354
0.994794
'''Main routine.''' # validate command line arguments arg_parser = argparse.ArgumentParser() arg_parser.add_argument('--uri', '-u', required=True, action='store', help='Template URI') arg_parser.add_argument('--params', '-p', required=True, action='store', help='Parameters json file') arg_parser.add_argument('--rg', '-g', required=True, action='store', help='Resource Group name') arg_parser.add_argument('--sub', '-s', required=False, action='store', help='subscription id (optional)') args = arg_parser.parse_args() template_uri = args.uri params = args.params rgname = args.rg subscription_id = args.sub # load parameters file try: with open(params) as params_file: param_data = json.load(params_file) except FileNotFoundError: print('Error: Expecting ' + params + ' in current folder') sys.exit() access_token = azurerm.get_access_token_from_cli() if subscription_id is None: subscription_id = azurerm.get_subscription_from_cli() deployment_name = Haikunator().haikunate() print('Deployment name:' + deployment_name) deploy_return = azurerm.deploy_template_uri( access_token, subscription_id, rgname, deployment_name, template_uri, param_data) print(json.dumps(deploy_return.json(), sort_keys=False, indent=2, separators=(',', ': ')))
def main()
Main routine.
2.459334
2.453725
1.002286
'''Main routine.''' # check for single command argument if len(sys.argv) != 2: sys.exit('Usage: python ' + sys.argv[0] + ' rg_name') rgname = sys.argv[1] # if in Azure cloud shell, authenticate using the MSI endpoint if 'ACC_CLOUD' in os.environ and 'MSI_ENDPOINT' in os.environ: access_token = azurerm.get_access_token_from_cli() subscription_id = azurerm.get_subscription_from_cli() else: # load service principal details from a config file try: with open('azurermconfig.json') as configfile: configdata = json.load(configfile) except FileNotFoundError: sys.exit('Error: Expecting azurermconfig.json in current folder') tenant_id = configdata['tenantId'] app_id = configdata['appId'] app_secret = configdata['appSecret'] subscription_id = configdata['subscriptionId'] # authenticate access_token = azurerm.get_access_token(tenant_id, app_id, app_secret) # delete a resource group rgreturn = azurerm.delete_resource_group(access_token, subscription_id, rgname) print(rgreturn)
def main()
Main routine.
2.569277
2.566993
1.00089
'''Main routine.''' # Load Azure app defaults try: with open('azurermconfig.json') as config_file: config_data = json.load(config_file) except FileNotFoundError: sys.exit("Error: Expecting azurermconfig.json in current folder") tenant_id = config_data['tenantId'] app_id = config_data['appId'] app_secret = config_data['appSecret'] subscription_id = config_data['subscriptionId'] access_token = azurerm.get_access_token(tenant_id, app_id, app_secret) # list locations locations = azurerm.list_locations(access_token, subscription_id) for location in locations['value']: print(location['name'] + ', Display Name: ' + location['displayName'] + ', Coords: ' + location['latitude'] + ', ' + location['longitude'])
def main()
Main routine.
1.936866
1.925115
1.006104
'''main routine''' # process arguments if len(sys.argv) < 4: usage() rgname = sys.argv[1] vmss_name = sys.argv[2] capacity = sys.argv[3] # Load Azure app defaults try: with open('azurermconfig.json') as config_file: config_data = json.load(config_file) except FileNotFoundError: print("Error: Expecting azurermconfig.json in current folder") sys.exit() tenant_id = config_data['tenantId'] app_id = config_data['appId'] app_secret = config_data['appSecret'] subscription_id = config_data['subscriptionId'] access_token = azurerm.get_access_token(tenant_id, app_id, app_secret) scaleoutput = azurerm.scale_vmss(access_token, subscription_id, rgname, vmss_name, capacity) print(scaleoutput.text)
def main()
main routine
2.045007
2.070347
0.98776
'''main routine''' # process arguments if len(sys.argv) < 3: usage() rgname = sys.argv[1] vmss_name = sys.argv[2] # Load Azure app defaults try: with open('azurermconfig.json') as config_file: config_data = json.load(config_file) except FileNotFoundError: sys.exit('Error: Expecting azurermonfig.json in current folder') tenant_id = config_data['tenantId'] app_id = config_data['appId'] app_secret = config_data['appSecret'] subscription_id = config_data['subscriptionId'] access_token = azurerm.get_access_token(tenant_id, app_id, app_secret) instanceviewlist = azurerm.list_vmss_vm_instance_view(access_token, subscription_id, rgname, vmss_name) for vmi in instanceviewlist['value']: instance_id = vmi['instanceId'] upgrade_domain = vmi['properties']['instanceView']['platformUpdateDomain'] fault_domain = vmi['properties']['instanceView']['platformFaultDomain'] print('Instance ID: ' + instance_id + ', UD: ' + str(upgrade_domain) + ', FD: ' + str(fault_domain))
def main()
main routine
2.243635
2.264733
0.990684
'''Create availability set. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. as_name (str): Name of the new availability set. update_domains (int): Number of update domains. fault_domains (int): Number of fault domains. location (str): Azure data center location. E.g. westus. Returns: HTTP response. JSON body of the availability set properties. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/Microsoft.Compute/availabilitySets/', as_name, '?api-version=', COMP_API]) as_body = {'location': location} properties = {'platformUpdateDomainCount': update_domains} properties['platformFaultDomainCount'] = fault_domains as_body['properties'] = properties body = json.dumps(as_body) return do_put(endpoint, body, access_token)
def create_as(access_token, subscription_id, resource_group, as_name, update_domains, fault_domains, location)
Create availability set. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. as_name (str): Name of the new availability set. update_domains (int): Number of update domains. fault_domains (int): Number of fault domains. location (str): Azure data center location. E.g. westus. Returns: HTTP response. JSON body of the availability set properties.
2.211067
1.719859
1.285609
'''Delete availability set. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. as_name (str): Name of the availability set. Returns: HTTP response. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/Microsoft.Compute/availabilitySets/', as_name, '?api-version=', COMP_API]) return do_delete(endpoint, access_token)
def delete_as(access_token, subscription_id, resource_group, as_name)
Delete availability set. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. as_name (str): Name of the availability set. Returns: HTTP response.
2.261181
2.031765
1.112915
'''Delete a virtual machine. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. vm_name (str): Name of the virtual machine. Returns: HTTP response. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/Microsoft.Compute/virtualMachines/', vm_name, '?api-version=', COMP_API]) return do_delete(endpoint, access_token)
def delete_vm(access_token, subscription_id, resource_group, vm_name)
Delete a virtual machine. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. vm_name (str): Name of the virtual machine. Returns: HTTP response.
2.143633
1.99851
1.072616
'''Delete a virtual machine scale set. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. vmss_name (str): Name of the virtual machine scale set. Returns: HTTP response. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/Microsoft.Compute/virtualMachineScaleSets/', vmss_name, '?api-version=', COMP_API]) return do_delete(endpoint, access_token)
def delete_vmss(access_token, subscription_id, resource_group, vmss_name)
Delete a virtual machine scale set. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. vmss_name (str): Name of the virtual machine scale set. Returns: HTTP response.
2.064246
1.94539
1.061096
'''Delete a VM in a VM Scale Set. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. vmss_name (str): Name of the virtual machine scale set. vm_ids (str): String representation of a JSON list of VM IDs. E.g. '[1,2]'. Returns: HTTP response. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/Microsoft.Compute/virtualMachineScaleSets/', vmss_name, '/delete?api-version=', COMP_API]) body = '{"instanceIds" : ' + vm_ids + '}' return do_post(endpoint, body, access_token)
def delete_vmss_vms(access_token, subscription_id, resource_group, vmss_name, vm_ids)
Delete a VM in a VM Scale Set. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. vmss_name (str): Name of the virtual machine scale set. vm_ids (str): String representation of a JSON list of VM IDs. E.g. '[1,2]'. Returns: HTTP response.
2.43721
1.81909
1.339796
'''List compute usage and limits for a location. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. location (str): Azure data center location. E.g. westus. Returns: HTTP response. JSON body of Compute usage and limits data. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/providers/Microsoft.compute/locations/', location, '/usages?api-version=', COMP_API]) return do_get(endpoint, access_token)
def get_compute_usage(access_token, subscription_id, location)
List compute usage and limits for a location. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. location (str): Azure data center location. E.g. westus. Returns: HTTP response. JSON body of Compute usage and limits data.
3.62651
2.321456
1.56217
'''Get virtual machine details. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. vm_name (str): Name of the virtual machine. Returns: HTTP response. JSON body of VM properties. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/Microsoft.Compute/virtualMachines/', vm_name, '?api-version=', COMP_API]) return do_get(endpoint, access_token)
def get_vm(access_token, subscription_id, resource_group, vm_name)
Get virtual machine details. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. vm_name (str): Name of the virtual machine. Returns: HTTP response. JSON body of VM properties.
2.421392
1.920151
1.261043
'''Get details about a VM extension. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. vm_name (str): Name of the virtual machine. extension_name (str): VM extension name. Returns: HTTP response. JSON body of VM extension properties. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/Microsoft.Compute/virtualMachines/', vm_name, '/extensions/', extension_name, '?api-version=', COMP_API]) return do_get(endpoint, access_token)
def get_vm_extension(access_token, subscription_id, resource_group, vm_name, extension_name)
Get details about a VM extension. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. vm_name (str): Name of the virtual machine. extension_name (str): VM extension name. Returns: HTTP response. JSON body of VM extension properties.
2.242164
1.768092
1.268126
'''Get virtual machine scale set details. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. vmss_name (str): Name of the virtual machine scale set. Returns: HTTP response. JSON body of scale set properties. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/Microsoft.Compute/virtualMachineScaleSets/', vmss_name, '?api-version=', COMP_API]) return do_get(endpoint, access_token)
def get_vmss(access_token, subscription_id, resource_group, vmss_name)
Get virtual machine scale set details. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. vmss_name (str): Name of the virtual machine scale set. Returns: HTTP response. JSON body of scale set properties.
2.317988
1.843719
1.257235
'''Get individual VMSS VM details. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. vmss_name (str): Name of the virtual machine scale set. instance_id (int): VM ID of the scale set VM. Returns: HTTP response. JSON body of VMSS VM model view. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/Microsoft.Compute/virtualMachineScaleSets/', vmss_name, '/virtualMachines/', str(instance_id), '?api-version=', COMP_API]) return do_get(endpoint, access_token)
def get_vmss_vm(access_token, subscription_id, resource_group, vmss_name, instance_id)
Get individual VMSS VM details. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. vmss_name (str): Name of the virtual machine scale set. instance_id (int): VM ID of the scale set VM. Returns: HTTP response. JSON body of VMSS VM model view.
2.631286
1.707557
1.540966
'''Get availability set details. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. as_name (str): Name of the new availability set. Returns: HTTP response. JSON body of the availability set properties. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/Microsoft.Compute/availabilitySets/', as_name, '?api-version=', COMP_API]) return do_get(endpoint, access_token)
def get_as(access_token, subscription_id, resource_group, as_name)
Get availability set details. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. as_name (str): Name of the new availability set. Returns: HTTP response. JSON body of the availability set properties.
2.511606
1.854156
1.354582
'''List availability sets in a subscription. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. Returns: HTTP response. JSON body of the list of availability set properties. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/providers/Microsoft.Compute/availabilitySets', '?api-version=', COMP_API]) return do_get_next(endpoint, access_token)
def list_as_sub(access_token, subscription_id)
List availability sets in a subscription. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. Returns: HTTP response. JSON body of the list of availability set properties.
3.670005
2.542173
1.443649
'''List VM images in a subscription. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. Returns: HTTP response. JSON body of a list of VM images. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/providers/Microsoft.Compute/images', '?api-version=', COMP_API]) return do_get_next(endpoint, access_token)
def list_vm_images_sub(access_token, subscription_id)
List VM images in a subscription. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. Returns: HTTP response. JSON body of a list of VM images.
3.330433
2.716974
1.225788
'''List VMs in a resource group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. Returns: HTTP response. JSON body of a list of VM model views. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/Microsoft.Compute/virtualMachines', '?api-version=', COMP_API]) return do_get(endpoint, access_token)
def list_vms(access_token, subscription_id, resource_group)
List VMs in a resource group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. Returns: HTTP response. JSON body of a list of VM model views.
2.869674
2.097376
1.368221
'''List VMs in a subscription. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. Returns: HTTP response. JSON body of a list of VM model views. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/providers/Microsoft.Compute/virtualMachines', '?api-version=', COMP_API]) return do_get_next(endpoint, access_token)
def list_vms_sub(access_token, subscription_id)
List VMs in a subscription. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. Returns: HTTP response. JSON body of a list of VM model views.
3.642865
2.595121
1.403736
'''List VM Scale Sets in a resource group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. Returns: HTTP response. JSON body of a list of scale set model views. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/Microsoft.Compute/virtualMachineScaleSets', '?api-version=', COMP_API]) return do_get_next(endpoint, access_token)
def list_vmss(access_token, subscription_id, resource_group)
List VM Scale Sets in a resource group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. Returns: HTTP response. JSON body of a list of scale set model views.
3.124783
2.147576
1.455028
'''List the VM skus available for a VM Scale Set. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. vmss_name (str): Name of the virtual machine scale set. Returns: HTTP response. JSON body of VM skus. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/Microsoft.Compute/virtualMachineScaleSets/', vmss_name, '/skus', '?api-version=', COMP_API]) return do_get_next(endpoint, access_token)
def list_vmss_skus(access_token, subscription_id, resource_group, vmss_name)
List the VM skus available for a VM Scale Set. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. vmss_name (str): Name of the virtual machine scale set. Returns: HTTP response. JSON body of VM skus.
2.761938
2.020954
1.36665
'''List VM Scale Sets in a subscription. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. Returns: HTTP response. JSON body of VM scale sets. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/providers/Microsoft.Compute/virtualMachineScaleSets', '?api-version=', COMP_API]) return do_get_next(endpoint, access_token)
def list_vmss_sub(access_token, subscription_id)
List VM Scale Sets in a subscription. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. Returns: HTTP response. JSON body of VM scale sets.
3.372975
2.58571
1.304467
'''Gets one page of a paginated list of scale set VM instance views. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. vmss_name (str): Name of the virtual machine scale set. link (str): Optional link to URI to get list (as part of a paginated API query). Returns: HTTP response. JSON body of list of VM instance views. ''' if link is None: endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/Microsoft.Compute/virtualMachineScaleSets/', vmss_name, '/virtualMachines?$expand=instanceView&$select=instanceView', '&api-version=', COMP_API]) else: endpoint = link return do_get(endpoint, access_token)
def list_vmss_vm_instance_view_pg(access_token, subscription_id, resource_group, vmss_name, link=None)
Gets one page of a paginated list of scale set VM instance views. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. vmss_name (str): Name of the virtual machine scale set. link (str): Optional link to URI to get list (as part of a paginated API query). Returns: HTTP response. JSON body of list of VM instance views.
3.029774
1.780688
1.701462
'''Power off all the VMs in a virtual machine scale set. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. vmss_name (str): Name of the virtual machine scale set. Returns: HTTP response. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/Microsoft.Compute/virtualMachineScaleSets/', vmss_name, '/powerOff?api-version=', COMP_API]) body = '{"instanceIds" : ["*"]}' return do_post(endpoint, body, access_token)
def poweroff_vmss(access_token, subscription_id, resource_group, vmss_name)
Power off all the VMs in a virtual machine scale set. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. vmss_name (str): Name of the virtual machine scale set. Returns: HTTP response.
2.276515
2.101811
1.083121
'''Poweroff all the VMs in a virtual machine scale set. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. vmss_name (str): Name of the virtual machine scale set. instance_ids (str): String representation of a JSON list of VM IDs. E.g. '[1,2]'. Returns: HTTP response. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/Microsoft.Compute/virtualMachineScaleSets/', vmss_name, '/powerOff?api-version=', COMP_API]) body = '{"instanceIds" : ' + instance_ids + '}' return do_post(endpoint, body, access_token)
def poweroff_vmss_vms(access_token, subscription_id, resource_group, vmss_name, instance_ids)
Poweroff all the VMs in a virtual machine scale set. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. vmss_name (str): Name of the virtual machine scale set. instance_ids (str): String representation of a JSON list of VM IDs. E.g. '[1,2]'. Returns: HTTP response.
2.356204
1.807252
1.303749
'''Put VMSS body. Can be used to create or update a scale set. E.g. call get_vmss(), make changes to the body, call put_vmss(). Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. vmss_name (str): Name of the new scale set. vmss_body (dictionary): Body containining Returns: HTTP response. JSON body of the virtual machine scale set properties. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/Microsoft.Compute/virtualMachineScaleSets/', vmss_name, '?api-version=', COMP_API]) body = json.dumps(vmss_body) return do_put(endpoint, body, access_token)
def put_vmss(access_token, subscription_id, resource_group, vmss_name, vmss_body)
Put VMSS body. Can be used to create or update a scale set. E.g. call get_vmss(), make changes to the body, call put_vmss(). Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. vmss_name (str): Name of the new scale set. vmss_body (dictionary): Body containining Returns: HTTP response. JSON body of the virtual machine scale set properties.
3.307894
1.584056
2.088244
'''Update a VMSS VM. E.g. add/remove a data disk from a specifc VM in a scale set (preview). Note: Only currently enabled for Azure Canary regions. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. vmss_name (str): Name of the new scale set. vm_id (int): VM ID of VM to update vmss_body (dictionary): Body containining Returns: HTTP response. JSON body of the virtual machine scale set VM properties. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/Microsoft.Compute/virtualMachineScaleSets/', vmss_name, '/virtualMachines/', str(vm_id), '?api-version=', COMP_API]) body = json.dumps(vm_body) return do_put(endpoint, body, access_token)
def put_vmss_vm(access_token, subscription_id, resource_group, vmss_name, vm_id, vm_body)
Update a VMSS VM. E.g. add/remove a data disk from a specifc VM in a scale set (preview). Note: Only currently enabled for Azure Canary regions. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. vmss_name (str): Name of the new scale set. vm_id (int): VM ID of VM to update vmss_body (dictionary): Body containining Returns: HTTP response. JSON body of the virtual machine scale set VM properties.
4.505469
1.582175
2.847643
'''Change the instance count of an existing VM Scale Set. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. vmss_name (str): Name of the virtual machine scale set. capacity (int): New number of VMs. Returns: HTTP response. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/Microsoft.Compute/virtualMachineScaleSets/', vmss_name, '?api-version=', COMP_API]) body = '{"sku":{"capacity":"' + str(capacity) + '"}}' return do_patch(endpoint, body, access_token)
def scale_vmss(access_token, subscription_id, resource_group, vmss_name, capacity)
Change the instance count of an existing VM Scale Set. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. vmss_name (str): Name of the virtual machine scale set. capacity (int): New number of VMs. Returns: HTTP response.
2.377398
1.917875
1.2396
'''Start a virtual machine. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. vm_name (str): Name of the virtual machine. Returns: HTTP response. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/Microsoft.Compute/virtualMachines/', vm_name, '/start', '?api-version=', COMP_API]) return do_post(endpoint, '', access_token)
def start_vm(access_token, subscription_id, resource_group, vm_name)
Start a virtual machine. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. vm_name (str): Name of the virtual machine. Returns: HTTP response.
2.223687
2.130807
1.043589
'''Update a virtual machine with a new JSON body. E.g. do a GET, change something, call this. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. vm_name (str): Name of the virtual machine. body (dict): JSON body of the VM. Returns: HTTP response. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/Microsoft.Compute/virtualMachines/', vm_name, '?api-version=', COMP_API]) return do_put(endpoint, body, access_token)
def update_vm(access_token, subscription_id, resource_group, vm_name, body)
Update a virtual machine with a new JSON body. E.g. do a GET, change something, call this. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. vm_name (str): Name of the virtual machine. body (dict): JSON body of the VM. Returns: HTTP response.
3.073947
1.810341
1.697993
'''Update a VMSS with a new JSON body. E.g. do a GET, change something, call this. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. vm_name (str): Name of the virtual machine. body (dict): JSON body of the VM scale set. Returns: HTTP response. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/Microsoft.Compute/virtualMachineScaleSets/', vmss_name, '?api-version=', COMP_API]) return do_put(endpoint, body, access_token)
def update_vmss(access_token, subscription_id, resource_group, vmss_name, body)
Update a VMSS with a new JSON body. E.g. do a GET, change something, call this. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. vm_name (str): Name of the virtual machine. body (dict): JSON body of the VM scale set. Returns: HTTP response.
3.301479
1.818315
1.815681
'''look at VMSS VM instance view to get VM IDs by UD''' instance_viewlist = azurerm.list_vmss_vm_instance_view(access_token, subscription_id, resource_group, vmssname) # print(json.dumps(instance_viewlist, sort_keys=False, indent=2, separators=(',', ': '))) # loop through the instance view list, and build the vm id list of VMs in # the matching UD udinstancelist = [] for instance_view in instance_viewlist['value']: vmud = instance_view['properties']['instance_view']['platformUpdateDomain'] if vmud == updatedomain: udinstancelist.append(instance_view['instanceId']) udinstancelist.sort() return udinstancelist
def get_vm_ids_by_ud(access_token, subscription_id, resource_group, vmssname, updatedomain)
look at VMSS VM instance view to get VM IDs by UD
3.604048
3.073755
1.172523
'''get a Microsoft Graph access token using Azure Cloud Shell's MSI_ENDPOINT. Notes: The auth token returned by this function is not an Azure auth token. Use it for querying the Microsoft Graph API. This function only works in an Azure cloud shell or virtual machine. Returns: A Microsoft Graph authentication token string. ''' if 'ACC_CLOUD' in os.environ and 'MSI_ENDPOINT' in os.environ: endpoint = os.environ['MSI_ENDPOINT'] else: return None headers = {'Metadata': 'true'} body = {"resource": 'https://' + GRAPH_RESOURCE_HOST + '/'} ret = requests.post(endpoint, headers=headers, data=body) return ret.json()['access_token']
def get_graph_token_from_msi()
get a Microsoft Graph access token using Azure Cloud Shell's MSI_ENDPOINT. Notes: The auth token returned by this function is not an Azure auth token. Use it for querying the Microsoft Graph API. This function only works in an Azure cloud shell or virtual machine. Returns: A Microsoft Graph authentication token string.
6.306285
2.446789
2.577371
'''Return the object ID for the Graph user who owns the access token. Args: access_token (str): A Microsoft Graph access token. (Not an Azure access token.) If not provided, attempt to get it from MSI_ENDPOINT. Returns: An object ID string for a user or service principal. ''' if access_token is None: access_token = get_graph_token_from_msi() endpoint = 'https://' + GRAPH_RESOURCE_HOST + '/v1.0/me/' headers = {'Authorization': 'Bearer ' + access_token, 'Host': GRAPH_RESOURCE_HOST} ret = requests.get(endpoint, headers=headers) return ret.json()['id']
def get_object_id_from_graph(access_token=None)
Return the object ID for the Graph user who owns the access token. Args: access_token (str): A Microsoft Graph access token. (Not an Azure access token.) If not provided, attempt to get it from MSI_ENDPOINT. Returns: An object ID string for a user or service principal.
3.976537
1.907037
2.085191
'''Get the default, or named, subscription id from CLI's local cache. Args: name (str): Optional subscription name. If this is set, the subscription id of the named subscription is returned from the CLI cache if present. If not set, the subscription id of the default subscription is returned. Returns: Azure subscription ID string. Requirements: User has run 'az login' once, or is in Azure Cloud Shell. ''' home = os.path.expanduser('~') azure_profile_path = home + os.sep + '.azure' + os.sep + 'azureProfile.json' if os.path.isfile(azure_profile_path) is False: print('Error from get_subscription_from_cli(): Cannot find ' + azure_profile_path) return None with io.open(azure_profile_path, 'r', encoding='utf-8-sig') as azure_profile_fd: azure_profile = json.load(azure_profile_fd) for subscription_info in azure_profile['subscriptions']: if (name is None and subscription_info['isDefault'] is True) or \ subscription_info['name'] == name: return subscription_info['id'] return None
def get_subscription_from_cli(name=None)
Get the default, or named, subscription id from CLI's local cache. Args: name (str): Optional subscription name. If this is set, the subscription id of the named subscription is returned from the CLI cache if present. If not set, the subscription id of the default subscription is returned. Returns: Azure subscription ID string. Requirements: User has run 'az login' once, or is in Azure Cloud Shell.
3.368585
1.794604
1.877063
'''List available locations for a subscription. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. Returns: HTTP response. JSON list of locations. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/locations?api-version=', BASE_API]) return do_get(endpoint, access_token)
def list_locations(access_token, subscription_id)
List available locations for a subscription. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. Returns: HTTP response. JSON list of locations.
3.244215
2.66509
1.2173
'''Create a new Cosmos DB account in the named resource group, with the named location. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. account_name (str): Name of the new Cosmos DB account. location (str): Azure data center location. E.g. westus. cosmosdb_kind (str): Database type. E.g. GlobalDocumentDB. Returns: HTTP response. JSON body of storage account properties. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourcegroups/', rgname, '/providers/Microsoft.DocumentDB/databaseAccounts/', account_name, '?api-version=', COSMOSDB_API]) cosmosdb_body = {'location': location, 'kind': cosmosdb_kind, 'properties': {'databaseAccountOfferType': 'Standard', 'locations': [{'failoverPriority': 0, 'locationName': location}]}} body = json.dumps(cosmosdb_body) return do_put(endpoint, body, access_token)
def create_cosmosdb_account(access_token, subscription_id, rgname, account_name, location, cosmosdb_kind)
Create a new Cosmos DB account in the named resource group, with the named location. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. account_name (str): Name of the new Cosmos DB account. location (str): Azure data center location. E.g. westus. cosmosdb_kind (str): Database type. E.g. GlobalDocumentDB. Returns: HTTP response. JSON body of storage account properties.
2.523188
1.735141
1.454169
'''Get the access keys for the specified Cosmos DB account. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. account_name (str): Name of the Cosmos DB account. Returns: HTTP response. JSON body of Cosmos DB account keys. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourcegroups/', rgname, '/providers/Microsoft.DocumentDB/databaseAccounts/', account_name, '/listKeys', '?api-version=', COSMOSDB_API]) return do_post(endpoint, '', access_token)
def get_cosmosdb_account_keys(access_token, subscription_id, rgname, account_name)
Get the access keys for the specified Cosmos DB account. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. account_name (str): Name of the Cosmos DB account. Returns: HTTP response. JSON body of Cosmos DB account keys.
2.459354
1.962984
1.252865
'''Create a new key vault in the named resource group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. vault_name (str): Name of the new key vault. location (str): Azure data center location. E.g. westus2. template_deployment (boolean): Whether to allow deployment from template. tenant_id (str): Optionally specify a tenant ID (otherwise picks first response) from ist_tenants(). object_id (str): Optionally specify an object ID representing user or principal for the access policy. Returns: HTTP response. JSON body of key vault properties. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourcegroups/', rgname, '/providers/Microsoft.KeyVault/vaults/', vault_name, '?api-version=', KEYVAULT_API]) # get tenant ID if not specified if tenant_id is None: ret = list_tenants(access_token) tenant_id = ret['value'][0]['tenantId'] # if object_id is None: access_policies = [{'tenantId': tenant_id, 'objectId': object_id, 'permissions': { 'keys': ['get', 'create', 'delete', 'list', 'update', 'import', 'backup', 'restore', 'recover'], 'secrets': ['get', 'list', 'set', 'delete', 'backup', 'restore', 'recover'], 'certificates': ['get', 'list', 'delete', 'create', 'import', 'update', 'managecontacts', 'getissuers', 'listissuers', 'setissuers', 'deleteissuers', 'manageissuers', 'recover'], 'storage': ['get', 'list', 'delete', 'set', 'update', 'regeneratekey', 'setsas', 'listsas', 'getsas', 'deletesas'] }}] vault_properties = {'tenantId': tenant_id, 'sku': {'family': 'A', 'name': 'standard'}, 'enabledForTemplateDeployment': template_deployment, 'accessPolicies': access_policies} vault_body = {'location': location, 'properties': vault_properties} body = json.dumps(vault_body) return do_put(endpoint, body, access_token)
def create_keyvault(access_token, subscription_id, rgname, vault_name, location, template_deployment=True, tenant_id=None, object_id=None)
Create a new key vault in the named resource group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. vault_name (str): Name of the new key vault. location (str): Azure data center location. E.g. westus2. template_deployment (boolean): Whether to allow deployment from template. tenant_id (str): Optionally specify a tenant ID (otherwise picks first response) from ist_tenants(). object_id (str): Optionally specify an object ID representing user or principal for the access policy. Returns: HTTP response. JSON body of key vault properties.
2.721998
1.826405
1.490359
'''Deletes a key vault in the named resource group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. vault_name (str): Name of the new key vault. Returns: HTTP response. 200 OK. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourcegroups/', rgname, '/providers/Microsoft.KeyVault/vaults/', vault_name, '?api-version=', KEYVAULT_API]) return do_delete(endpoint, access_token)
def delete_keyvault(access_token, subscription_id, rgname, vault_name)
Deletes a key vault in the named resource group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. vault_name (str): Name of the new key vault. Returns: HTTP response. 200 OK.
2.500852
1.856021
1.347426
'''Gets details about the named key vault. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. vault_name (str): Name of the key vault. Returns: HTTP response. JSON body of key vault properties. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourcegroups/', rgname, '/providers/Microsoft.KeyVault/vaults/', vault_name, '?api-version=', KEYVAULT_API]) return do_get(endpoint, access_token)
def get_keyvault(access_token, subscription_id, rgname, vault_name)
Gets details about the named key vault. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. vault_name (str): Name of the key vault. Returns: HTTP response. JSON body of key vault properties.
2.412607
1.832013
1.316916
'''Lists key vaults in the named resource group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. Returns: HTTP response. 200 OK. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourcegroups/', rgname, '/providers/Microsoft.KeyVault/vaults', '?api-version=', KEYVAULT_API]) return do_get_next(endpoint, access_token)
def list_keyvaults(access_token, subscription_id, rgname)
Lists key vaults in the named resource group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. Returns: HTTP response. 200 OK.
2.907119
2.258683
1.287086
'''Lists key vaults belonging to this subscription. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. Returns: HTTP response. 200 OK. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/providers/Microsoft.KeyVault/vaults', '?api-version=', KEYVAULT_API]) return do_get_next(endpoint, access_token)
def list_keyvaults_sub(access_token, subscription_id)
Lists key vaults belonging to this subscription. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. Returns: HTTP response. 200 OK.
3.266489
2.564667
1.273651
'''Adds a secret to a key vault using the key vault URI. Creates a new version if the secret already exists. Args: access_token (str): A valid Azure authentication token. vault_uri (str): Vault URI e.g. https://myvault.vault.azure.net. secret_name (str): Name of the secret to add. secret_value (str): Value of the secret. Returns: HTTP response. 200 OK. ''' endpoint = ''.join([vault_uri, '/secrets/', secret_name, '?api-version=', '7.0']) current_time = datetime.datetime.now().isoformat() attributes = {'created': current_time, 'enabled': True, 'exp': None, 'nbf': None, 'recoveryLevel': 'Purgeable', 'updated': current_time} secret_body = {'attributes': attributes, 'contentType': None, 'kid': None, 'managed': None, 'tags': {'file-encoding': 'utf-8'}, 'value': secret_value} body = json.dumps(secret_body) print(body) return do_put(endpoint, body, access_token)
def set_keyvault_secret(access_token, vault_uri, secret_name, secret_value)
Adds a secret to a key vault using the key vault URI. Creates a new version if the secret already exists. Args: access_token (str): A valid Azure authentication token. vault_uri (str): Vault URI e.g. https://myvault.vault.azure.net. secret_name (str): Name of the secret to add. secret_value (str): Value of the secret. Returns: HTTP response. 200 OK.
2.766208
2.071036
1.335664
'''Deletes a secret from a key vault using the key vault URI. Args: access_token (str): A valid Azure authentication token. vault_uri (str): Vault URI e.g. https://myvault.azure.net. secret_name (str): Name of the secret to add. Returns: HTTP response. 200 OK. ''' endpoint = ''.join([vault_uri, '/secrets/', secret_name, '?api-version=', '7.0']) return do_delete(endpoint, access_token)
def delete_keyvault_secret(access_token, vault_uri, secret_name)
Deletes a secret from a key vault using the key vault URI. Args: access_token (str): A valid Azure authentication token. vault_uri (str): Vault URI e.g. https://myvault.azure.net. secret_name (str): Name of the secret to add. Returns: HTTP response. 200 OK.
3.521797
2.063768
1.706488
'''Create a new autoscale rule - pass the output in a list to create_autoscale_setting(). Args: subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. vmss_name (str): Name of scale set to apply scale events to. metric_name (str): Name of metric being evaluated. operator (str): Operator to evaluate. E.g. "GreaterThan". threshold (str): Threshold to trigger action. direction (str): Direction of action. E.g. Increase. change_count (str): How many to increase or decrease by. time_grain (str): Optional. Measurement granularity. Default 'PT1M'. time_window (str): Optional. Range of time to collect data over. Default 'PT5M'. cool_down (str): Optional. Time to wait after last scaling action. ISO 8601 format. Default 'PT1M'. Returns: HTTP response. JSON body of autoscale setting. ''' metric_trigger = {'metricName': metric_name} metric_trigger['metricNamespace'] = '' metric_trigger['metricResourceUri'] = '/subscriptions/' + subscription_id + \ '/resourceGroups/' + resource_group + \ '/providers/Microsoft.Compute/virtualMachineScaleSets/' + vmss_name metric_trigger['timeGrain'] = time_grain metric_trigger['statistic'] = 'Average' metric_trigger['timeWindow'] = time_window metric_trigger['timeAggregation'] = 'Average' metric_trigger['operator'] = operator metric_trigger['threshold'] = threshold scale_action = {'direction': direction} scale_action['type'] = 'ChangeCount' scale_action['value'] = str(change_count) scale_action['cooldown'] = cool_down new_rule = {'metricTrigger': metric_trigger} new_rule['scaleAction'] = scale_action return new_rule
def create_autoscale_rule(subscription_id, resource_group, vmss_name, metric_name, operator, threshold, direction, change_count, time_grain='PT1M', time_window='PT5M', cool_down='PT1M')
Create a new autoscale rule - pass the output in a list to create_autoscale_setting(). Args: subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. vmss_name (str): Name of scale set to apply scale events to. metric_name (str): Name of metric being evaluated. operator (str): Operator to evaluate. E.g. "GreaterThan". threshold (str): Threshold to trigger action. direction (str): Direction of action. E.g. Increase. change_count (str): How many to increase or decrease by. time_grain (str): Optional. Measurement granularity. Default 'PT1M'. time_window (str): Optional. Range of time to collect data over. Default 'PT5M'. cool_down (str): Optional. Time to wait after last scaling action. ISO 8601 format. Default 'PT1M'. Returns: HTTP response. JSON body of autoscale setting.
2.402957
1.365612
1.759619
'''Create a new autoscale setting for a scale set. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. setting_name (str): Name of the autoscale setting. vmss_name (str): Name of scale set to apply scale events to. location (str): Azure data center location. E.g. westus. minval (int): Minimum number of VMs. maxval (int): Maximum number of VMs. default (int): Default VM number when no data available. autoscale_rules (list): List of outputs from create_autoscale_rule(). notify (str): Optional. Returns: HTTP response. JSON body of autoscale setting. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/microsoft.insights/autoscaleSettings/', setting_name, '?api-version=', INSIGHTS_API]) autoscale_setting = {'location': location} profile = {'name': 'Profile1'} capacity = {'minimum': str(minval)} capacity['maximum'] = str(maxval) capacity['default'] = str(default) profile['capacity'] = capacity profile['rules'] = autoscale_rules profiles = [profile] properties = {'name': setting_name} properties['profiles'] = profiles properties['targetResourceUri'] = '/subscriptions/' + subscription_id + \ '/resourceGroups/' + resource_group + \ '/providers/Microsoft.Compute/virtualMachineScaleSets/' + vmss_name properties['enabled'] = True if notify is not None: notification = {'operation': 'Scale'} email = {'sendToSubscriptionAdministrato': False} email['sendToSubscriptionCoAdministrators'] = False email['customEmails'] = [notify] notification = {'email': email} properties['notifications'] = [notification] autoscale_setting['properties'] = properties body = json.dumps(autoscale_setting) return do_put(endpoint, body, access_token)
def create_autoscale_setting(access_token, subscription_id, resource_group, setting_name, vmss_name, location, minval, maxval, default, autoscale_rules, notify=None)
Create a new autoscale setting for a scale set. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. setting_name (str): Name of the autoscale setting. vmss_name (str): Name of scale set to apply scale events to. location (str): Azure data center location. E.g. westus. minval (int): Minimum number of VMs. maxval (int): Maximum number of VMs. default (int): Default VM number when no data available. autoscale_rules (list): List of outputs from create_autoscale_rule(). notify (str): Optional. Returns: HTTP response. JSON body of autoscale setting.
2.545196
1.871057
1.360298
'''List the autoscale settings in a subscription. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. Returns: HTTP response. JSON body of autoscale settings. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/providers/microsoft.insights/', '/autoscaleSettings?api-version=', INSIGHTS_API]) return do_get(endpoint, access_token)
def list_autoscale_settings(access_token, subscription_id)
List the autoscale settings in a subscription. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. Returns: HTTP response. JSON body of autoscale settings.
3.054832
2.48524
1.22919
'''List the Microsoft Insights components in a resource group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. Returns: HTTP response. JSON body of components. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/microsoft.insights/', '/components?api-version=', INSIGHTS_COMPONENTS_API]) return do_get(endpoint, access_token)
def list_insights_components(access_token, subscription_id, resource_group)
List the Microsoft Insights components in a resource group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. Returns: HTTP response. JSON body of components.
2.830278
2.227402
1.270663
'''List the monitoring metric definitions for a resource. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. resource_provider (str): Type of resource provider. resource_type (str): Type of resource. resource_name (str): Name of resource. Returns: HTTP response. JSON body of metric definitions. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/', resource_provider, '/', resource_type, '/', resource_name, '/providers/microsoft.insights', '/metricdefinitions?api-version=', INSIGHTS_METRICS_API]) return do_get(endpoint, access_token)
def list_metric_defs_for_resource(access_token, subscription_id, resource_group, resource_provider, resource_type, resource_name)
List the monitoring metric definitions for a resource. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. resource_provider (str): Type of resource provider. resource_type (str): Type of resource. resource_name (str): Name of resource. Returns: HTTP response. JSON body of metric definitions.
2.16158
1.739362
1.242743
'''Get the monitoring metrics for a resource. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. resource_type (str): Type of resource. resource_name (str): Name of resource. Returns: HTTP response. JSON body of resource metrics. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/', resource_provider, '/', resource_type, '/', resource_name, '/providers/microsoft.insights', '/metrics?api-version=', INSIGHTS_PREVIEW_API]) return do_get(endpoint, access_token)
def get_metrics_for_resource(access_token, subscription_id, resource_group, resource_provider, resource_type, resource_name)
Get the monitoring metrics for a resource. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. resource_type (str): Type of resource. resource_name (str): Name of resource. Returns: HTTP response. JSON body of resource metrics.
2.404265
1.840996
1.305959
'''Get the insights evens for a subsctipion since the specific timestamp. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. start_timestamp (str): timestamp to get events from. E.g. '2017-05-01T00:00:00.0000000Z'. Returns: HTTP response. JSON body of insights events. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/providers/microsoft.insights/eventtypes/management/values?api-version=', INSIGHTS_API, '&$filter=eventTimestamp ge \'', start_timestamp, '\'']) return do_get(endpoint, access_token)
def get_events_for_subscription(access_token, subscription_id, start_timestamp)
Get the insights evens for a subsctipion since the specific timestamp. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. start_timestamp (str): timestamp to get events from. E.g. '2017-05-01T00:00:00.0000000Z'. Returns: HTTP response. JSON body of insights events.
3.976723
1.976516
2.011986
'''Main routine.''' # Load Azure app defaults try: with open('azurermconfig.json') as config_file: config_data = json.load(config_file) except FileNotFoundError: sys.exit('Error: Expecting azurermconfig.json in current folder') tenant_id = config_data['tenantId'] app_id = config_data['appId'] app_secret = config_data['appSecret'] subscription_id = config_data['subscriptionId'] access_token = azurerm.get_access_token(tenant_id, app_id, app_secret) vmlist = azurerm.list_vms_sub(access_token, subscription_id) print(json.dumps(vmlist, sort_keys=False, indent=2, separators=(',', ': '))) ''' for vm in vmlist['value']: count += 1 name = vm['name'] location = vm['location'] offer = vm['properties']['storageProfile']['imageReference']['offer'] sku = vm['properties']['storageProfile']['imageReference']['sku'] print(''.join([str(count), ': ', name, # ', RG: ', rgname, ', location: ', location, ', OS: ', offer, ' ', sku])) '''
def main()
Main routine.
2.083784
2.09066
0.996711
'''Deploy a template referenced by a JSON string, with parameters as a JSON string. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. deployment_name (str): A name you give to the deployment. template (str): String representatipn of a JSON template body. parameters (str): String representation of a JSON template parameters body. Returns: HTTP response. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourcegroups/', resource_group, '/providers/Microsoft.Resources/deployments/', deployment_name, '?api-version=', DEPLOYMENTS_API]) properties = {'template': template} properties['mode'] = 'Incremental' properties['parameters'] = parameters template_body = {'properties': properties} body = json.dumps(template_body) return do_put(endpoint, body, access_token)
def deploy_template(access_token, subscription_id, resource_group, deployment_name, template, parameters)
Deploy a template referenced by a JSON string, with parameters as a JSON string. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. deployment_name (str): A name you give to the deployment. template (str): String representatipn of a JSON template body. parameters (str): String representation of a JSON template parameters body. Returns: HTTP response.
2.959578
1.937423
1.527585
'''Deploy a template referenced by a URI, with parameters as a JSON string. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. deployment_name (str): A name you give to the deployment. template_uri (str): URI which points to a JSON template (e.g. github raw location). parameters (str): String representation of a JSON template parameters body. Returns: HTTP response. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourcegroups/', resource_group, '/providers/Microsoft.Resources/deployments/', deployment_name, '?api-version=', DEPLOYMENTS_API]) properties = {'templateLink': {'uri': template_uri}} properties['mode'] = 'Incremental' properties['parameters'] = parameters template_body = {'properties': properties} body = json.dumps(template_body) return do_put(endpoint, body, access_token)
def deploy_template_uri(access_token, subscription_id, resource_group, deployment_name, template_uri, parameters)
Deploy a template referenced by a URI, with parameters as a JSON string. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. deployment_name (str): A name you give to the deployment. template_uri (str): URI which points to a JSON template (e.g. github raw location). parameters (str): String representation of a JSON template parameters body. Returns: HTTP response.
3.006889
1.885752
1.59453
'''Deploy a template with both template and parameters referenced by URIs. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. deployment_name (str): A name you give to the deployment. template_uri (str): URI which points to a JSON template (e.g. github raw location). parameters_uri (str): URI which points to a JSON parameters file (e.g. github raw location). Returns: HTTP response. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourcegroups/', resource_group, '/providers/Microsoft.Resources/deployments/', deployment_name, '?api-version=', DEPLOYMENTS_API]) properties = {'templateLink': {'uri': template_uri}} properties['mode'] = 'Incremental' properties['parametersLink'] = {'uri': parameters_uri} template_body = {'properties': properties} body = json.dumps(template_body) return do_put(endpoint, body, access_token)
def deploy_template_uri_param_uri(access_token, subscription_id, resource_group, deployment_name, template_uri, parameters_uri)
Deploy a template with both template and parameters referenced by URIs. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. deployment_name (str): A name you give to the deployment. template_uri (str): URI which points to a JSON template (e.g. github raw location). parameters_uri (str): URI which points to a JSON parameters file (e.g. github raw location). Returns: HTTP response.
2.668477
1.825831
1.461514
'''Attach a data disk to a VMSS VM model''' disk_id = '/subscriptions/' + subscription + '/resourceGroups/' + rgname + \ '/providers/Microsoft.Compute/disks/' + diskname disk_model = {'lun': lun, 'createOption': 'Attach', 'caching': 'None', 'managedDisk': {'storageAccountType': 'Standard_LRS', 'id': disk_id}} vmssvm_model['properties']['storageProfile']['dataDisks'].append( disk_model) return vmssvm_model
def attach_model(subscription, rgname, vmssvm_model, diskname, lun)
Attach a data disk to a VMSS VM model
2.370495
2.346894
1.010056
'''Detach a data disk from a VMSS VM model''' data_disks = vmssvm_model['properties']['storageProfile']['dataDisks'] data_disks[:] = [disk for disk in data_disks if disk.get('lun') != lun] vmssvm_model['properties']['storageProfile']['dataDisks'] = data_disks return vmssvm_model
def detach_model(vmssvm_model, lun)
Detach a data disk from a VMSS VM model
2.275512
2.318404
0.981499
'''Main routine.''' # validate command line arguments arg_parser = argparse.ArgumentParser() arg_parser.add_argument('--vmssname', '-n', required=True, action='store', help='Scale set name') arg_parser.add_argument('--rgname', '-g', required=True, action='store', help='Resource Group Name') arg_parser.add_argument('--operation', '-o', required=True, action='store', help='Operation (attach/detach)') arg_parser.add_argument('--vmid', '-i', required=True, action='store', help='VM id') arg_parser.add_argument('--lun', '-l', required=True, action='store', help='lun id') arg_parser.add_argument('--diskname', '-d', required=False, action='store', help='Optional password') args = arg_parser.parse_args() vmssname = args.vmssname rgname = args.rgname operation = args.operation vmid = args.vmid lun = int(args.lun) diskname = args.diskname if operation != 'attach' and operation != 'detach': sys.exit('--operation must be attach or detach') if diskname is None and operation == 'attach': sys.exit('--diskname is required for attach operation.') subscription_id = azurerm.get_subscription_from_cli() # authenticate access_token = azurerm.get_access_token_from_cli() # do a get on the VM vmssvm_model = azurerm.get_vmss_vm(access_token, subscription_id, rgname, vmssname, vmid) # check operation if operation == 'attach': new_model = attach_model(subscription_id, rgname, vmssvm_model, diskname, lun) else: if operation == 'detach': new_model = detach_model(vmssvm_model, lun) # do a put on the VM rmreturn = azurerm.put_vmss_vm(access_token, subscription_id, rgname, vmssname, vmid, new_model) if rmreturn.status_code != 201: sys.exit('Error ' + str(rmreturn.status_code) + ' creating VM. ' + rmreturn.text) print(json.dumps(rmreturn, sort_keys=False, indent=2, separators=(',', ': ')))
def main()
Main routine.
2.186665
2.180873
1.002656
'''get an Azure access token using the adal library. Args: tenant_id (str): Tenant id of the user's account. application_id (str): Application id of a Service Principal account. application_secret (str): Application secret (password) of the Service Principal account. Returns: An Azure authentication token string. ''' context = adal.AuthenticationContext( get_auth_endpoint() + tenant_id, api_version=None) token_response = context.acquire_token_with_client_credentials( get_resource_endpoint(), application_id, application_secret) return token_response.get('accessToken')
def get_access_token(tenant_id, application_id, application_secret)
get an Azure access token using the adal library. Args: tenant_id (str): Tenant id of the user's account. application_id (str): Application id of a Service Principal account. application_secret (str): Application secret (password) of the Service Principal account. Returns: An Azure authentication token string.
2.888562
1.669229
1.730477
'''Get an Azure authentication token from CLI's cache. Will only work if CLI local cache has an unexpired auth token (i.e. you ran 'az login' recently), or if you are running in Azure Cloud Shell (aka cloud console) Returns: An Azure authentication token string. ''' # check if running in cloud shell, if so, pick up token from MSI_ENDPOINT if 'ACC_CLOUD' in os.environ and 'MSI_ENDPOINT' in os.environ: endpoint = os.environ['MSI_ENDPOINT'] headers = {'Metadata': 'true'} body = {"resource": "https://management.azure.com/"} ret = requests.post(endpoint, headers=headers, data=body) return ret.json()['access_token'] else: # not running cloud shell home = os.path.expanduser('~') sub_username = "" # 1st identify current subscription azure_profile_path = home + os.sep + '.azure' + os.sep + 'azureProfile.json' if os.path.isfile(azure_profile_path) is False: print('Error from get_access_token_from_cli(): Cannot find ' + azure_profile_path) return None with codecs.open(azure_profile_path, 'r', 'utf-8-sig') as azure_profile_fd: subs = json.load(azure_profile_fd) for sub in subs['subscriptions']: if sub['isDefault'] == True: sub_username = sub['user']['name'] if sub_username == "": print('Error from get_access_token_from_cli(): Default subscription not found in ' + \ azure_profile_path) return None # look for acces_token access_keys_path = home + os.sep + '.azure' + os.sep + 'accessTokens.json' if os.path.isfile(access_keys_path) is False: print('Error from get_access_token_from_cli(): Cannot find ' + access_keys_path) return None with open(access_keys_path, 'r') as access_keys_fd: keys = json.load(access_keys_fd) # loop through accessTokens.json until first unexpired entry found for key in keys: if key['userId'] == sub_username: if 'accessToken' not in keys[0]: print('Error from get_access_token_from_cli(): accessToken not found in ' + \ access_keys_path) return None if 'tokenType' not in keys[0]: print('Error from get_access_token_from_cli(): tokenType not found in ' + \ access_keys_path) return None if 'expiresOn' not in keys[0]: print('Error from get_access_token_from_cli(): expiresOn not found in ' + \ access_keys_path) return None expiry_date_str = key['expiresOn'] # check date and skip past expired entries if 'T' in expiry_date_str: exp_date = dt.strptime(key['expiresOn'], '%Y-%m-%dT%H:%M:%S.%fZ') else: exp_date = dt.strptime(key['expiresOn'], '%Y-%m-%d %H:%M:%S.%f') if exp_date < dt.now(): continue else: return key['accessToken'] # if dropped out of the loop, token expired print('Error from get_access_token_from_cli(): token expired. Run \'az login\'') return None
def get_access_token_from_cli()
Get an Azure authentication token from CLI's cache. Will only work if CLI local cache has an unexpired auth token (i.e. you ran 'az login' recently), or if you are running in Azure Cloud Shell (aka cloud console) Returns: An Azure authentication token string.
2.507923
2.069966
1.211577
'''Main routine.''' # Load Azure app defaults try: with open('azurermconfig.json') as config_file: config_data = json.load(config_file) except FileNotFoundError: sys.exit('Error: Expecting azurermconfig.json in current folder') tenant_id = config_data['tenantId'] app_id = config_data['appId'] app_secret = config_data['appSecret'] subscription_id = config_data['subscriptionId'] access_token = azurerm.get_access_token(tenant_id, app_id, app_secret) count = 0 vmimglist = azurerm.list_vm_images_sub(access_token, subscription_id) print(json.dumps(vmimglist, sort_keys=False, indent=2, separators=(',', ': '))) for vm_image in vmimglist['value']: count += 1 name = vm_image['name'] location = vm_image['location'] offer = vm_image['properties']['storageProfile']['imageReference']['offer'] sku = vm_image['properties']['storageProfile']['imageReference']['sku'] print(''.join([str(count), ': ', name, ', location: ', location, ', OS: ', offer, ' ', sku]))
def main()
Main routine.
2.003615
1.996344
1.003642
'''List available VM image offers from a publisher. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. location (str): Azure data center location. E.g. westus. publisher (str): Publisher name, e.g. Canonical. Returns: HTTP response with JSON list of image offers. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/providers/Microsoft.Compute/', 'locations/', location, '/publishers/', publisher, '/artifacttypes/vmimage/offers?api-version=', COMP_API]) return do_get(endpoint, access_token)
def list_offers(access_token, subscription_id, location, publisher)
List available VM image offers from a publisher. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. location (str): Azure data center location. E.g. westus. publisher (str): Publisher name, e.g. Canonical. Returns: HTTP response with JSON list of image offers.
3.198254
2.066088
1.547976
'''List available VM image skus for a publisher offer. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. location (str): Azure data center location. E.g. westus. publisher (str): VM image publisher. E.g. MicrosoftWindowsServer. offer (str): VM image offer. E.g. WindowsServer. Returns: HTTP response with JSON list of skus. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/providers/Microsoft.Compute/', 'locations/', location, '/publishers/', publisher, '/artifacttypes/vmimage/offers/', offer, '/skus?api-version=', COMP_API]) return do_get(endpoint, access_token)
def list_skus(access_token, subscription_id, location, publisher, offer)
List available VM image skus for a publisher offer. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. location (str): Azure data center location. E.g. westus. publisher (str): VM image publisher. E.g. MicrosoftWindowsServer. offer (str): VM image offer. E.g. WindowsServer. Returns: HTTP response with JSON list of skus.
2.588993
1.89083
1.369236
'''List available versions for a given publisher's sku. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. location (str): Azure data center location. E.g. westus. publisher (str): VM image publisher. E.g. MicrosoftWindowsServer. offer (str): VM image offer. E.g. WindowsServer. sku (str): VM image sku. E.g. 2016-Datacenter. Returns: HTTP response with JSON list of versions. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/providers/Microsoft.Compute/', 'locations/', location, '/publishers/', publisher, '/artifacttypes/vmimage/offers/', offer, '/skus/', sku, '/versions?api-version=', COMP_API]) return do_get(endpoint, access_token)
def list_sku_versions(access_token, subscription_id, location, publisher, offer, sku)
List available versions for a given publisher's sku. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. location (str): Azure data center location. E.g. westus. publisher (str): VM image publisher. E.g. MicrosoftWindowsServer. offer (str): VM image offer. E.g. WindowsServer. sku (str): VM image sku. E.g. 2016-Datacenter. Returns: HTTP response with JSON list of versions.
2.352913
1.746827
1.346964
'''Main routine.''' # validate command line arguments arg_parser = argparse.ArgumentParser() arg_parser.add_argument('--vmssname', '-n', required=True, action='store', help='Scale set name') arg_parser.add_argument('--rgname', '-g', required=True, action='store', help='Resource Group Name') arg_parser.add_argument('--operation', '-o', required=True, action='store', help='Operation (attach/detach)') arg_parser.add_argument('--vmid', '-i', required=True, action='store', help='VM id') arg_parser.add_argument('--lun', '-l', required=True, action='store', help='lun id') arg_parser.add_argument('--diskname', '-d', required=False, action='store', help='Optional password') args = arg_parser.parse_args() vmssname = args.vmssname rgname = args.rgname operation = args.operation vmid = args.vmid lun = int(args.lun) diskname = args.diskname if operation != 'attach' and operation != 'detach': sys.exit('--operation must be attach or detach') if diskname is None and operation == 'attach': sys.exit('--diskname is required for attach operation.') # Load Azure app defaults try: with open('azurermconfig.json') as config_file: config_data = json.load(config_file) except FileNotFoundError: sys.exit("Error: Expecting azurermconfig.json in current folder") tenant_id = config_data['tenantId'] app_id = config_data['appId'] app_secret = config_data['appSecret'] subscription_id = config_data['subscriptionId'] # authenticate access_token = azurerm.get_access_token(tenant_id, app_id, app_secret) # do a get on the VM vmssvm_model = azurerm.get_vmss_vm(access_token, subscription_id, rgname, vmssname, vmid) # check operation if operation == 'attach': new_model = attach_model(subscription_id, rgname, vmssvm_model, diskname, lun) else: if operation == 'detach': new_model = detach_model(vmssvm_model, lun) # do a put on the VM rmreturn = azurerm.put_vmss_vm(access_token, subscription_id, rgname, vmssname, vmid, new_model) if rmreturn.status_code != 201 and rmreturn.status_code != 202: sys.exit('Error ' + str(rmreturn.status_code) + ' creating VM. ' + rmreturn.text) print(json.dumps(rmreturn, sort_keys=False, indent=2, separators=(',', ': ')))
def main()
Main routine.
1.924757
1.91822
1.003408
'''Main routine.''' # process arguments if len(sys.argv) < 3: usage() rgname = sys.argv[1] vmss = sys.argv[2] # Load Azure app defaults try: with open('azurermconfig.json') as config_file: config_data = json.load(config_file) except FileNotFoundError: sys.exit("Error: Expecting azurermconfig.json in current folder") tenant_id = config_data['tenantId'] app_id = config_data['appId'] app_secret = config_data['appSecret'] sub_id = config_data['subscriptionId'] access_token = azurerm.get_access_token(tenant_id, app_id, app_secret) # get metric definitions provider = 'Microsoft.Compute' resource_type = 'virtualMachineScaleSets' metric_definitions = azurerm.list_metric_defs_for_resource(access_token, sub_id, rgname, provider, resource_type, vmss) print(json.dumps(metric_definitions, sort_keys=False, indent=2, separators=(',', ': '))) metrics = azurerm.get_metrics_for_resource(access_token, sub_id, rgname, provider, resource_type, vmss) print(json.dumps(metrics, sort_keys=False, indent=2, separators=(',', ': ')))
def main()
Main routine.
1.930156
1.928482
1.000868
'''main reoutine''' # validate command line arguments arg_parser = argparse.ArgumentParser() arg_parser.add_argument('--vmssname', '-n', required=True, action='store', help='VMSS Name') arg_parser.add_argument('--rgname', '-g', required=True, action='store', help='Resource Group Name') arg_parser.add_argument('--details', '-a', required=False, action='store', help='Print all details') args = arg_parser.parse_args() name = args.vmssname rgname = args.rgname details = args.details # Load Azure app defaults try: with open('azurermconfig.json') as config_file: config_data = json.load(config_file) except FileNotFoundError: print("Error: Expecting azurermconfig.json in current folder") sys.exit() tenant_id = config_data['tenantId'] app_id = config_data['appId'] app_secret = config_data['appSecret'] subscription_id = config_data['subscriptionId'] # authenticate access_token = azurerm.get_access_token(tenant_id, app_id, app_secret) # get public IPs public_ips = azurerm.get_vmss_public_ips(access_token, subscription_id, rgname, name) # print details if details is True: print(json.dumps(public_ips, sort_keys=False, indent=2, separators=(',', ': '))) else: for pip in public_ips['value']: vm_id = re.search('Machines/(.*)/networkInt', pip['id']).group(1) ipaddr = pip['properties']['ipAddress'] print('VM id: ' + vm_id + ', IP: ' + ipaddr)
def main()
main reoutine
2.020613
1.96693
1.027293
'''Main routine.''' # if in Azure cloud shell, authenticate using the MSI endpoint if 'ACC_CLOUD' in os.environ and 'MSI_ENDPOINT' in os.environ: access_token = azurerm.get_access_token_from_cli() subscription_id = azurerm.get_subscription_from_cli() else: # load service principal details from a config file try: with open('azurermconfig.json') as configfile: configdata = json.load(configfile) except FileNotFoundError: sys.exit('Error: Expecting azurermconfig.json in current folder') tenant_id = configdata['tenantId'] app_id = configdata['appId'] app_secret = configdata['appSecret'] subscription_id = configdata['subscriptionId'] # authenticate access_token = azurerm.get_access_token(tenant_id, app_id, app_secret) # list resource groups resource_groups = azurerm.list_resource_groups(access_token, subscription_id) for rgname in resource_groups['value']: print(rgname['name'] + ', ' + rgname['location']) ''' rg_details = azurerm.get_resource_group(access_token, subscription_id, rgname['name']) print(json.dumps(rg_details, sort_keys=False, indent=2, separators=(',', ': '))) '''
def main()
Main routine.
2.214159
2.235127
0.990619
'''Makes a python dictionary of container properties. Args: container_name: The name of the container. image (str): Container image string. E.g. nginx. port (int): TCP port number. E.g. 8080. cpu (float): Amount of CPU to allocate to container. E.g. 1.0. memgb (float): Memory in GB to allocate to container. E.g. 1.5. environment (list): A list of [{'name':'envname', 'value':'envvalue'}]. Sets environment variables in the container. Returns: A Python dictionary of container properties, pass a list of these to create_container_group(). ''' container = {'name': container_name} container_properties = {'image': image} container_properties['ports'] = [{'port': port}] container_properties['resources'] = { 'requests': {'cpu': cpu, 'memoryInGB': memgb}} container['properties'] = container_properties if environment is not None: container_properties['environmentVariables'] = environment return container
def create_container_definition(container_name, image, port=80, cpu=1.0, memgb=1.5, environment=None)
Makes a python dictionary of container properties. Args: container_name: The name of the container. image (str): Container image string. E.g. nginx. port (int): TCP port number. E.g. 8080. cpu (float): Amount of CPU to allocate to container. E.g. 1.0. memgb (float): Memory in GB to allocate to container. E.g. 1.5. environment (list): A list of [{'name':'envname', 'value':'envvalue'}]. Sets environment variables in the container. Returns: A Python dictionary of container properties, pass a list of these to create_container_group().
2.965699
1.448363
2.047621
'''Create a new container group with a list of containers specifified by container_list. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. container_group_name (str): Name of container instance group. container_list (list): A list of container properties. Use create_container_definition to create each container property set. location (str): Azure data center location. E.g. westus. ostype (str): Container operating system type. Linux or Windows. port (int): TCP port number. E.g. 8080. iptype (str): Type of IP address. E.g. public. Returns: HTTP response with JSON body of container group. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourcegroups/', resource_group, '/providers/Microsoft.ContainerInstance/ContainerGroups/', container_group_name, '?api-version=', CONTAINER_API]) container_group_body = {'location': location} properties = {'osType': ostype} properties['containers'] = container_list ipport = {'protocol': 'TCP'} ipport['port'] = port ipaddress = {'ports': [ipport]} ipaddress['type'] = iptype properties['ipAddress'] = ipaddress container_group_body['properties'] = properties body = json.dumps(container_group_body) return do_put(endpoint, body, access_token)
def create_container_instance_group(access_token, subscription_id, resource_group, container_group_name, container_list, location, ostype='Linux', port=80, iptype='public')
Create a new container group with a list of containers specifified by container_list. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. container_group_name (str): Name of container instance group. container_list (list): A list of container properties. Use create_container_definition to create each container property set. location (str): Azure data center location. E.g. westus. ostype (str): Container operating system type. Linux or Windows. port (int): TCP port number. E.g. 8080. iptype (str): Type of IP address. E.g. public. Returns: HTTP response with JSON body of container group.
2.654751
1.688789
1.571985
'''Delete a container group from a resource group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. container_group_name (str): Name of container instance group. Returns: HTTP response. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourcegroups/', resource_group, '/providers/Microsoft.ContainerInstance/ContainerGroups/', container_group_name, '?api-version=', CONTAINER_API]) return do_delete(endpoint, access_token)
def delete_container_instance_group(access_token, subscription_id, resource_group, container_group_name)
Delete a container group from a resource group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. container_group_name (str): Name of container instance group. Returns: HTTP response.
2.264596
1.946291
1.163544
'''Get the JSON definition of a container group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. container_group_name (str): Name of container instance group. Returns: HTTP response. JSON body of container group. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourcegroups/', resource_group, '/providers/Microsoft.ContainerInstance/ContainerGroups/', container_group_name, '?api-version=', CONTAINER_API]) return do_get(endpoint, access_token)
def get_container_instance_group(access_token, subscription_id, resource_group, container_group_name)
Get the JSON definition of a container group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. container_group_name (str): Name of container instance group. Returns: HTTP response. JSON body of container group.
2.580346
1.873572
1.377233
'''Get the container logs for containers in a container group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. container_group_name (str): Name of container instance group. container_name (str): Optional name of a container in the group. Returns: HTTP response. Container logs. ''' if container_name is None: container_name = container_group_name endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourcegroups/', resource_group, '/providers/Microsoft.ContainerInstance/ContainerGroups/', container_group_name, '/containers/', container_name, '/logs?api-version=', CONTAINER_API]) return do_get(endpoint, access_token)
def get_container_instance_logs(access_token, subscription_id, resource_group, container_group_name, container_name=None)
Get the container logs for containers in a container group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. container_group_name (str): Name of container instance group. container_name (str): Optional name of a container in the group. Returns: HTTP response. Container logs.
2.385406
1.814711
1.314483
'''List the container groups in a resource group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. Returns: HTTP response. JSON list of container groups and their properties. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourcegroups/', resource_group, '/providers/Microsoft.ContainerInstance/ContainerGroups', '?api-version=', CONTAINER_API]) return do_get(endpoint, access_token)
def list_container_instance_groups(access_token, subscription_id, resource_group)
List the container groups in a resource group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. Returns: HTTP response. JSON list of container groups and their properties.
2.621964
2.031429
1.2907
'''List the container groups in a subscription. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. Returns: HTTP response. JSON list of container groups and their properties. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/providers/Microsoft.ContainerInstance/ContainerGroups', '?api-version=', CONTAINER_API]) return do_get(endpoint, access_token)
def list_container_instance_groups_sub(access_token, subscription_id)
List the container groups in a subscription. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. Returns: HTTP response. JSON list of container groups and their properties.
3.043779
2.317065
1.313635
'''Create a resource group in the specified location. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. location (str): Azure data center location. E.g. westus. Returns: HTTP response. JSON body. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourcegroups/', rgname, '?api-version=', RESOURCE_API]) rg_body = {'location': location} body = json.dumps(rg_body) return do_put(endpoint, body, access_token)
def create_resource_group(access_token, subscription_id, rgname, location)
Create a resource group in the specified location. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. location (str): Azure data center location. E.g. westus. Returns: HTTP response. JSON body.
2.664205
2.007129
1.327371
'''Delete the named resource group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. Returns: HTTP response. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourcegroups/', rgname, '?api-version=', RESOURCE_API]) return do_delete(endpoint, access_token)
def delete_resource_group(access_token, subscription_id, rgname)
Delete the named resource group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. Returns: HTTP response.
2.667946
2.30589
1.157013
'''Capture the specified resource group as a template Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. Returns: HTTP response. JSON body. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourcegroups/', rgname, '/exportTemplate', '?api-version=', RESOURCE_API]) rg_body = {'options':'IncludeParameterDefaultValue', 'resources':['*']} body = json.dumps(rg_body) return do_post(endpoint, body, access_token)
def export_template(access_token, subscription_id, rgname)
Capture the specified resource group as a template Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. Returns: HTTP response. JSON body.
3.953092
3.020673
1.308679
'''Get details about the named resource group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. Returns: HTTP response. JSON body. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', rgname, '?api-version=', RESOURCE_API]) return do_get(endpoint, access_token)
def get_resource_group(access_token, subscription_id, rgname)
Get details about the named resource group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. Returns: HTTP response. JSON body.
2.93806
2.169398
1.35432
'''List the resource groups in a subscription. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. Returns: HTTP response. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', '?api-version=', RESOURCE_API]) return do_get(endpoint, access_token)
def list_resource_groups(access_token, subscription_id)
List the resource groups in a subscription. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. Returns: HTTP response.
3.274694
2.956887
1.10748
'''Main routine.''' # validate command line arguments arg_parser = argparse.ArgumentParser() arg_parser.add_argument( '--vmssname', '-n', required=True, action='store', help='VMSS Name') arg_parser.add_argument('--rgname', '-g', required=True, action='store', help='Resource Group Name') arg_parser.add_argument('--details', '-a', required=False, action='store_true', default=False, help='Print all details') args = arg_parser.parse_args() name = args.vmssname rgname = args.rgname details = args.details # authenticate access_token = azurerm.get_access_token_from_cli() subscription_id = azurerm.get_subscription_from_cli() # get rolling upgrade latest status upgrade_status = azurerm.get_vmss_rolling_upgrades( access_token, subscription_id, rgname, name) # print details if details is True: print(json.dumps(upgrade_status, sort_keys=False, indent=2, separators=(',', ': '))) else: print(json.dumps(upgrade_status, sort_keys=False, indent=2, separators=(',', ': ')))
def main()
Main routine.
2.184583
2.164231
1.009404
"Write your forwards methods here." # Note: Don't use "from appname.models import ModelName". # Use orm.ModelName to refer to models in this application, # and orm['appname.ModelName'] for models in other applications. for coupon in orm['coupons.Coupon'].objects.all(): if coupon.user is not None or coupon.redeemed_at is not None: orm['coupons.CouponUser'].objects.create( coupon=coupon, user=coupon.user, redeemed_at=coupon.redeemed_at )
def forwards(self, orm)
Write your forwards methods here.
3.389809
3.198152
1.059927
filename = self.generate_filename(requirement) for backend in list(self.backends): try: pathname = backend.get(filename) if pathname is not None: return pathname except CacheBackendDisabledError as e: logger.debug("Disabling %s because it requires configuration: %s", backend, e) self.backends.remove(backend) except Exception as e: logger.exception("Disabling %s because it failed: %s", backend, e) self.backends.remove(backend)
def get(self, requirement)
Get a distribution archive from any of the available caches. :param requirement: A :class:`.Requirement` object. :returns: The absolute pathname of a local file or :data:`None` when the distribution archive is missing from all available caches.
3.182158
3.237835
0.982804
filename = self.generate_filename(requirement) for backend in list(self.backends): handle.seek(0) try: backend.put(filename, handle) except CacheBackendDisabledError as e: logger.debug("Disabling %s because it requires configuration: %s", backend, e) self.backends.remove(backend) except Exception as e: logger.exception("Disabling %s because it failed: %s", backend, e) self.backends.remove(backend)
def put(self, requirement, handle)
Store a distribution archive in all of the available caches. :param requirement: A :class:`.Requirement` object. :param handle: A file-like object that provides access to the distribution archive.
3.355114
3.378609
0.993046
return FILENAME_PATTERN % (self.config.cache_format_revision, requirement.name, requirement.version, get_python_version())
def generate_filename(self, requirement)
Generate a distribution archive filename for a package. :param requirement: A :class:`.Requirement` object. :returns: The filename of the distribution archive (a string) including a single leading directory component to indicate the cache format revision.
11.300523
8.506015
1.328533
install_timer = Timer() missing_dependencies = self.find_missing_dependencies(requirement) if missing_dependencies: # Compose the command line for the install command. install_command = shlex.split(self.install_command) + missing_dependencies # Prepend `sudo' to the command line? if not WINDOWS and not is_root(): # FIXME Ideally this should properly detect the presence of `sudo'. # Or maybe this should just be embedded in the *.ini files? install_command.insert(0, 'sudo') # Always suggest the installation command to the operator. logger.info("You seem to be missing %s: %s", pluralize(len(missing_dependencies), "dependency", "dependencies"), concatenate(missing_dependencies)) logger.info("You can install %s with this command: %s", "it" if len(missing_dependencies) == 1 else "them", " ".join(install_command)) if self.config.auto_install is False: # Refuse automatic installation and don't prompt the operator when the configuration says no. self.installation_refused(requirement, missing_dependencies, "automatic installation is disabled") # Get the operator's permission to install the missing package(s). if self.config.auto_install: logger.info("Got permission to install %s (via auto_install option).", pluralize(len(missing_dependencies), "dependency", "dependencies")) elif self.confirm_installation(requirement, missing_dependencies, install_command): logger.info("Got permission to install %s (via interactive prompt).", pluralize(len(missing_dependencies), "dependency", "dependencies")) else: logger.error("Refused installation of missing %s!", "dependency" if len(missing_dependencies) == 1 else "dependencies") self.installation_refused(requirement, missing_dependencies, "manual installation was refused") if subprocess.call(install_command) == 0: logger.info("Successfully installed %s in %s.", pluralize(len(missing_dependencies), "dependency", "dependencies"), install_timer) return True else: logger.error("Failed to install %s.", pluralize(len(missing_dependencies), "dependency", "dependencies")) msg = "Failed to install %s required by Python package %s! (%s)" raise DependencyInstallationFailed(msg % (pluralize(len(missing_dependencies), "system package", "system packages"), requirement.name, concatenate(missing_dependencies))) return False
def install_dependencies(self, requirement)
Install missing dependencies for the given requirement. :param requirement: A :class:`.Requirement` object. :returns: :data:`True` when missing system packages were installed, :data:`False` otherwise. :raises: :exc:`.DependencyInstallationRefused` when automatic installation is disabled or refused by the operator. :raises: :exc:`.DependencyInstallationFailed` when the installation of missing system packages fails. If `pip-accel` fails to build a binary distribution, it will call this method as a last chance to install missing dependencies. If this function does not raise an exception, `pip-accel` will retry the build once.
3.563781
3.322973
1.072468
known_dependencies = self.find_known_dependencies(requirement) if known_dependencies: installed_packages = self.find_installed_packages() logger.debug("Checking for missing dependencies of %s ..", requirement.name) missing_dependencies = sorted(set(known_dependencies).difference(installed_packages)) if missing_dependencies: logger.debug("Found %s: %s", pluralize(len(missing_dependencies), "missing dependency", "missing dependencies"), concatenate(missing_dependencies)) else: logger.info("All known dependencies are already installed.") return missing_dependencies
def find_missing_dependencies(self, requirement)
Find missing dependencies of a Python package. :param requirement: A :class:`.Requirement` object. :returns: A list of strings with system package names.
3.136995
3.149616
0.995993
logger.info("Checking for known dependencies of %s ..", requirement.name) known_dependencies = sorted(self.dependencies.get(requirement.name.lower(), [])) if known_dependencies: logger.info("Found %s: %s", pluralize(len(known_dependencies), "known dependency", "known dependencies"), concatenate(known_dependencies)) else: logger.info("No known dependencies... Maybe you have a suggestion?") return known_dependencies
def find_known_dependencies(self, requirement)
Find the known dependencies of a Python package. :param requirement: A :class:`.Requirement` object. :returns: A list of strings with system package names.
4.078801
4.145151
0.983993
list_command = subprocess.Popen(self.list_command, shell=True, stdout=subprocess.PIPE) stdout, stderr = list_command.communicate() if list_command.returncode != 0: raise SystemDependencyError("The command to list the installed system packages failed! ({command})", command=self.list_command) installed_packages = sorted(stdout.decode().split()) logger.debug("Found %i installed system package(s): %s", len(installed_packages), installed_packages) return installed_packages
def find_installed_packages(self)
Find the installed system packages. :returns: A list of strings with system package names. :raises: :exc:`.SystemDependencyError` when the command to list the installed system packages fails.
3.180199
2.521244
1.261361
msg = "Missing %s (%s) required by Python package %s (%s) but %s!" raise DependencyInstallationRefused( msg % (pluralize(len(missing_dependencies), "system package", "system packages"), concatenate(missing_dependencies), requirement.name, requirement.version, reason) )
def installation_refused(self, requirement, missing_dependencies, reason)
Raise :exc:`.DependencyInstallationRefused` with a user friendly message. :param requirement: A :class:`.Requirement` object. :param missing_dependencies: A list of strings with missing dependencies. :param reason: The reason why installation was refused (a string).
5.703859
5.211572
1.09446
try: return prompt_for_confirmation(format( "Do you want me to install %s %s?", "this" if len(missing_dependencies) == 1 else "these", "dependency" if len(missing_dependencies) == 1 else "dependencies", ), default=True) except KeyboardInterrupt: # Control-C is a negative response but doesn't # otherwise interrupt the program flow. return False
def confirm_installation(self, requirement, missing_dependencies, install_command)
Ask the operator's permission to install missing system packages. :param requirement: A :class:`.Requirement` object. :param missing_dependencies: A list of strings with missing dependencies. :param install_command: A list of strings with the command line needed to install the missing dependencies. :raises: :exc:`.DependencyInstallationRefused` when the operator refuses.
4.899272
5.435833
0.901292
return '\n\n'.join(' '.join(p.split()) for p in text.split('\n\n')).format(**kw)
def compact(text, **kw)
Compact whitespace in a string and format any keyword arguments into the string. :param text: The text to compact (a string). :param kw: Any keyword arguments to apply using :func:`str.format()`. :returns: The compacted, formatted string. The whitespace compaction preserves paragraphs.
4.340985
5.134321
0.845484
# The following logic previously used regular expressions but that approach # turned out to be very error prone, hence the current contraption based on # direct string manipulation :-). home_directory = find_home_directory() separators = set([os.sep]) if os.altsep is not None: separators.add(os.altsep) if len(pathname) >= 2 and pathname[0] == '~' and pathname[1] in separators: pathname = os.path.join(home_directory, pathname[2:]) # Also expand environment variables. return parse_path(pathname)
def expand_path(pathname)
Expand the home directory in a pathname based on the effective user id. :param pathname: A pathname that may start with ``~/``, indicating the path should be interpreted as being relative to the home directory of the current (effective) user. :returns: The (modified) pathname. This function is a variant of :func:`os.path.expanduser()` that doesn't use ``$HOME`` but instead uses the home directory of the effective user id. This is basically a workaround for ``sudo -s`` not resetting ``$HOME``.
5.877805
6.068013
0.968654
if WINDOWS: directory = os.environ.get('APPDATA') if not directory: directory = os.path.expanduser(r'~\Application Data') else: # This module isn't available on Windows so we have to import it here. import pwd # Look up the home directory of the effective user id so we can # generate pathnames relative to the home directory. entry = pwd.getpwuid(os.getuid()) directory = entry.pw_dir return directory
def find_home_directory()
Look up the home directory of the effective user id. :returns: The pathname of the home directory (a string). .. note:: On Windows this uses the ``%APPDATA%`` environment variable (if available) and otherwise falls back to ``~/Application Data``.
4.723618
3.99909
1.181173