def get_vmss_properties(access_token, subscription_id): global vmssProperties global vmssVmProperties while True: try: # get VMSS details vmssget = azurerm.get_vmss(access_token, subscription_id, rgname, vmssname) name = vmssget['name'] location = vmssget['location'] capacity = vmssget['sku']['capacity'] offer = vmssget['properties']['virtualMachineProfile']['storageProfile']['imageReference']['offer'] sku = vmssget['properties']['virtualMachineProfile']['storageProfile']['imageReference']['sku'] provisioningState = vmssget['properties']['provisioningState'] vmssProperties = [name, capacity, location, rgname, offer, sku, provisioningState, dns, ipaddr] vmssvms = azurerm.list_vmss_vms(access_token, subscription_id, rgname, vmssname) # get VM details vmssVmProperties = [] for vm in vmssvms['value']: instanceId = vm['instanceId'] vmName = vm['name'] provisioningState = vm['properties']['provisioningState'] vmssVmProperties.append([instanceId, vmName, provisioningState]) except: # this catches errors like throttling from the Azure server f = open('error.log', 'w') if len(vmssvms) > 0: for p in vmssvms.items(): f.write("%s:%s\n" % p) f.close() # break out of loop when an error is encountered break # sleep before before each loop to avoid throttling time.sleep(2)
def get_vmss_properties(access_token, subscription_id): global vmssProperties global vmssVmProperties while True: try: # get VMSS details vmssget = azurerm.get_vmss(access_token, subscription_id, rgname, vmssname) vmssProperties['name'] = vmssget['name'] vmssProperties['capacity'] = vmssget['sku']['capacity'] vmssProperties['location'] = vmssget['location'] vmssProperties['vmsize'] = vmssget['sku'][ 'name'] # needed for scale operations (and displayed on dashboard) vmssProperties['tier'] = vmssget['sku'][ 'tier'] # needed for scale operations vmssProperties['offer'] = \ vmssget['properties']['virtualMachineProfile']['storageProfile']['imageReference']['offer'] vmssProperties['sku'] = vmssget['properties'][ 'virtualMachineProfile']['storageProfile']['imageReference'][ 'sku'] vmssProperties['provisioningState'] = vmssget['properties'][ 'provisioningState'] vmssvms = azurerm.list_vmss_vms(access_token, subscription_id, rgname, vmssname) # get VM details vmssVmTempProperties = [] for vm in vmssvms['value']: instanceId = vm['instanceId'] vmName = vm['name'] provisioningState = vm['properties']['provisioningState'] powerState = '' if provisioningState == 'Succeeded': instanceView = azurerm.get_vmss_vm_instance_view( access_token, subscription_id, rgname, vmssname, instanceId) powerState = instanceView['statuses'][1]['displayStatus'] vmssVmTempProperties.append( [instanceId, vmName, provisioningState, powerState]) vmssVmProperties = list(vmssVmTempProperties) print( json.dumps(vmssVmProperties, sort_keys=False, indent=2, separators=(',', ': '))) except: # this catches errors like throttling from the Azure server f = open('error.log', 'w') if len(vmssvms) > 0: for p in vmssvms.items(): f.write("%s:%s\n" % p) f.close() # break out of loop when an error is encountered break # sleep before before each loop to avoid throttling time.sleep(5)
def refresh_model(self): vmssmodel = azurerm.get_vmss(self.access_token, self.sub_id, self.rgname, self.name) self.model = vmssmodel self.capacity = vmssmodel['sku']['capacity'] self.vmsize = vmssmodel['sku']['name'] if self.image_type == 'platform': self.version = vmssmodel['properties']['virtualMachineProfile']['storageProfile']['imageReference']['version'] else: self.version = vmssmodel['properties']['virtualMachineProfile']['storageProfile']['osDisk']['image']['uri'] self.provisioningState = vmssmodel['properties']['provisioningState'] self.status = self.provisioningState
def _get_scaleset(self, resource_group=None, scale_group=None): output = azurerm.get_vmss(self.access_token, self.subscription_id, self._get_resource_group(resource_group), scale_group) return {'resource_group': self._get_resource_group(resource_group), 'scale_group_name': output['name'], 'tier': output['sku']['tier'], 'capacity': output['sku']['capacity'], 'machine_type': output['sku']['name']}
def main(): '''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 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) print('Printing VMSS details\n') vmssget = azurerm.get_vmss(access_token, subscription_id, rgname, vmss_name) name = vmssget['name'] capacity = vmssget['sku']['capacity'] location = vmssget['location'] offer = \ vmssget['properties']['virtualMachineProfile']['storageProfile']['imageReference']['offer'] sku = vmssget['properties']['virtualMachineProfile']['storageProfile'][ 'imageReference']['sku'] print( json.dumps(vmssget, sort_keys=False, indent=2, separators=(',', ': '))) print('Name: ' + name + ', capacity: ' + str(capacity) + ', ' + location + ', ' + offer + ', ' + sku) print('Printing VMSS instance view') instance_view = azurerm.get_vmss_instance_view(access_token, subscription_id, rgname, vmss_name) print( json.dumps(instance_view, sort_keys=False, indent=2, separators=(',', ': '))) '''
def get_vmss_properties(access_token, subscription_id): global vmssProperties global vmssVmProperties while True: try: # get VMSS details vmssget = azurerm.get_vmss(access_token, subscription_id, rgname, vmssname) vmssProperties['name'] = vmssget['name'] vmssProperties['capacity'] = vmssget['sku']['capacity'] vmssProperties['location'] = vmssget['location'] vmssProperties['vmsize'] = vmssget['sku'][ 'name'] # needed for scale operations (and displayed on dashboard) vmssProperties['tier'] = vmssget['sku']['tier'] # needed for scale operations vmssProperties['offer'] = \ vmssget['properties']['virtualMachineProfile']['storageProfile']['imageReference']['offer'] vmssProperties['sku'] = vmssget['properties']['virtualMachineProfile']['storageProfile']['imageReference'][ 'sku'] vmssProperties['provisioningState'] = vmssget['properties']['provisioningState'] vmssvms = azurerm.list_vmss_vms(access_token, subscription_id, rgname, vmssname) # get VM details vmssVmTempProperties = [] for vm in vmssvms['value']: instanceId = vm['instanceId'] vmName = vm['name'] provisioningState = vm['properties']['provisioningState'] powerState = '' if provisioningState == 'Succeeded': instanceView = azurerm.get_vmss_vm_instance_view(access_token, subscription_id, rgname, vmssname, instanceId) powerState = instanceView['statuses'][1]['displayStatus'] vmssVmTempProperties.append([instanceId, vmName, provisioningState, powerState]) vmssVmProperties = list(vmssVmTempProperties) print(json.dumps(vmssVmProperties, sort_keys=False, indent=2, separators=(',', ': '))) except: # this catches errors like throttling from the Azure server f = open('error.log', 'w') if len(vmssvms) > 0: for p in vmssvms.items(): f.write("%s:%s\n" % p) f.close() # break out of loop when an error is encountered break # sleep before before each loop to avoid throttling time.sleep(5)
def updatevmss(): newversion = versiontext.get() vmssname = vmsstext.get() resource_group = selectedrg.get() try: vmssmodel = azurerm.get_vmss(access_token, subscription_id, resource_group, vmssname) imagereference = vmssmodel['properties']['virtualMachineProfile']['storageProfile']['imageReference'] except KeyError: statusmsg('KeyError: azurerm.get_vmss() returned: ' + vmssmodel) return if imagereference['version'] != newversion: vmssmodel['properties']['virtualMachineProfile']['storageProfile']['imageReference']['version'] = newversion # put the vmss model updateresult = azurerm.update_vmss(access_token, subscription_id, resource_group, vmssname, json.dumps(vmssmodel)) statusmsg(updateresult) else: statusmsg('Versions are the same, skipping update')
def getvmss(rgname, vmssname): global vmss_properties try: vmssget = azurerm.get_vmss(access_token, subscription_id, rgname, vmssname) vmss_properties['name'] = vmssget['name'] vmss_properties['capacity'] = vmssget['sku']['capacity'] vmss_properties['location'] = vmssget['location'] vmss_properties['vmsize'] = vmssget['sku']['name'] vmss_properties['tier'] = vmssget['sku']['tier'] vmss_properties['offer'] = vmssget['properties']['virtualMachineProfile']['storageProfile']['imageReference'][ 'offer'] vmss_properties['version'] = vmssget['properties']['virtualMachineProfile']['storageProfile']['imageReference'][ 'version'] vmss_properties['sku'] = vmssget['properties']['virtualMachineProfile']['storageProfile']['imageReference'][ 'sku'] vmss_properties['provisioningState'] = vmssget['properties']['provisioningState'] except KeyError: statusmsg('KeyError: azurerm.get_vmss() returned: ' + json.dumps(vmssget)) return # get an instance view list in order to build a heatmap vmssinstances = azurerm.list_vmss_vm_instance_view(access_token, subscription_id, rgname, vmssname) draw_vms(vmssinstances)
def exec_cmd(window, access_token, cap, cmd): global subscription_id, rgname, vmssname, vmsku, tier, vm_selected, window_vm, panel_vm, vm_details, vm_nic, page, insights_flag; #Return codes... initerror = 2; syntaxerror = 3; capacityerror = 4; execsuccess = 0; execerror = 1; #Sanity check on capacity... if (cap == "999999"): return initerror; if not (isinstance(cap, int)): return initerror; #Syntax check... if (len(cmd.split()) != 4 and len(cmd.split()) != 3): return syntaxerror; counter = 0; for c in cmd.split(): if (counter == 0): if (c == "add" or c == "del" or c == "rg" or c == "select" or c == "show"): op = c; else: return syntaxerror; if (counter == 1 and op == "show" and c != "page"): return syntaxerror; if (counter == 1 and c != "vm") and (op == "add" or op == "del" or op == "select"): return syntaxerror; if (counter == 1 and op == "rg"): rgname_new = c; if (counter == 2) and (op == "add" or op == "del" or op == "select" or op == "show"): try: a = int(c) + 1; qtd = int(c); except: return syntaxerror; if (counter == 2 and op == "select"): z = 0; ifound = 0; while (z < instances_deployed.__len__()): if (instances_deployed[z] == int(c)): ifound = 1; break; z += 1; if (ifound): vm = int(c); else: return execerror; if (counter == 2 and op == "rg" and c != "vmss"): return syntaxerror; if (counter == 2 and op == "show"): try: a = int(c) + 1; if (int(c) == page): return execsuccess; if (int(c) > 1): b = ((window_vm.__len__() / (int(c) - 1))); if (b <= 100 or (int(c)) <= 0): return syntaxerror; else: page_new = int(c); elif (int(c) == 1): page_new = int(c); else: return syntaxerror; except: return syntaxerror; if (counter == 3 and op == "rg"): vmssname_new = c; counter += 1; #Execution... if (op == "add" or op == "del"): if (qtd > 99): return capacityerror; #Scale-in or Scale-out... if (op == "add"): newCapacity = cap + int(c); else: newCapacity = cap - int(c); #Ok, everything seems fine, let's do it... #Change the VM scale set capacity by 'qtd' (can be positive or negative for scale-out/in) #The interface for scale_vmss changed from 7 to just 5 arguments... #scaleoutput = azurerm.scale_vmss(access_token, subscription_id, rgname, vmssname, vmsku, tier, newCapacity); scaleoutput = azurerm.scale_vmss(access_token, subscription_id, rgname, vmssname, newCapacity); if (scaleoutput.status_code == 200): return execsuccess; else: return execerror; elif (op == "select"): vm_selected[1] = vm_selected[0]; vm_selected[0] = vm; vm_details_old = vm_details; vm_nic_old = vm_nic; vm_details = azurerm.get_vmss_vm_instance_view(access_token, subscription_id, rgname, vmssname, vm_selected[0]); #vm_nic = azurerm.get_vmss_vm_nics(access_token, subscription_id, rgname, vmssname, vm_selected[0]); #if (len(vm_details) > 0 and len(vm_nic) > 0): if (len(vm_details) > 0): return execsuccess; else: vm_details = vm_details_old; vm_nic = vm_nic_old; vm_selected[1] = 999998; return execerror; elif (op == "show"): unset_page(); set_page(window, page_new); return execsuccess; else: #Test to be sure the resource group and vmss provided do exist... rgoutput = azurerm.get_vmss(access_token, subscription_id, rgname_new, vmssname_new); try: test = rgoutput['location']; rgname = rgname_new; vmssname = vmssname_new; #Just a flag for us to know that we changed the vmss and need to deselect any VM... vm_selected[1] = 999998; #We need to clear the Insights graph too... insights_flag = 1; page = 1; return execsuccess; except: return execerror;
configData = json.load(configFile) except FileNotFoundError: print("Error: Expecting vmssConfig.json in current folder") sys.exit() tenant_id = configData['tenantId'] app_id = configData['appId'] app_secret = configData['appSecret'] subscription_id = configData['subscriptionId'] rg = configData['resourceGroup'] vmss = configData['vmssName'] access_token = azurerm.get_access_token(tenant_id, app_id, app_secret) print('Printing VMSS details\n') vmssget = azurerm.get_vmss(access_token, subscription_id, rg, vmss) name = vmssget['name'] capacity = vmssget['sku']['capacity'] location = vmssget['location'] offer = vmssget['properties']['virtualMachineProfile']['storageProfile'][ 'imageReference']['offer'] sku = vmssget['properties']['virtualMachineProfile']['storageProfile'][ 'imageReference']['sku'] print(json.dumps(vmssget, sort_keys=False, indent=2, separators=(',', ': '))) print('Name: ' + name + ', capacity: ' + str(capacity) + ', ' + location + ', ' + offer + ', ' + sku) print('\nPrinting VMSS instance view\n') instanceView = azurerm.get_vmss_instance_view(access_token, subscription_id, rg, vmss) print( json.dumps(instanceView, sort_keys=False, indent=2,
def get_vmss_properties(access_token, run_event, window_information, panel_information, window_continents, panel_continents): global vmssProperties, vmssVmProperties, countery, capacity, region, tier, vmsku, vm_selected, window_vm, panel_vm, instances_deployed, vm_details, vm_nic, page; ROOM = 5; DEPLOYED = 0; #VM's destination... destx = 22; desty = 4; XS =50; YS = 4; init_coords = (XS, YS); window_dc = 0; #Our window_information arrays... panel_vm = []; window_vm = []; #Our thread loop... while run_event.is_set(): try: #Timestamp... ourtime = time.strftime("%H:%M:%S"); write_str(window_information['status'], 1, 13, ourtime); #Clean Forms... clean_forms(window_information); #Get VMSS details vmssget = azurerm.get_vmss(access_token, subscription_id, rgname, vmssname); # Get public ip address for RG (First IP) - modify this if your RG has multiple ips net = azurerm.list_public_ips(access_token, subscription_id, rgname); #Clean Info and Sys Windows... clean_infoandsys(window_information); #Fill the information... fill_vmss_info(window_information, vmssget, net); #Set VMSS variables... (name, capacity, location, offer, sku, provisioningState, dns, ipaddr) = set_vmss_variables(vmssget, net); #Set the current and old location... old_location = region; if (old_location != ""): continent_old_location = get_continent_dc(old_location); #New region = location; continent_location = get_continent_dc(location); #Quota... quota = azurerm.get_compute_usage(access_token, subscription_id, location); fill_quota_info(window_information, quota); #Mark Datacenter where VMSS is deployed... if (old_location != ""): if (old_location != location): #Now switch the datacenter mark on map... new_window_dc = mark_vmss_dc(continent_old_location, window_continents[continent_old_location], old_location, window_continents[continent_location], location, window_dc); window_dc = new_window_dc; else: new_window_dc = mark_vmss_dc(continent_location, window_continents[continent_location], location, window_continents[continent_location], location, window_dc); window_dc = new_window_dc; #Our arrays... vmssProperties = [name, capacity, location, rgname, offer, sku, provisioningState, dns, ipaddr]; vmssvms = azurerm.list_vmss_vms(access_token, subscription_id, rgname, vmssname); vmssVmProperties = []; #All VMs are created in the following coordinates... qtd = vmssvms['value'].__len__(); factor = (vmssvms['value'].__len__() / 100); write_str(window_information['system'], 3, 22, qtd); step = qtd / 10; if (step < 1): step = 1; #We take more time on our VM effect depending on how many VMs we are talking about... if (qtd < 10): ts = 0.01; elif (qtd < 25): ts = 0.005; elif (qtd < 50): ts = 0.002; elif (qtd < 100): ts = 0.0005; else: ts = 0; counter = 1; counter_page = 0; nr_pages = 1; snap_page = page; page_top = (snap_page * 100); page_base = ((snap_page - 1) * 100); if (vm_selected[1] == 999998): #Clean VM Info... clean_vm(window_information); #Loop each VM... for vm in vmssvms['value']: instanceId = vm['instanceId']; write_str(window_information['monitor'], 1, 30, instanceId); wrefresh(window_information['monitor']); vmsel = 0; vmName = vm['name']; provisioningState = vm['properties']['provisioningState']; vmssVmProperties.append([instanceId, vmName, provisioningState]); if (counter > DEPLOYED): window_vm.append(DEPLOYED); panel_vm.append(DEPLOYED); instances_deployed.append(DEPLOYED); instances_deployed[DEPLOYED] = int(instanceId); #Prepare the place for the VM icon... if countery < 10: countery += 1; else: destx += 3; desty = 4; countery = 1; if (counter_page > 99): destx = 22; counter_page = 0; nr_pages += 1; cur_page = "%02d" % snap_page; tot_pages = "%02d" % nr_pages; update_vm_footer(window_information, cur_page, tot_pages); else: counter_page += 1; window_vm[DEPLOYED] = create_window(3, 5, init_coords[0], init_coords[1]); panel_vm[DEPLOYED] = new_panel(window_vm[DEPLOYED]); #Show only VM's that are on the visible window... if (page_top > DEPLOYED and DEPLOYED >= page_base): show_panel(panel_vm[DEPLOYED]); else: hide_panel(panel_vm[DEPLOYED]); box(window_vm[DEPLOYED]); #Creation of the VM icon, in this flow we never have a VM selected... draw_vm(int(instanceId), window_vm[DEPLOYED], provisioningState, vmsel); vm_animation(panel_vm[DEPLOYED], init_coords, destx, desty, 1, ts); desty += ROOM; DEPLOYED += 1; else: instances_deployed[counter - 1] = int(instanceId); #Remove the old mark... vmsel = deselect_vm(window_vm, panel_information, instanceId, counter); #Show only VM's that are on the visible window... if (page_top > (counter - 1) and (counter - 1) >= page_base): show_panel(panel_vm[counter -1]); else: hide_panel(panel_vm[counter -1]); #Creation of the VM icon... draw_vm(int(instanceId), window_vm[counter - 1], provisioningState, vmsel); #If a VM is selected, fill the details... if (vm_selected[0] == int(instanceId) and vm_selected[1] != 999998): vm_details = azurerm.get_vmss_vm_instance_view(access_token, subscription_id, rgname, vmssname, vm_selected[0]); vm_nic = azurerm.get_vmss_vm_nics(access_token, subscription_id, rgname, vmssname, vm_selected[0]); clean_vm(window_information); if (vm_details != "" and vm_nic != ""): fill_vm_details(window_information, instanceId, vmName, provisioningState); update_panels(); doupdate(); counter += 1; do_update_bar(window_information['status'], step, 0); step += step; #Last mile... write_str(window_information['monitor'], 1, 30, "Done."); do_update_bar(window_information['status'], step, 1); #Remove destroyed VMs... counter_page = 0; if (DEPLOYED >= counter): time.sleep(0.5); write_str_color(window_information['monitor'], 1, 30, "Removing VM's...", 7, 0); wrefresh(window_information['monitor']); time.sleep(1); clean_monitor_form(window_information); while (DEPLOYED >= counter): write_str(window_information['monitor'], 1, 30, DEPLOYED); lastvm = window_vm.__len__() - 1; vm_coords = getbegyx(window_vm[lastvm]); vm_animation(panel_vm[lastvm], vm_coords, init_coords[0], init_coords[1], 0, ts); if (countery > 0): desty -= ROOM; countery -= 1; elif (destx > 22): destx -= 3; desty = 49; countery = 9; if (counter_page > 99): destx = 52; counter_page = 0; nr_pages -= 1; tot_pages = "%02d" % nr_pages; cur_page = "%02d" % page; update_vm_footer(window_information, cur_page, tot_pages); else: counter_page += 1; #Clean VM Info... if (vm_selected[0] == instances_deployed[lastvm]): clean_vm(window_information); #Free up some memory... del_panel(panel_vm[lastvm]); delwin(window_vm[lastvm]); wobj = panel_vm[lastvm]; panel_vm.remove(wobj); wobj = window_vm[lastvm]; window_vm.remove(wobj); wobj = instances_deployed[lastvm]; instances_deployed.remove(wobj); DEPLOYED -= 1; update_panels(); doupdate(); write_str(window_information['monitor'], 1, 30, "Done."); ourtime = time.strftime("%H:%M:%S"); do_update_bar(window_information['status'], step, 1); write_str(window_information['status'], 1, 13, ourtime); write_str_color(window_information['status'], 1, 22, " OK ", 6, 0); update_panels(); doupdate(); # sleep before each loop to avoid throttling... time.sleep(interval); except: logging.exception("Getting VMSS Information...") write_str(window_information['error'], 1, 24, "Let's sleep for 30 seconds and try to refresh the dashboard again..."); show_panel(panel_information['error']); update_panels(); doupdate(); ## break out of loop when an error is encountered #break time.sleep(30); hide_panel(panel_information['error']);
def main(): # create parser argParser = argparse.ArgumentParser() argParser.add_argument('--vmssname', '-s', required=True, action='store', help='VM Scale Set name') argParser.add_argument('--resourcegroup', '-r', required=True, dest='resource_group', action='store', help='Resource group name') argParser.add_argument('--newversion', '-n', dest='newversion', action='store', help='New platform image version string') argParser.add_argument('--customuri', '-c', dest='customuri', action='store', help='New custom image URI string') argParser.add_argument('--updatedomain', '-u', dest='updatedomain', action='store', type=int, help='Update domain (int)') argParser.add_argument('--vmid', '-i', dest='vmid', action='store', type=int, help='Single VM ID (int)') argParser.add_argument('--vmlist', '-l', dest='vmlist', action='store', help='List of VM IDs e.g. "["1", "2"]"') argParser.add_argument('--nowait', '-w', action='store_true', default=False, help='Start upgrades and then exit without waiting') argParser.add_argument('--verbose', '-v', action='store_true', default=False, help='Show additional information') argParser.add_argument('-y', dest='noprompt', action='store_true', default=False, help='Do not prompt for confirmation') args = argParser.parse_args() # switches to determine program behavior noprompt = args.noprompt # go ahead and upgrade without waiting for confirmation when True nowait = args.nowait # don't loop waiting for upgrade provisioning to complete when True verbose = args.verbose # print extra status information when True vmssname = args.vmssname resource_group = args.resource_group if args.newversion is not None: newversion = args.newversion storagemode = 'platform' elif args.customuri is not None: customuri = args.customuri storagemode = 'custom' else: argParser.error( 'You must specify a new version for platform images or a custom uri for custom images' ) if args.updatedomain is not None: updatedomain = args.updatedomain upgrademode = 'updatedomain' elif args.vmid is not None: vmid = args.vmid upgrademode = 'vmid' elif args.vmlist is not None: vmlist = args.vmlist upgrademode = 'vmlist' else: argParser.error( 'You must specify an update domain, a vm id, or a vm list') # Load Azure app defaults try: with open('vmssconfig.json') as configFile: configdata = json.load(configFile) except FileNotFoundError: print("Error: Expecting vmssconfig.json in current folder") sys.exit() tenant_id = configdata['tenantId'] app_id = configdata['appId'] app_secret = configdata['appSecret'] subscription_id = configdata['subscriptionId'] access_token = azurerm.get_access_token(tenant_id, app_id, app_secret) # get the vmss model vmssmodel = azurerm.get_vmss(access_token, subscription_id, resource_group, vmssname) # print(json.dumps(vmssmodel, sort_keys=False, indent=2, separators=(',', ': '))) if storagemode == 'platform': # check current version imagereference = vmssmodel['properties']['virtualMachineProfile'][ 'storageProfile']['imageReference'] print('Current image reference in Scale Set model:') print( json.dumps(imagereference, sort_keys=False, indent=2, separators=(',', ': '))) # compare current version with new version if imagereference['version'] == newversion: print('Scale Set model version is already set to ' + newversion + ', skipping model update.') else: if not noprompt: response = input('Confirm version upgrade to: ' + newversion + ' (y/n)') if response.lower() != 'y': sys.exit(1) # change the version vmssmodel['properties']['virtualMachineProfile']['storageProfile'][ 'imageReference']['version'] = newversion # put the vmss model updateresult = azurerm.update_vmss(access_token, subscription_id, resource_group, vmssname, json.dumps(vmssmodel)) if verbose: print(updateresult) print('OS version updated to ' + newversion + ' in model for VM Scale Set: ' + vmssname) else: # storagemode = custom # check current uri oldimageuri = vmssmodel['properties']['virtualMachineProfile'][ 'storageProfile']['osDisk']['image']['uri'] print('Current image URI in Scale Set model:' + oldimageuri) # compare current uri with new uri if oldimageuri == customuri: print('Scale Set model version is already set to ' + customuri + ', skipping model update.') else: if not noprompt: response = input('Confirm uri upgrade to: ' + customuri + ' (y/n)') if response.lower() != 'y': sys.exit(1) # change the version vmssmodel['properties']['virtualMachineProfile']['storageProfile'][ 'osDisk']['image']['uri'] = customuri # put the vmss model updateresult = azurerm.update_vmss(access_token, subscription_id, resource_group, vmssname, json.dumps(vmssmodel)) if verbose: print(updateresult) print('Image URI updated to ' + customuri + ' in model for VM Scale Set: ' + vmssname) # build the list of VMs to upgrade depending on the upgrademode setting if upgrademode == 'updatedomain': # list the VMSS VM instance views to determine their update domains print('Examining the scale set..') udinstancelist = get_vm_ids_by_ud(access_token, subscription_id, resource_group, vmssname, updatedomain) print('VM instances in UD: ' + str(updatedomain) + ' to upgrade:') print(udinstancelist) vmids = json.dumps(udinstancelist) print('Upgrading VMs in UD: ' + str(updatedomain)) elif upgrademode == 'vmid': vmids = json.dumps([str(vmid)]) print('Upgrading VM ID: ' + str(vmid)) else: # upgrademode = vmlist vmids = vmlist print('Upgrading VM IDs: ' + vmlist) # do manualupgrade on the VMs in the list upgraderesult = azurerm.upgrade_vmss_vms(access_token, subscription_id, resource_group, vmssname, vmids) print(upgraderesult) # now wait for upgrade to complete # query VM scale set instance view if not nowait: updatecomplete = False provisioningstate = '' while not updatecomplete: vmssinstanceview = azurerm.get_vmss_instance_view( access_token, subscription_id, resource_group, vmssname) for status in vmssinstanceview['statuses']: provisioningstate = status['code'] if provisioningstate == 'ProvisioningState/succeeded': updatecomplete = True if verbose: print(provisioningstate) time.sleep(5) print(status['code']) else: print( 'Check Scale Set provisioning state to determine when upgrade is complete.' )
def main(): # create parser argParser = argparse.ArgumentParser() argParser.add_argument('--vmssname', '-s', required=True, action='store', help='VM Scale Set name') argParser.add_argument('--resourcegroup', '-r', required=True, dest='resource_group', action='store', help='Resource group name') argParser.add_argument('--newversion', '-n', dest='newversion', action='store', help='New platform image version string') argParser.add_argument('--customuri', '-c', dest='customuri', action='store', help='New custom image URI string') argParser.add_argument('--updatedomain', '-u', dest='updatedomain', action='store', type=int, help='Update domain (int)') argParser.add_argument('--vmid', '-i', dest='vmid', action='store', type=int, help='Single VM ID (int)') argParser.add_argument('--vmlist', '-l', dest='vmlist', action='store', help='List of VM IDs e.g. "["1", "2"]"') argParser.add_argument('--nowait', '-w', action='store_true', default=False, help='Start upgrades and then exit without waiting') argParser.add_argument('--verbose', '-v', action='store_true', default=False, help='Show additional information') argParser.add_argument('-y', dest='noprompt', action='store_true', default=False, help='Do not prompt for confirmation') args = argParser.parse_args() # switches to determine program behavior noprompt = args.noprompt # go ahead and upgrade without waiting for confirmation when True nowait = args.nowait # don't loop waiting for upgrade provisioning to complete when True verbose = args.verbose # print extra status information when True vmssname = args.vmssname resource_group = args.resource_group if args.newversion is not None: newversion = args.newversion storagemode = 'platform' elif args.customuri is not None: customuri = args.customuri storagemode = 'custom' else: argParser.error('You must specify a new version for platform images or a custom uri for custom images') if args.updatedomain is not None: updatedomain = args.updatedomain upgrademode = 'updatedomain' elif args.vmid is not None: vmid = args.vmid upgrademode = 'vmid' elif args.vmlist is not None: vmlist = args.vmlist upgrademode = 'vmlist' else: argParser.error('You must specify an update domain, a vm id, or a vm list') # Load Azure app defaults try: with open('vmssconfig.json') as configFile: configdata = json.load(configFile) except FileNotFoundError: print("Error: Expecting vmssconfig.json in current folder") sys.exit() tenant_id = configdata['tenantId'] app_id = configdata['appId'] app_secret = configdata['appSecret'] subscription_id = configdata['subscriptionId'] access_token = azurerm.get_access_token(tenant_id, app_id, app_secret) # get the vmss model vmssmodel = azurerm.get_vmss(access_token, subscription_id, resource_group, vmssname) # print(json.dumps(vmssmodel, sort_keys=False, indent=2, separators=(',', ': '))) if storagemode == 'platform': # check current version imagereference = vmssmodel['properties']['virtualMachineProfile']['storageProfile']['imageReference'] print('Current image reference in Scale Set model:') print(json.dumps(imagereference, sort_keys=False, indent=2, separators=(',', ': '))) # compare current version with new version if imagereference['version'] == newversion: print('Scale Set model version is already set to ' + newversion + ', skipping model update.') else: if not noprompt: response = input('Confirm version upgrade to: ' + newversion + ' (y/n)') if response.lower() != 'y': sys.exit(1) # change the version vmssmodel['properties']['virtualMachineProfile']['storageProfile']['imageReference']['version'] = newversion # put the vmss model updateresult = azurerm.update_vmss(access_token, subscription_id, resource_group, vmssname, json.dumps(vmssmodel)) if verbose: print(updateresult) print('OS version updated to ' + newversion + ' in model for VM Scale Set: ' + vmssname) else: # storagemode = custom # check current uri oldimageuri = vmssmodel['properties']['virtualMachineProfile']['storageProfile']['osDisk']['image']['uri'] print('Current image URI in Scale Set model:' + oldimageuri) # compare current uri with new uri if oldimageuri == customuri: print('Scale Set model version is already set to ' + customuri + ', skipping model update.') else: if not noprompt: response = input('Confirm uri upgrade to: ' + customuri + ' (y/n)') if response.lower() != 'y': sys.exit(1) # change the version vmssmodel['properties']['virtualMachineProfile']['storageProfile']['osDisk']['image']['uri'] = customuri # put the vmss model updateresult = azurerm.update_vmss(access_token, subscription_id, resource_group, vmssname, json.dumps(vmssmodel)) if verbose: print(updateresult) print('Image URI updated to ' + customuri + ' in model for VM Scale Set: ' + vmssname) # build the list of VMs to upgrade depending on the upgrademode setting if upgrademode == 'updatedomain': # list the VMSS VM instance views to determine their update domains print('Examining the scale set..') udinstancelist = get_vm_ids_by_ud(access_token, subscription_id, resource_group, vmssname, updatedomain) print('VM instances in UD: ' + str(updatedomain) + ' to upgrade:') print(udinstancelist) vmids = json.dumps(udinstancelist) print('Upgrading VMs in UD: ' + str(updatedomain)) elif upgrademode == 'vmid': vmids = json.dumps([str(vmid)]) print('Upgrading VM ID: ' + str(vmid)) else: # upgrademode = vmlist vmids = vmlist print('Upgrading VM IDs: ' + vmlist) # do manualupgrade on the VMs in the list upgraderesult = azurerm.upgrade_vmss_vms(access_token, subscription_id, resource_group, vmssname, vmids) print(upgraderesult) # now wait for upgrade to complete # query VM scale set instance view if not nowait: updatecomplete = False provisioningstate = '' while not updatecomplete: vmssinstanceview = azurerm.get_vmss_instance_view(access_token, subscription_id, resource_group, vmssname) for status in vmssinstanceview['statuses']: provisioningstate = status['code'] if provisioningstate == 'ProvisioningState/succeeded': updatecomplete = True if verbose: print(provisioningstate) time.sleep(5) print(status['code']) else: print('Check Scale Set provisioning state to determine when upgrade is complete.')
def get_vmss_properties(access_token, run_event, window_information, panel_information, window_continents, panel_continents): global vmssProperties, vmssVmProperties, countery, capacity, region, tier, vmsku, vm_selected, window_vm, panel_vm, instances_deployed, vm_details, vm_nic, page; ROOM = 5; DEPLOYED = 0; #VM's destination... destx = 22; desty = 4; XS =50; YS = 4; init_coords = (XS, YS); window_dc = 0; #Our window_information arrays... panel_vm = []; window_vm = []; #Our thread loop... while run_event.is_set(): try: #Timestamp... ourtime = time.strftime("%H:%M:%S"); write_str(window_information['status'], 1, 13, ourtime); #Clean Forms... clean_forms(window_information); #Get VMSS details vmssget = azurerm.get_vmss(access_token, subscription_id, rgname, vmssname); # Get public ip address for RG (First IP) - modify this if your RG has multiple ips net = azurerm.list_public_ips(access_token, subscription_id, rgname); #Clean Info and Sys Windows... clean_infoandsys(window_information); #Fill the information... fill_vmss_info(window_information, vmssget, net); #Set VMSS variables... (name, capacity, location, offer, sku, provisioningState, dns, ipaddr) = set_vmss_variables(vmssget, net); #Set the current and old location... old_location = region; if (old_location != ""): continent_old_location = get_continent_dc(old_location); #New region = location; continent_location = get_continent_dc(location); #Quota... quota = azurerm.get_compute_usage(access_token, subscription_id, location); fill_quota_info(window_information, quota); #Mark Datacenter where VMSS is deployed... if (old_location != ""): if (old_location != location): #Now switch the datacenter mark on map... new_window_dc = mark_vmss_dc(continent_old_location, window_continents[continent_old_location], old_location, window_continents[continent_location], location, window_dc); window_dc = new_window_dc; else: new_window_dc = mark_vmss_dc(continent_location, window_continents[continent_location], location, window_continents[continent_location], location, window_dc); window_dc = new_window_dc; #Our arrays... vmssProperties = [name, capacity, location, rgname, offer, sku, provisioningState, dns, ipaddr]; vmssvms = azurerm.list_vmss_vms(access_token, subscription_id, rgname, vmssname); vmssVmProperties = []; #All VMs are created in the following coordinates... qtd = vmssvms['value'].__len__(); factor = (vmssvms['value'].__len__() / 100); write_str(window_information['system'], 3, 22, qtd); step = qtd / 10; if (step < 1): step = 1; #We take more time on our VM effects depending on how many VMs we are talking about... if (qtd < 10): ts = 0.01; elif (qtd < 25): ts = 0.004; elif (qtd < 50): ts = 0.0008; elif (qtd < 100): ts = 0.0004; else: ts = 0; counter = 1; counter_page = 0; nr_pages = 1; snap_page = page; page_top = (snap_page * 100); page_base = ((snap_page - 1) * 100); if (vm_selected[1] == 999998): #Clean VM Info... clean_vm(window_information); #Loop each VM... for vm in vmssvms['value']: instanceId = vm['instanceId']; write_str(window_information['monitor'], 1, 30, instanceId); wrefresh(window_information['monitor']); vmsel = 0; vmName = vm['name']; provisioningState = vm['properties']['provisioningState']; vmssVmProperties.append([instanceId, vmName, provisioningState]); if (counter > DEPLOYED): window_vm.append(DEPLOYED); panel_vm.append(DEPLOYED); instances_deployed.append(DEPLOYED); instances_deployed[DEPLOYED] = int(instanceId); #Prepare the place for the VM icon... if countery < 10: countery += 1; else: destx += 3; desty = 4; countery = 1; if (counter_page > 99): destx = 22; counter_page = 0; nr_pages += 1; cur_page = "%02d" % snap_page; tot_pages = "%02d" % nr_pages; update_vm_footer(window_information, cur_page, tot_pages); else: counter_page += 1; window_vm[DEPLOYED] = create_window(3, 5, init_coords[0], init_coords[1]); panel_vm[DEPLOYED] = new_panel(window_vm[DEPLOYED]); #Show only VM's that are on the visible window... if (page_top > DEPLOYED and DEPLOYED >= page_base): show_panel(panel_vm[DEPLOYED]); else: hide_panel(panel_vm[DEPLOYED]); box(window_vm[DEPLOYED]); #Creation of the VM icon, in this flow we never have a VM selected... draw_vm(int(instanceId), window_vm[DEPLOYED], provisioningState, vmsel); vm_animation(panel_vm[DEPLOYED], init_coords, destx, desty, 1, ts); desty += ROOM; DEPLOYED += 1; else: instances_deployed[counter - 1] = int(instanceId); #Remove the old mark... vmsel = deselect_vm(window_vm, panel_information, instanceId, counter); #Show only VM's that are on the visible window... if (page_top > (counter - 1) and (counter - 1) >= page_base): show_panel(panel_vm[counter -1]); else: hide_panel(panel_vm[counter -1]); #Creation of the VM icon... draw_vm(int(instanceId), window_vm[counter - 1], provisioningState, vmsel); #If a VM is selected, fill the details... if (vm_selected[0] == int(instanceId) and vm_selected[1] != 999998): vm_details = azurerm.get_vmss_vm_instance_view(access_token, subscription_id, rgname, vmssname, vm_selected[0]); vm_nic = azurerm.get_vmss_vm_nics(access_token, subscription_id, rgname, vmssname, vm_selected[0]); clean_vm(window_information); if (vm_details != "" and vm_nic != ""): fill_vm_details(window_information, instanceId, vmName, provisioningState); update_panels(); doupdate(); counter += 1; do_update_bar(window_information['status'], step, 0); step += step; #Last mile... write_str(window_information['monitor'], 1, 30, "Done."); do_update_bar(window_information['status'], step, 1); #Remove destroyed VMs... counter_page = 0; if (DEPLOYED >= counter): time.sleep(0.5); write_str_color(window_information['monitor'], 1, 30, "Removing VM's...", 7, 0); wrefresh(window_information['monitor']); time.sleep(1); clean_monitor_form(window_information); while (DEPLOYED >= counter): write_str(window_information['monitor'], 1, 30, DEPLOYED); lastvm = window_vm.__len__() - 1; vm_coords = getbegyx(window_vm[lastvm]); vm_animation(panel_vm[lastvm], vm_coords, init_coords[0], init_coords[1], 0, ts); if (countery > 0): desty -= ROOM; countery -= 1; elif (destx > 22): destx -= 3; desty = 49; countery = 9; if (counter_page > 99): destx = 52; counter_page = 0; nr_pages -= 1; tot_pages = "%02d" % nr_pages; cur_page = "%02d" % page; update_vm_footer(window_information, cur_page, tot_pages); else: counter_page += 1; #Clean VM Info... if (vm_selected[0] == instances_deployed[lastvm]): clean_vm(window_information); #Free up some memory... del_panel(panel_vm[lastvm]); delwin(window_vm[lastvm]); wobj = panel_vm[lastvm]; panel_vm.remove(wobj); wobj = window_vm[lastvm]; window_vm.remove(wobj); wobj = instances_deployed[lastvm]; instances_deployed.remove(wobj); DEPLOYED -= 1; update_panels(); doupdate(); write_str(window_information['monitor'], 1, 30, "Done."); ourtime = time.strftime("%H:%M:%S"); do_update_bar(window_information['status'], step, 1); write_str(window_information['status'], 1, 13, ourtime); write_str_color(window_information['status'], 1, 22, " OK ", 6, 0); update_panels(); doupdate(); # sleep before each loop to avoid throttling... time.sleep(interval); except: logging.exception("Getting VMSS Information...") write_str(window_information['error'], 1, 24, "Let's sleep for 30 seconds and try to refresh the dashboard again..."); show_panel(panel_information['error']); update_panels(); doupdate(); ## break out of loop when an error is encountered #break time.sleep(30); hide_panel(panel_information['error']);
def exec_cmd(window, access_token, cap, cmd): global subscription_id, rgname, vmssname, vmsku, tier, vm_selected, window_vm, panel_vm, vm_details, vm_nic, page, insights_flag; #Return codes... initerror = 2; syntaxerror = 3; capacityerror = 4; execsuccess = 0; execerror = 1; #Sanity check on capacity... if (cap == "999999"): return initerror; if not (isinstance(cap, int)): return initerror; #Syntax check... if (len(cmd.split()) != 4 and len(cmd.split()) != 3): return syntaxerror; counter = 0; for c in cmd.split(): if (counter == 0): if (c == "add" or c == "del" or c == "rg" or c == "select" or c == "show"): op = c; else: return syntaxerror; if (counter == 1 and op == "show" and c != "page"): return syntaxerror; if (counter == 1 and c != "vm") and (op == "add" or op == "del" or op == "select"): return syntaxerror; if (counter == 1 and op == "rg"): rgname_new = c; if (counter == 2) and (op == "add" or op == "del" or op == "select" or op == "show"): try: a = int(c) + 1; qtd = int(c); except: return syntaxerror; if (counter == 2 and op == "select"): z = 0; ifound = 0; while (z < instances_deployed.__len__()): if (instances_deployed[z] == int(c)): ifound = 1; break; z += 1; if (ifound): vm = int(c); else: return execerror; if (counter == 2 and op == "rg" and c != "vmss"): return syntaxerror; if (counter == 2 and op == "show"): try: a = int(c) + 1; if (int(c) == page): return execsuccess; if (int(c) > 1): b = ((window_vm.__len__() / (int(c) - 1))); if (b <= 100 or (int(c)) <= 0): return syntaxerror; else: page_new = int(c); elif (int(c) == 1): page_new = int(c); else: return syntaxerror; except: return syntaxerror; if (counter == 3 and op == "rg"): vmssname_new = c; counter += 1; #Execution... if (op == "add" or op == "del"): if (qtd > 99): return capacityerror; #Scale-in or Scale-out... if (op == "add"): newCapacity = cap + int(c); else: newCapacity = cap - int(c); #Ok, everything seems fine, let's do it... #Change the VM scale set capacity by 'qtd' (can be positive or negative for scale-out/in) scaleoutput = azurerm.scale_vmss(access_token, subscription_id, rgname, vmssname, vmsku, tier, newCapacity); if (scaleoutput.status_code == 200): return execsuccess; else: return execerror; elif (op == "select"): vm_selected[1] = vm_selected[0]; vm_selected[0] = vm; vm_details_old = vm_details; vm_nic_old = vm_nic; vm_details = azurerm.get_vmss_vm_instance_view(access_token, subscription_id, rgname, vmssname, vm_selected[0]); #vm_nic = azurerm.get_vmss_vm_nics(access_token, subscription_id, rgname, vmssname, vm_selected[0]); #if (len(vm_details) > 0 and len(vm_nic) > 0): if (len(vm_details) > 0): return execsuccess; else: vm_details = vm_details_old; vm_nic = vm_nic_old; vm_selected[1] = 999998; return execerror; elif (op == "show"): unset_page(); set_page(window, page_new); return execsuccess; else: #Test to be sure the resource group and vmss provided do exist... rgoutput = azurerm.get_vmss(access_token, subscription_id, rgname_new, vmssname_new); try: test = rgoutput['location']; rgname = rgname_new; vmssname = vmssname_new; #Just a flag for us to know that we changed the vmss and need to deselect any VM... vm_selected[1] = 999998; #We need to clear the Insights graph too... insights_flag = 1; page = 1; return execsuccess; except: return execerror;
# app state variables vmssProperties = [] def scale_event(scaleNum, access_token): global vmssProperties global rgname global vmssname global subscription_id newCapacity = vmssProperties[1] + scaleNum scaleoutput = azurerm.scale_vmss(access_token, subscription_id, rgname, vmssname, 'Standard_A1', 'Standard', newCapacity) print(scaleoutput) access_token = azurerm.get_access_token(tenant_id, app_id, app_secret) vmssget = azurerm.get_vmss(access_token, subscription_id, rgname, vmssname) print(json.dumps(vmssget, sort_keys=False, indent=2, separators=(',', ': '))) name = vmssget['name'] print('Name: ' + name) location = vmssget['location'] print('Location: ' + location) capacity = vmssget['sku']['capacity'] print('Capacity: ' + str(capacity)) offer = vmssget['properties']['virtualMachineProfile']['storageProfile']['imageReference']['offer'] print('Offer: ' + offer) sku = vmssget['properties']['virtualMachineProfile']['storageProfile']['imageReference']['sku'] print('sku: ' + sku) provisioningState = vmssget['properties']['provisioningState'] print('provisioning state: ' + provisioningState) vmssProperties = [name, capacity, location, rgname, offer, sku, provisioningState]