def run_module(): """ Run the module """ module = AnsibleModule(argument_spec=dict( hostname=dict(type='str', required=True), username=dict(type='str', default='admin'), password=dict(type='str', required=True, no_log=True), name=dict(type='str'), descr=dict(type='str'), state=dict( type='str', default='present', choices=['present', 'absent']))) from ucsmsdk.ucshandle import UcsHandle from ucsmsdk.mometa.org.OrgOrg import OrgOrg handle = UcsHandle(module.params['hostname'], module.params['username'], module.params['password']) handle.login() ucs_mo = OrgOrg(parent_mo_or_dn='org-root', name=module.params['name'], descr=module.params['descr']) handle.add_mo(ucs_mo, modify_present=True) handle.commit() handle.logout() # TODO: Add delete object code result = dict(changed=True) module.exit_json(**result)
def update_usrlbl(usrlbl): """ Update object usrlbl, ComputeBlade,ComputeRackUnit, LsServer""" handle = UcsHandle(UCS_HOST, UCS_USER, UCS_PASS) handle.login() usrlbl_classes = ['computeblade', 'computerackunit', 'lsserver'] for usrlbl_class in usrlbl_classes: compute_mos = handle.query_classid(usrlbl_class) for compute_mo in compute_mos: if '/blade-' in compute_mo.dn: print('blade', compute_mo.dn, 'usrlbl', compute_mo.usr_lbl) compute_mo.usr_lbl = usrlbl elif '/rackunit-' in compute_mo.dn: print('rack', compute_mo.dn, 'usrlbl', compute_mo.usr_lbl) compute_mo.usr_lbl = usrlbl elif '/ls-' in compute_mo.dn: print('service profile', compute_mo.dn, 'usrlbl', compute_mo.usr_lbl) compute_mo.usr_lbl = usrlbl handle.add_mo(compute_mo, modify_present=True) handle.commit()
def main(): handle = UcsHandle("192.168.254.200","ucspe","ucspe", secure=False) handle.login() # Query Blades that are unassociated print("\n\n=== Query Based on Class Name with Filter equal to") filter = "(oper_state,'unassociated',type='eq')".format(BLADE_MODEL) blades = handle.query_classid("computeBlade",filter_str=filter) print("***Found {} Blades".format(len(blades))) # Error Check for available blades if len(blades) < NUM_SP: error = "There are only {} blades left to associate, and you asked for {} Servers to be generated".format(len(blades),NUM_SP) raise NameError(error) # Setup Variable for SP Templates to be deployed dn_set = DnSet() for i in range(1, NUM_SP+1): dn = Dn() sp_name = "SP{}".format(str(i)) dn.attr_set("value", sp_name) dn_set.child_add(dn) # Build XML Object to submit to the API templates = ls_instantiate_n_named_template( cookie=handle.cookie, dn="org-root/ls-globotemplate", in_target_org="org-root", in_error_on_existing="false", in_name_set=dn_set ) # Send XML Object to xml process handler sp_list = handle.process_xml_elem(templates) # Loop through each created sp, and associate them to blades i = 0 while i < len(sp_list): sp = sp_list[i] blade = blades[i] # Print SP and Blade Combination print(sp.dn,blade.dn) # Get Binding Object mo = LsBinding( parent_mo_or_dn=sp.dn, pn_dn=blade.dn, restrict_migration="no" ) # Add MO Binding Object to handler handle.add_mo(mo,modify_present=True) i=i+1 # Bundle the SP Associates handle.commit()
def updateNtp(module): ucs_ip = module.params['ucs_ip'] ucs_user = module.params['ucs_user'] ucs_pass = module.params['ucs_pass'] ntp = module.params['ntp'] state = module.params['state'] results = {} results['changed'] = False results['created'] = [] results['removed'] = [] # Login to UCS try: handle = UcsHandle(ucs_ip, ucs_user, ucs_pass) except: module.fail_json(msg="Could not login to UCS") try: # Obtain a handle for the Timezone object tz = handle.query_classid(class_id="CommDateTime") if type(ntp) != list: ntp = list(ntp) for server in ntp: filter_str = '(name, "%s", type="eq")' % (server) obj = handle.query_children( in_mo=tz[0], class_id="CommNtpProvider", filter_str=filter_str ) if state == 'present' and len(obj) > 0: pass elif state == 'present' and len(obj) == 0: ntp_server = CommNtpProvider(tz[0], name=server) handle.add_mo(ntp_server) handle.commit() results['created'].append(server) results['changed'] = True elif state == 'absent' and len(obj) > 0: handle.remove_mo(obj[0]) handle.commit() results['changed'] = True results['removed'].append(server) except Exception, e: module.fail_json(msg="Could not create or validate servers; %s" % e)
def add_vlan_to_vnic_template(): """ Add VLAN to VNIC Template """ handle = UcsHandle(UCS_HOST, UCS_USER, UCS_PASS) handle.login() my_vlan = handle.query_classid("fabricVlan", filter_str='(id,"301")') my_templ = handle.query_classid("vnicLanConnTempl", filter_str='(name,"Trunk_B")') VnicEtherIf(parent_mo_or_dn=my_templ[0], default_net=my_vlan[0].default_net, name=my_vlan[0].name) handle.add_mo(my_templ[0], True) handle.commit()
def updateVlans(module): ucs_ip = module.params['ucs_ip'] ucs_user = module.params['ucs_user'] ucs_pass = module.params['ucs_pass'] vlans = module.params['vlans'] state = module.params['state'] results = {} results['changed'] = False results['created'] = [] results['removed'] = [] # Login to UCS try: handle = UcsHandle(ucs_ip, ucs_user, ucs_pass) except: module.fail_json(msg="Could not login to UCS") try: # Obtain a handle for the LAN Cloud lancloud = handle.query_classid(class_id="FabricLanCloud") defined_vlans = handle.query_children(in_mo=lancloud[0], class_id="FabricVlan") for key, val in vlans.iteritems(): filter_str = '(name, "%s", type="eq") and (id, %s, type="eq")' \ % (key, val) obj = handle.query_children(in_mo=lancloud[0], class_id="FabricVlan", filter_str=filter_str) if state == 'present' and len(obj) > 0: pass elif state == 'present' and len(obj) == 0: vlan = FabricVlan(lancloud[0], name=key, id=str(val)) handle.add_mo(vlan) handle.commit() results['created'].append(key) results['changed'] = True elif state == 'absent' and len(obj) > 0: handle.remove_mo(obj[0]) handle.commit() results['changed'] = True results['removed'].append(key) except Exception, e: module.fail_json(msg="Could not create or validate VLANs; %s" % e)
def create_UCS_VLAN(vl_range): handle = UcsHandle(credentials.UCS_login['ipaddr'], credentials.UCS_login['username'], credentials.UCS_login['password']) handle.login() for vlan_id in vl_range: mo = FabricVlan(parent_mo_or_dn="fabric/lan", sharing="none", name="ACI-" + vlan_id, id=vlan_id, mcast_policy_name="", policy_owner="local", default_net="no", pub_nw_name="", compression_type="included") handle.add_mo(mo) handle.commit()
def add_ucs_bios_policy(): """ Add UCS BIOS Policy """ handle = UcsHandle(UCS_HOST, UCS_USER, UCS_PASS) handle.login() mo_bios_policy = BiosVProfile(parent_mo_or_dn='org-root', name='test-bios-prof', reboot_on_update='yes') BiosVfQuietBoot(parent_mo_or_dn=mo_bios_policy, vp_quiet_boot='disabled') BiosVfResumeOnACPowerLoss(parent_mo_or_dn=mo_bios_policy, vp_resume_on_ac_power_loss='stay-off') BiosVfConsoleRedirection(parent_mo_or_dn=mo_bios_policy, vp_baud_rate='9600', vp_console_redirection='com-0', vp_terminal_type='pc-ansi') handle.add_mo(mo_bios_policy, modify_present=True) handle.commit()
def main(): handle = UcsHandle("192.168.254.200", "ucspe", "ucspe", secure=False) handle.login() # Get Parrent Object lan_cloud = handle.query_classid("FabricLanCloud") # Create new VLAN Object for vlan 100 vlan_mo = FabricVlan(parent_mo_or_dn=lan_cloud[0], name="vlan100", id="100") # Add the object to be ready to be committed handle.add_mo(vlan_mo) # Commit changes back to UCS handle.commit() handle.logout()
# Here the environment variable is called 'MY_SECURE_PASSWORD' which # contains your secret password. username = '******' # UCS Manager username password = '******' # UCS Manager password # Create a connection handle # You can reserve the Cisco DEVNET UCS sanbox and use it # for the following example. handle = UcsHandle("10.10.20.113", username, password) # Login to the server handle.login() # Query the class FabricLanCloud which contains VLANs info fabric_lan_cloud = handle.query_classid("FabricLanCloud") # Create the VLAN 123 # 'id' and 'name' are mandatory arguments vlan123 = FabricVlan(parent_mo_or_dn=fabric_lan_cloud[0], name="vlan123", id="123") # Add the VLAN 123 object to the object handle using the add_mo method. handle.add_mo(vlan123) # Commit the change to add the VLAN 123 to the UCS Manager handle.commit() # Logout from the server handle.logout()
# Get a handle and login to UCS Manager from ucsmsdk.ucshandle import UcsHandle handle = UcsHandle("198.18.133.91", "admin", "password") handle.login() # Query for compute blades that are not associated blades = handle.query_classid("computeBlade") for blade in blades: if blade.association == "none": print(blade.dn, blade.association) # Create the Python_Heroes Organization from ucsmsdk.mometa.org.OrgOrg import OrgOrg root_org = handle.query_dn("org-root") mo_org = OrgOrg(parent_mo_or_dn=root_org, name="Python_Heroes") handle.add_mo(mo_org, modify_present=True) handle.commit() # Create the CommanderCode_Python_Server Service Profile from ucsmsdk.mometa.ls.LsServer import LsServer sp_org = handle.query_dn("org-root/org-Python_Heroes") mo_sp = LsServer(parent_mo_or_dn=sp_org, name="CommanderCode_Python_Server") handle.add_mo(mo_sp, modify_present=True) handle.commit() # Add a MAC block to the default MAC Pool from ucsmsdk.mometa.macpool.MacpoolBlock import MacpoolBlock mac_pool_default = handle.query_dn("org-root/mac-pool-default") mo_mac_pool_block = MacpoolBlock(parent_mo_or_dn=mac_pool_default, r_from="00:25:B5:00:00:AA", to="00:25:B5:00:00:D9")
from ucsmsdk.ucshandle import UcsHandle from ucsmsdk.mometa.fabric.FabricVlan import FabricVlan handle = UcsHandle("198.18.133.91", "admin", "C1sco12345") handle.login() fabric_lan_cloud = handle.query_classid("FabricLanCloud") vlan_ids = ['300', '301', '302', '303', '304', '305'] for vlan_id in vlan_ids: add_vlan = FabricVlan(parent_mo_or_dn=fabric_lan_cloud[0], name="vlan" + vlan_id, id=vlan_id) handle.add_mo(add_vlan) handle.commit() handle.logout() input("Vlans Added - Press Enter to Continue to Set Vlans...") # Set Vlans is a transaction from ucsmsdk.ucshandle import UcsHandle handle = UcsHandle("198.18.133.91", "admin", "C1sco12345") handle.login() vlan_ids = ['300', '301', '302', '303', '304', '305'] for vlan_id in vlan_ids:
"").replace("}", "").replace('"', "").split(":")[1] ucs_list = [] for host in ucs_list: sysLocation = host.split(".")[2 - 3].upper() handle = UcsHandle(host, "rdeviate", user_pass) handle.login() mo_enable_snmp = CommSnmp(parent_mo_or_dn="sys/svc-ext", admin_state="enabled", sys_contact="*****@*****.**", sys_location=sysLocation) mo_user_snmp = CommSnmpUser(parent_mo_or_dn="sys/svc-ext/snmp-svc", auth="sha", name="cs-snmp", privpwd=snmpv3_pass, pwd=snmpv3_pass, use_aes="yes") handle.add_mo(mo_enable_snmp, True) handle.add_mo(mo_user_snmp) handle.commit() handle.logout()
## Mission: Programming Cisco Compute - Python Basic and Advanced ## Mission Exercise 2 - Solution # Get a handle and login to UCS Manager from ucsmsdk.ucshandle import UcsHandle handle = UcsHandle("198.18.133.91", "admin", "password") handle.login() # Import Classes ComputePool and ComputePooledSlot from ucsmsdk.mometa.compute.ComputePool import ComputePool from ucsmsdk.mometa.compute.ComputePooledSlot import ComputePooledSlot # Create a ComputePool Object mo_pool = ComputePool(parent_mo_or_dn="org-root", name="Python_Heroes_Server_Pool") handle.add_mo(mo_pool, modify_present=True) handle.commit() # Retrieve the ComputePool object and add Servers filter_exp = '(name,"Python_Heroes_Server_Pool")' mo_compute_pool = handle.query_classid("computePool",filter_str=filter_exp) for slot_num in 1,2,3,4: mo_compute_pooled_slot = ComputePooledSlot(parent_mo_or_dn=mo_compute_pool[0].dn, chassis_id="2", slot_id=str(slot_num)) handle.add_mo(mo_compute_pooled_slot, modify_present=True) handle.commit() # Logout of the UCS Manager handle.logout()
from ucsmsdk.ucshandle import UcsHandle # Create a connection handle handle = UcsHandle("10.87.118.160", "admin", "Cisco123") # Login to the server handle.login() print 'Logged in Capitan!' from ucsmsdk.mometa.ls.LsServer import LsServer # checking to see if the python created SP exists - delete it if so sp = LsServer(parent_mo_or_dn="org-root", name="sp1_demo") handle.add_mo(sp) print sp print 'Created sp1_demo service profile' sp = handle.query_dn("org-root/ls-sp_demo") print sp spall = handle.query_dn("org-root") print spall sp2 = handle.query_dn("org-root/ls-lab-65-bfs2") sp2.descr = "pythoned" handle.set_mo(sp2) handle.commit() print 'changing description' sp2 = handle.query_dn("org-root/ls-lab-65-bfs2")
Cisco Systems, Inc. """ from ucsmsdk.ucshandle import UcsHandle from ucsmsdk.mometa.fabric.FabricVlan import FabricVlan # Create a Login Handle and Login HANDLE = UcsHandle("13.58.22.56", "admin", "password") HANDLE.login() VLANS = ['200', '300', '400', '500'] # Iterate over the VLANS list instantiating a vlan_mo and adding # the vlan_mo to the HANDLE. The UCS Python SDK is transactional # by default. for vlan in VLANS: vlan_mo = FabricVlan(parent_mo_or_dn="fabric/lan", name="vlan" + vlan, id=vlan) # Add the current instantiated vlan_mo Object to the HANDLE # This action does not overwrite previous vlan_mo ojects in # the uncommited HANDLE HANDLE.add_mo(vlan_mo, modify_present=True) # Commit the HANDLE to add the VLANS to UCS Manager HANDLE.commit() # Logout HANDLE.logout()
i=1 while i < len(VLAN_Name): print VLAN_Name[i] i = i + 1 elif row[0] == "VLAN ID": VLAN_ID = row i=1 while i < len(VLAN_ID): print VLAN_ID[i] i = i + 1 else: print "Bad Robot" #Create Sub Organization mo = OrgOrg(parent_mo_or_dn="org-root", name=my_Org, descr="Sub Organization") handle.add_mo(mo) handle.commit() #Create Production VLANs k = 1 while k < len(VLAN_ID): mo = FabricVlan(parent_mo_or_dn="fabric/lan", sharing="none", name=VLAN_Name[k], id=VLAN_ID[k], mcast_policy_name="", policy_owner="local", default_net="no", pub_nw_name="", compression_type="included") handle.add_mo(mo) handle.commit() print k k = k+1 #Create UUID Pool mo = UuidpoolPool(parent_mo_or_dn=my_Full_Path_Org, policy_owner="local", prefix="derived", descr="UUID Pool", assignment_order="sequential", name="UUID_POOL") mo_1 = UuidpoolBlock(parent_mo_or_dn=mo, to="0001-000000000100", r_from="0001-000000000001") handle.add_mo(mo)
Purpose: UCS Manager VLAN creation example Author: John McDonough ([email protected]) github: (@movinalot) Cisco Systems, Inc. """ from ucsmsdk.ucshandle import UcsHandle from ucsmsdk.mometa.fabric.FabricVlan import FabricVlan # Create a Login Handle and Login HANDLE = UcsHandle("13.58.22.56", "admin", "password") HANDLE.login() # Query the FabricLanCloud, under which VLAN Objects are inserted FABRIC_LAN_CLOUD = HANDLE.query_classid("FabricLanCloud") # Instantiate a VLAN Object, minimally "id" and "name" are required VLAN = FabricVlan(parent_mo_or_dn=FABRIC_LAN_CLOUD[0], name="vlan100", id="100") # Add the instantiated VLAN Object to the HANDLE HANDLE.add_mo(VLAN, modify_present=True) # Commit the HANDLE to add the VLAN to UCS Manager HANDLE.commit() # Logout HANDLE.logout()
from ucsmsdk.ucshandle import UcsHandle handle = UcsHandle( (sheet.cell_value(3,1)),(sheet.cell_value(4,1)),(sheet.cell_value(5,1))) handle.login() mo = handle.query_dn("org-root") print (mo) # Compute Chassis Link Aggregation Policy from ucsmsdk.mometa.compute.ComputeChassisDiscPolicy import ComputeChassisDiscPolicy mo = ComputeChassisDiscPolicy(parent_mo_or_dn="org-root", rebalance="user-acknowledged", descr="", action=(sheet.cell.value(8.1)), name="", policy_owner="local", link_aggregation_pref="none") handle.add_mo(mo, True) handle.commit() #logout handle.logout()
## Mission: Programming Cisco Compute - Python Basic and Advanced ## Mission Exercise 3 - Solution # Get a handle and login to UCS Manager from ucsmsdk.ucshandle import UcsHandle handle = UcsHandle("198.18.133.91", "admin", "password") handle.login() # Create a MAC Pool Block from ucsmsdk.mometa.macpool.MacpoolBlock import MacpoolBlock mac_pool_default = handle.query_dn("org-root/mac-pool-default") mo_mac_pool_block = MacpoolBlock(parent_mo_or_dn=mac_pool_default,r_from="00:25:B5:00:00:AA",to="00:25:B5:00:00:D9") handle.add_mo(mo_mac_pool_block, modify_present=True) handle.commit() # Create a Service Profile Template and associate to a Server Pool from ucsmsdk.mometa.ls.LsServer import LsServer from ucsmsdk.mometa.ls.LsRequirement import LsRequirement mo_sp_template = LsServer(parent_mo_or_dn="org-root", type="initial-template", name="CommanderCode_PY_Mission_Templ") handle.add_mo(mo_sp_template, modify_present=True) handle.commit() filter_exp = '(name,"CommanderCode_PY_Mission_Templ")' mo_sp_templ = handle.query_classid("lsServer",filter_str=filter_exp) mo_sp_templ_ls_requirement = LsRequirement(parent_mo_or_dn=mo_sp_templ[0].dn, name="Python_Heroes_Server_Pool") handle.add_mo(mo_sp_templ_ls_requirement, modify_present=True) # Instantiate a Service Profile from the Service Profile template
def run_module(): """ Run the module """ module = AnsibleModule( argument_spec=dict( hostname=dict(type='str', required=True), username=dict(type='str', default='admin'), password=dict(type='str', required=True, no_log=True), name=dict(type='str'), descr=dict(type='str'), state=dict(type='str', default='present', choices=['present', 'absent']) ), required_if=[ ['state', 'present', ['name']], ], supports_check_mode=True ) from ucsmsdk.ucshandle import UcsHandle from ucsmsdk.mometa.org.OrgOrg import OrgOrg error = False changed = False kwargs = dict() result = dict() if module.params['descr'] is not None: kwargs['descr'] = module.params['descr'] try: handle = UcsHandle( module.params['hostname'], module.params['username'], module.params['password'] ) handle.login() ucs_mo = handle.query_dn('org-root/org-' + module.params['name']) # Determine state change if ucs_mo: # Object exists, should it exist? has anything changed? if module.params['state'] == 'present': # Any Object properties not match, that is a change if not ucs_mo.check_prop_match(**kwargs): changed = True # Object does not exist but should, that is a change else: if module.params['state'] == 'present': changed = True # Object exists but should not, that is a change if ucs_mo and module.params['state'] == 'absent': changed = True # Apply state if not check_mode if changed and not module.check_mode: if module.params['state'] == 'absent': handle.remove_mo(ucs_mo) else: kwargs['parent_mo_or_dn'] = 'org-root' kwargs['name'] = module.params['name'] if module.params['descr'] is not None: kwargs['descr'] = module.params['descr'] ucs_mo = OrgOrg(**kwargs) handle.add_mo(ucs_mo, modify_present=True) handle.commit() except Exception as e: error = True result['msg'] = "error: %s " % str(e) result['changed'] = changed if error: module.fail_json(**result) module.exit_json(**result)
#skeleton script #import ucshandle class from ucshandle from ucsmsdk.ucshandle import UcsHandle #init handle handle = UcsHandle("192.168.157.153", "admin", "password", secure=False) # Login handle.login() #####IPNUT GENERATED CODE from ucsmsdk.mometa.fabric.FabricVlan import FabricVlan mo = FabricVlan(parent_mo_or_dn="fabric/lan", sharing="none", name="vlan123", id="123", mcast_policy_name="", policy_owner="local", default_net="no", pub_nw_name="", compression_type="included") handle.add_mo(mo) handle.commit() # Logout after execution handle.logout()
from ucsmsdk.ucshandle import UcsHandle handle = UcsHandle("10.10.20.113", "admin", "password") from ucsmsdk.mometa.fabric.FabricVlan import FabricVlan lan_cloud = handle.query_classid("FabricLanCloud") # vlan_mo = FabricVlan(parent_mo_or_dn=lan_cloud[0], name="vlan100", id="100") # handle.add_mo(vlan_mo, True) vlans = ["200", "201", "202"] for vlan in vlans: vlan_mo = FabricVlan(parent_mo_or_dn=lan_cloud[0], name="vlan" + vlan, id=vlan) handle.add_mo(vlan_mo, True) handle.commit()
from ucsmsdk.mometa.lsboot.LsbootVirtualMedia import LsbootVirtualMedia import connection as Connection UCS_HOST = Connection.UCS_HOST UCS_USER = Connection.UCS_USER UCS_PASS = Connection.UCS_PASS HANDLE = UcsHandle(UCS_HOST, UCS_USER, UCS_PASS) HANDLE.login() BOOT_POLICY = LsbootVirtualMedia( parent_mo_or_dn="org-root/boot-policy-virt-media-add", access="read-only-remote-cimc", order="3" ) HANDLE.add_mo(BOOT_POLICY, True) HANDLE.commit() # Get boot items (children) of Boot Policy OBJECTS = HANDLE.query_children(in_dn="org-root/boot-policy-virt-media-add") # Update boot items order for mo in OBJECTS: if mo.access == "read-only-remote-cimc": mo.order = "1" print(mo) HANDLE.set_mo(mo) elif mo.access == "read-write": storage_object = HANDLE.query_dn( "org-root/boot-policy-virt-media-add/storage/local-storage/local-hdd" )
In addition to importing the UcsHandle module you will also need to import the FabricVlan module. Think of the module as a recipe for creating a VLAN. Create vlan100. Use these python statements. There is no output indicating successful completion of the operation, no error is an indication of a successful operation. However, if you wanted to ensure that the object was created just query for it. In this operation the add_mo() handle method was used with two arguments. The first argument, like set_mo() is the object, the second argument could have been written as modify_present=True. Since the modify_present is the second argument in the add_mo method definition Python lets up just provide the value without having to provide the argument name. modify_present allows the add_mo() method to act like a set_mo() and update the object if it already exists. By default modify_present is False meaning that if add_mo() was being used to create an object that already exists then the add operation would fail. ''' handle = UcsHandle("192.168.193.138", "ucspe", "ucspe", secure=False) lan_cloud = handle.query_classid("FabricLanCloud") vlan_mo = FabricVlan(parent_mo_or_dn=lan_cloud[0], name="vlan_1001", id="1001") handle.add_mo(vlan_mo, modify_present=True) handle.commit() ################ Create UCS Manager VLANs in a Transaction ############## ''' UCS Manager Python SDK commit() can commit more than one object at a time, in fact the objects can be of different classes. Objects can be continually added to the handle and a single call to commit() will commit them all. This is called a Transaction, a few caveats apply. If one object fails to be created everything up to that point is rolled back and nothing is created. Objects in the Transaction cannot have dependencies on each other. Objects only become visible to others users of UCS Manager when the Transaction is complete. UCS Manager is Transaction oriented by default adding objects to the handle and committing them is the standard process. Using Transactions for processes that create many objects is far more efficient than processing each object one at a time. Create vlan200, vlan201, vlan202 in a Transaction. Use these python statements.
from ucsmsdk.ucshandle import UcsHandle from ucsmsdk.mometa.ls.LsServer import LsServer from ucsmsdk.mometa.org.OrgOrg import OrgOrg HANDLE = UcsHandle( "sandbox-ucsm1.cisco.com", "admin", "password" ) HANDLE.login() ORG_ORG = OrgOrg( parent_mo_or_dn='org-root', name="devnet", ) HANDLE.add_mo(ORG_ORG, modify_present=True) HANDLE.commit() SP_TEMPLATE = LsServer( parent_mo_or_dn='org-root/org-devnet', name="devcore_template", type="updating-template" ) HANDLE.add_mo(SP_TEMPLATE, modify_present=True) HANDLE.commit() HANDLE.logout()
class Controller: def __init__(self, host, username, password): self.host = host self.username = username self.password = password self.handler = None self.change_log = [] self.state = {} print("Local State Data Created") @classmethod def load(cls, filename="config.yaml"): import yaml with open(filename, 'r') as f: config = yaml.load(f, Loader=yaml.FullLoader) return cls(config['host'], config['username'], config['password']) def connect(self) -> UcsHandle: self.handler = UcsHandle(self.host, self.username, self.password) self.handler.login() return self.handler def commit(self): if len(self.change_log) > 0: print("COMMIT LOG:") for line in self.change_log: print(line) if input('Confirm Commit (y,n)? ') == 'y': self.handler.commit() print("Remote State Changes Committed") self.state = {} self.change_log = [] print("Local State Data Destroyed") else: print("No Changes To Commit, skipping...") def get_objects_state_from_class_id(self, class_id): if class_id not in self.state: self.state[class_id] = self.handler.query_classid(class_id) print(f"Local State Data Updated with \"{class_id}\"") return self.state[class_id] def move_vlan(self, vlan_id, source_name=None, target_name=None): """ move_vlan will take a series of vlans bound to a specific id, remove them from old local and add them to a new local. When no group names are passed, null is interpreted as an unbound Vlan. When an invalid group name is passed this function fails, raising an exception :param vlan_id: The VLAN ID to migrate :param source_name: The source Vlan Group (null if Not Bound) :param target_name: The target Vlan Group (null if Not Bound) :return: target_vlans: List: A list of the vlan managed objects which were moved. """ vlans = self.get_objects_state_from_class_id('fabricVlan') target_vlans = [vlan for vlan in vlans if vlan.id == vlan_id] target_vlan_names = [vlan.name for vlan in target_vlans] vlan_groups = self.get_objects_state_from_class_id('fabricNetGroup') source, target = None, None if source_name: source = next(vlanGroup for vlanGroup in vlan_groups if vlanGroup.name == source_name) if target_name: target = next(vlanGroup for vlanGroup in vlan_groups if vlanGroup.name == target_name) # If there is a source vlan group, then we want to strip off all pooled vlans from that vlan group that match # the vlan_id, but if no source vlan group was defined, we want to remove port-channels which are bound under # this vlan to insure forwarding only occurs on port-channels bound to the vlan group we are migrating too. if source: group_vlans = self.handler.query_dn(source.dn, hierarchy=True) for groupVlan in group_vlans: if groupVlan.name in target_vlan_names: self.handler.remove_mo(groupVlan) self.change_log.append(f"remove({groupVlan.dn})") else: for vlan in target_vlans: children = self.handler.query_dn(vlan.dn, hierarchy=True) for child in children: # pop off every port-channel which is a child of this vlan if isinstance(child, FabricEthVlanPc): self.handler.remove_mo(child) self.change_log.append(f"remove({child.dn})") # If there is a target vlan group defined we want to create a fabricPooledVlan child object of that vlan group # for every vlan which matches the vlan_id, otherwise, we will leave the vlan unbound. if target: for targetVlan in target_vlans: tmp = FabricPooledVlan(parent_mo_or_dn=target, name=targetVlan.name) self.handler.add_mo(tmp, modify_present=True) self.change_log.append(f"create({tmp.dn})") self.change_log.append( f"move_vlan({vlan_id},source_name={source_name},target_name={target_name})" ) return target_vlans def show_vlans(self, vlan_id): if 'vlan' not in self.state: self.state['vlan'] = self.handler.query_classid('fabricVlan') target_vlans = [ vlan for vlan in self.state['vlan'] if vlan.id == vlan_id ] for vlan in target_vlans: print(vlan)
def deploy(self,settings): """Deploy""" ucsm_ip = settings['ucsm']['credentials']['ip'] ucsm_user = settings['ucsm']['credentials']['user'] ucsm_pw = settings['ucsm']['credentials']['pw'] handle = UcsHandle(ucsm_ip, ucsm_user, ucsm_pw) print ucsm_ip print ucsm_user print ucsm_pw handle.login() print "\n>>>>>>>>>>>>> UCSM Login <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n" print "############# Creating Policies #######################" s_policies = settings['ucsm']['policies'] policies = self.create_policies(s_policies) """ Timezone """ mo = handle.query_dn("sys/svc-ext/datetime-svc") mo.timezone = str(settings['ucsm']['policies']['timezone']) mo.policy_owner = "local" mo.admin_state = "enabled" mo.port = "0" mo.descr = "" handle.set_mo(mo) handle.commit() """ Policies """ for key in policies: #print 'Type: ' + key for sub_key in policies[key]: #print key + ': ' + sub_key handle.add_mo(policies[key][sub_key]['mo'], True) # Overwrite handle.commit() """ Qos System Class """ mo = handle.query_dn("fabric/lan/classes") mo.policy_owner = "local" mo.descr = "" mo_1 = QosclassEthBE(parent_mo_or_dn=mo, multicast_optimize="no", name="", weight="10", mtu="9216") mo_2 = QosclassFc(parent_mo_or_dn=mo, cos="3", name="", weight="none") handle.set_mo(mo) handle.commit() print "> QoS System Class................................[OK]" print "############# Enabling FI Ports #######################" s_fi_ports = settings['ucsm']['fi_ports'] fi_ports = self.enable_fi_ports(s_fi_ports) for key in fi_ports: #print 'Type: ' + key for sub_key in fi_ports[key]: #print key + ': ' + sub_key handle.add_mo(fi_ports[key][sub_key]['mo'], True) # Overwrite handle.commit() print "############# Labeling Equipment ######################" labels = settings['ucsm']['labels'] for key in labels['chassis']: #print key l_dn = labels['chassis'][key]['dn'] l_label = labels['chassis'][key]['label'] mo = handle.query_dn(l_dn) mo.usr_lbl = l_label mo.admin_state = "acknowledged" handle.set_mo(mo) handle.commit() print "> Chassis.........................................[OK]" for key in labels['servers']: print key l_dn = labels['servers'][key]['dn'] l_label = labels['servers'][key]['label'] l_lc = labels['servers'][key]['lc'] mo = handle.query_dn(l_dn) #mo.lc = l_lc mo.descr = "" mo.usr_lbl = l_label mo.admin_power = "policy" mo.policy_owner = "local" mo.name = "" handle.set_mo(mo) handle.commit() print "> Servers.........................................[OK]" print "############# Register to UCSC ########################" s_register = settings['ucsm']['register'] mo = self.register_to_ucsc(s_register) handle.add_mo(mo, True) handle.commit() print "> Register........................................[OK]" print "\n>>>>>>>>>>>>> UCSM Logout <<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n" handle.logout()
def main(): handle = UcsHandle("192.168.254.200","ucspe","ucspe", secure=False) handle.login() ## Acknolwedge Chassis mo = EquipmentChassis(parent_mo_or_dn="sys", admin_state="re-acknowledge", id="5") handle.add_mo(mo, True) handle.commit() ## Update MAC Pool mo = MacpoolBlock(parent_mo_or_dn="org-root/mac-pool-default", r_from="00:25:B5:00:00:00", to="00:25:B5:00:00:C7") handle.add_mo(mo) handle.commit() ## Update UUID Pools handle.query_dn("org-root/uuid-pool-default") mo = UuidpoolBlock(parent_mo_or_dn="org-root/uuid-pool-default", r_from="0000-000000000001", to="0000-0000000000C8") handle.add_mo(mo) handle.commit() ## Setup Fabric Ethernet Uplink A Side mo = FabricEthLan(parent_mo_or_dn="fabric/lan", id="A") mo_1 = FabricEthLanEp(parent_mo_or_dn=mo, admin_speed="10gbps", admin_state="enabled", auto_negotiate="yes", eth_link_profile_name="default", fec="auto", flow_ctrl_policy="default", name="", port_id="1", slot_id="1", usr_lbl="") handle.add_mo(mo, True) handle.commit() ## Setup Fabric Ethernet Uplink A Side mo = FabricEthLan(parent_mo_or_dn="fabric/lan", id="B") mo_1 = FabricEthLanEp(parent_mo_or_dn=mo, admin_speed="10gbps", admin_state="enabled", auto_negotiate="yes", eth_link_profile_name="default", fec="auto", flow_ctrl_policy="default", name="", port_id="1", slot_id="1", usr_lbl="") handle.add_mo(mo, True) handle.commit() ## Setup Service Profile Template mo = LsServer(parent_mo_or_dn="org-root", ident_pool_name="default", name="globotemplate", type="initial-template", uuid="00000000-0000-0000-0000-000000000000") handle.add_mo(mo) handle.commit() handle.logout()
John McDonough ([email protected]) github: (@movinalot) Cisco Systems, Inc. """ from ucsmsdk.ucshandle import UcsHandle from ucsmsdk.mometa.compute.ComputePool import ComputePool from ucsmsdk.mometa.compute.ComputePooledSlot import ComputePooledSlot from ucsmsdk.mometa.ls.LsRequirement import LsRequirement HANDLE = UcsHandle("sandbox-ucsm1.cisco.com", "admin", "password") HANDLE.login() SERVER_POOL = ComputePool(parent_mo_or_dn="org-root/org-devnet", name="devcore_pool") HANDLE.add_mo(SERVER_POOL, modify_present=True) for blade in HANDLE.query_classid("computeBlade", filter_str='(chassis_id, "7")'): SERVER = ComputePooledSlot(parent_mo_or_dn=SERVER_POOL, chassis_id=blade.chassis_id, slot_id=blade.slot_id) HANDLE.add_mo(SERVER, modify_present=True) HANDLE.commit() SP_TEMPLATE = LsRequirement( parent_mo_or_dn="org-root/org-devnet/ls-devcore_template", name="devcore_pool") HANDLE.add_mo(SP_TEMPLATE, modify_present=True) HANDLE.commit()
handle.commit() handle.logout() # Add NTP Server from ucsmsdk.ucshandle import UcsHandle from ucsmsdk.mometa.comm.CommNtpProvider import CommNtpProvider handle = UcsHandle("198.18.133.91", "admin", "C1sco12345") handle.login() timezone_mo = handle.query_dn("sys/svc-ext/datetime-svc") ntp_provider_mo = CommNtpProvider(parent_mo_or_dn=timezone_mo, name="198.18.128.3") handle.add_mo(ntp_provider_mo) handle.commit() handle.logout() input("NTP Server Added - Press Enter to Continue to Remove NTP Server...") # Delete NTP Server from ucsmsdk.ucshandle import UcsHandle handle = UcsHandle("198.18.133.91", "admin", "C1sco12345") handle.login() ntp_provider_mo = handle.query_dn("sys/svc-ext/datetime-svc/ntp-198.18.128.3") handle.remove_mo(ntp_provider_mo)