def delete_user(intersight_api_params, user_email): # Create Intersight API instance # ---------------------- api_instance = IntersightApiClient( host=intersight_api_params['api_base_uri'], private_key=intersight_api_params['api_private_key_file'], api_key_id=intersight_api_params['api_key_id'], ) try: # GET Users users_handle = iam_user_api.IamUserApi(api_instance) kwargs = dict(filter="Email eq '%s'" % user_email) users_result = users_handle.iam_users_get(**kwargs) if users_result.results: # DELETE Users users_delete_result = users_handle.iam_users_moid_delete( moid=users_result.results[0].moid) else: print("User not found:", user_email) except Exception as err: print("Exception:", str(err)) import traceback print('-' * 60) traceback.print_exc(file=sys.stdout) print('-' * 60)
def __init__(self, api_key, keyfile): self.type = 'Intersight' api_instance = IntersightApiClient(private_key=keyfile, api_key_id=api_key) self.NetworkElementApi = intersight.NetworkElementApi(api_instance) self.ComputeRackUnitApi = intersight.ComputeRackUnitApi(api_instance) self.HyperflexClusterApi = intersight.HyperflexClusterApi(api_instance) self.CondAlarmApi = intersight.CondAlarmApi(api_instance) self.HyperflexAlarmApi = intersight.HyperflexAlarmApi(api_instance) self.current_state = { 'network_elements': [], 'compute_rack_units': [], 'hyperflex_clusters': [], 'cond_alarms': [], 'hyperflex_alarms': [] } self.previous_state = { 'network_elements': [], 'compute_rack_units': [], 'hyperflex_clusters': [], 'cond_alarms': [], 'hyperflex_alarms': [] }
def get_faults(): """Get Intersight Faults via the Intersight API.""" try: api_instance = IntersightApiClient( host="https://intersight.com/api/v1", private_key="SecretKey.txt", api_key_id= "59dd1f1916267c00015e0929/59dd1ec316267c00015e0496/5b0edbde68306b6e34173261" ) # GET Faults handle = fault_instance_api.FaultInstanceApi(api_instance) response = handle.fault_instances_get() # Create a unique list of the severity types in the response severities = [fault.severity for fault in response._results] # Create a message with a count of each severity type that was in the response message = ( "For the requested Intersight fault retrieval operation, there are " ) for severity in set([fault.severity for fault in response._results]): message += str( sum(f.severity == severity for f in response._results)) + " " + severity + " faults, " except Exception as err: print err message = ( "There was an error connecting to or retrieving information from Cisco Intersight" ) return message
def add_user(intersight_api_params, username, user_role='Account Administrator'): # Create Intersight API instance # ---------------------- api_instance = IntersightApiClient( host=intersight_api_params['api_base_uri'], private_key=intersight_api_params['api_private_key_file'], api_key_id=intersight_api_params['api_key_id'], ) # GET Permissions permissions_handle = iam_permission_api.IamPermissionApi(api_instance) kwargs = dict(filter="Name eq '%s'" % user_role) permissions_result = permissions_handle.iam_permissions_get(**kwargs) if permissions_result.results: # GET IdpReference idp_reference_handle = iam_idp_reference_api.IamIdpReferenceApi( api_instance) idp_reference_name = 'Cisco' kwargs = dict(filter="Name eq '%s'" % idp_reference_name) idp_reference_result = idp_reference_handle.iam_idp_references_get( **kwargs) if idp_reference_result.results: user_matches = False # GET Users users_handle = iam_user_api.IamUserApi(api_instance) kwargs = dict(filter="Email eq '%s'" % username) users_result = users_handle.iam_users_get(**kwargs) if (users_result.results and users_result.results[0].permissions[0].moid == permissions_result.results[0].moid and users_result.results[0].idpreference.moid == idp_reference_result.results[0].moid): user_matches = True if not user_matches: # POST Users with Permissions and IdpReference users_body = { 'Email': username, 'Idpreference': idp_reference_result.results[0].moid, 'Permissions': [permissions_result.results[0].moid], } users_result = users_handle.iam_users_post(users_body) result['changed'] = True else: # user exists and IdP/Permissions match print('User exists with requested role:', username) else: print('Could not find IdP', idp_reference_name) else: print('Invalid user role', user_role)
Purpose: Intersight functions for the Intersight Skill Author: John McDonough ([email protected]) Cisco Systems, Inc. """ import sys import json from intersight.intersight_api_client import IntersightApiClient from intersight.apis import cond_alarm_api from intersight.apis import hyperflex_cluster_profile_api api_instance = IntersightApiClient( host="https://intersight.com/api/v1", private_key="soperspam1_ucstechtalks_SecretKey.txt", api_key_id= "5a3404ac3768393836093cab/5b02fa7e6d6c356772394170/5b02fad36d6c356772394449" ) def get_alarms(): """Get Intersight Faults via the Intersight API.""" try: # GET Alarms handle = cond_alarm_api.CondAlarmApi(api_instance) kwargs = dict(top=2000) response = handle.cond_alarms_get(**kwargs) # Create a unique list of the severity types in the response severities = [alarm.severity for alarm in response._results]
'AccountOwnershipState'] != 'Claimed': (claim_resp, device_id, claim_code) = dc_obj.get_claim_info() if claim_resp.get('ApiError'): result['msg'] += claim_resp['ApiError'] return_code = 1 print(json.dumps(result)) continue result['msg'] += " Id: %s" % device_id result['msg'] += " Token: %s" % claim_code # Create Intersight API instance and post ID/claim code # ---------------------- api_instance = IntersightApiClient( host=intersight_api_params['api_base_uri'], private_key=intersight_api_params['api_private_key_file'], api_key_id=intersight_api_params['api_key_id'], ) # create device claim API handle api_handle = asset_device_claim_api.AssetDeviceClaimApi( api_instance) # post ID/Claim Code claim_body = { 'SecurityToken': claim_code, 'SerialNumber': device_id } claim_result = api_handle.asset_device_claims_post(claim_body) result['changed'] = True
Purpose: Intersight functions for the Intersight Skill Author: John McDonough ([email protected]) Cisco Systems, Inc. """ from intersight.intersight_api_client import IntersightApiClient from intersight.apis import cond_alarm_api from intersight.apis import hyperflex_cluster_profile_api from intersight.apis import hyperflex_cluster_api api_instance = IntersightApiClient( host="https://intersight.com/api/v1", private_key="soperspam1_ucstechtalks_SecretKey.txt", # private_key="/Users/dsoper/Downloads/SSOSecretKey.txt", api_key_id= "5a3404ac3768393836093cab/5b02fa7e6d6c356772394170/5b02fad36d6c356772394449" # api_key_id="596cc79e5d91b400010d15ad/596cc7945d91b400010d154e/5b6275df3437357030a7795f" ) def get_alarms(moid): """ Get Intersight alarms via the Intersight API. Returns a string with the Critial and Warning alarms counts for the given MOID """ message = '' # GET Alarms handle = cond_alarm_api.CondAlarmApi(api_instance) kwargs = dict(filter="AffectedMoId eq '%s'" % moid)
default='settings.json', help='JSON settings file (settings.json used by default)') parser.add_argument('-t', '--target_host', dest='hostname', help='target host ip to delete') args = parser.parse_args() if os.path.isfile(args.file): settings = json.load(open(args.file, 'r')) else: settings = json.loads(args.file) # Create Intersight API instance # ---------------------- api_instance = IntersightApiClient( host=settings['api_host'], private_key=settings['api_private_key'], api_key_id=settings['api_key_id']) # create API handle api_handle = asset_device_registration_api.AssetDeviceRegistrationApi( api_instance) kwargs = dict(filter="ConnectionStatus eq 'Connected'") api_result = api_handle.asset_device_registrations_get(**kwargs) for device in api_result.results: if device.device_ip_address[0] == args.hostname: api_handle = asset_device_claim_api.AssetDeviceClaimApi( api_instance) api_handle.asset_device_claims_moid_delete( moid=device.device_claim.moid) result['changed'] = True
key_id = "" # MODULE REQUIREMENT 2 """ For the following variable below named key, please fill in between the quotes your system's file path to your Intersight API key "SecretKey.txt" file. Here is an example: key = "C:\Keys\Key1\SecretKey.txt" """ key = "" # Define Intersight SDK IntersightApiClient variables # Tested on Cisco Intersight API Reference v1.0.9-853 base_url = "https://intersight.com/api/v1" api_instance = IntersightApiClient(host=base_url, private_key=key, api_key_id=key_id) # Establish Intersight Universal Functions def iu_get(api_path): """This is a function to perform a universal or generic GET on objects under available Intersight API types, including those not yet defined in the Intersight SDK for Python. An argument for the API type path is required. Args: api_path: The path to the targeted Intersight API type. For example, to specify the Intersight API type for adapter configuration policies, enter "adapter/ConfigPolicies". More API types can be found in the Intersight API reference library at https://intersight.com/apidocs/introduction/overview/. Returns:
api_key_file = "api.txt" api_secret_file = "SecretKey.txt" if __name__ == "__main__": print("Intersight Workshop") # step 1 - get keys # add file api.txt and SecretKey.txt to the folder # step 2 - install sdk, create auth # python3 -m pip install git+https://github.com/CiscoUcs/intersight-python.git api_key = "" with open(api_key_file) as file: api_key = file.read() api_key = api_key.strip() api_instance = IntersightApiClient( private_key=api_secret_file, api_key_id=api_key ) #Require Argument to allow different options in script if len(sys.argv) < 2: print("more arguments required") sys.exit() cmd = sys.argv[1] #API Useage Example for Organization if cmd == "org": orgAPI = intersight.OrganizationOrganizationApi(api_instance) orgs = orgAPI.organization_organizations_get() for org in orgs.results: print("Name: {}, MOID: {}".format(org.name, org.moid)) if cmd == "show": print("Liste Rackserver")
def connect(self): """Connect to Intersight.""" self.api_instance = IntersightApiClient( host=self.intersight_url, private_key=self.api_secret_path, api_key_id=self.api_key)
def main(): argument_spec = dict( api_private_key=dict(type='path', required=True), api_uri=dict(type='str', default='https://intersight.com/api/v1'), api_key_id=dict(type='str', required=True), objects=dict(type='list'), json_config_file=dict(type='path'), state=dict(type='str', choices=['present', 'absent'], default='present'), ) module = AnsibleModule( argument_spec, supports_check_mode=True, required_one_of=[ ['objects', 'json_config_file'], ], mutually_exclusive=[ ['objects', 'json_config_file'], ], ) if not HAS_INTERSIGHT: module.fail_json(msg='intersight module is not available') api_instance = IntersightApiClient( host=module.params['api_uri'], private_key=module.params['api_private_key'], api_key_id=module.params['api_key_id'], ) err = False # note that all objects specified in the object list report a single result (including a single changed). result = dict(changed=False) try: if module.params.get('objects'): objects = module.params['objects'] else: # either objects or json_config_file will be specified, so if there is no objects option use a config file with open(module.params['json_config_file']) as f: objects = json.load(f) for item in objects: moid = None props_match = False # import the module and GET the resource based on an optional filter param api_module = import_module(item['api_module']) api_class = getattr(api_module, item['api_class']) api_object = api_class(api_instance) response_dict = get_object(api_object, item) result['api_response'] = response_dict if response_dict.get('moid'): moid = response_dict['moid'] if module.params['state'] == 'absent': # object must exist, but all properties do not have to match if moid: if not module.check_mode: api_moid_delete_method = getattr( api_object, item['api_method_prefix'] + '_moid_delete') api_moid_delete_method(moid) result['api_response'] = {} result['changed'] = True else: # configure as present. Note that no api_body implies a GET only - api_response from above returned if item.get('api_body'): # configure based on api_body if moid: # check object properties data_module = import_module(item['data_module']) data_class = getattr(data_module, item['data_class']) deserialize_instance = ApiClient() data_object = deserialize_instance._ApiClient__deserialize_model( item['api_body'], data_class) deserialize_dict = data_object.to_dict() props_match = compare_values(deserialize_dict, response_dict) if not props_match: if not module.check_mode: if moid: # update the resource - user has to specify all the props they want updated api_moid_patch_method = getattr( api_object, item['api_method_prefix'] + '_moid_patch') api_response = api_moid_patch_method( moid, item['api_body']) else: # create the resource api_post_method = getattr( api_object, item['api_method_prefix'] + '_post') api_response = api_post_method( item['api_body']) if not api_response: result['api_response'] = get_object( api_object, item) result['changed'] = True except Exception as e: err = True result['msg'] = "setup error: %s " % str(e) if err: module.fail_json(**result) module.exit_json(**result)
# Uebung 1 --> in Intersight # Uebung 2 import intersight from intersight.intersight_api_client import IntersightApiClient import json api_instance = IntersightApiClient( private_key="./SecretKey.txt", api_key_id="EIGENE_KEY_ID_HIER_EINFÜGEN", ) # Uebung 3 rackApi = intersight.ComputeRackUnitApi(api_instance) rack_servers = rackApi.compute_rack_units_get() for server in rack_servers.results: print('Serial: {}, MOID: {}, Model: {}'.format(server.serial,server.model,server.moid)) # Uebung 4 faultApi = intersight.FaultInstanceApi(api_instance) faults = faultApi.fault_instances_get() for fault in faults.results: if fault.severity in ['critical', 'major']: print('{} - {}'.format(fault.ancestor_mo_id,fault.description))
#! /usr/bin/env python from intersight.intersight_api_client import IntersightApiClient from inter.apis import equipment_device_summary_api #Create an Intersight API Client Instance API_INSTANCE = IntersightApiClient( host='https://intersight.com/api/v1',\ private_key = '/Path_to/SecretKey.txt',\ api_key_id='your_own_api_key_id') #Create an equipment device handle D_HANDLE = equipment_device_summary_api.EquipmentDeviceSummaryApi(API_INSTANCE) DEVICES = D_HANDLE.equipment_device_summaries_get().results print ('{0:35s}{1:40s}{2:13s}'.format( 'DN', 'MODEL', 'SERIAL', 'OBJECT TYPE')) print('-'*105) # Loop through devices and extract data for DEVICE in DEVICES: print('{0:35s}{1:40s}{2:13s}{3:14s}'.format( DEVICE.dn, DEVICE.model, DEVICE.serial, DEVICE.source_object_type))