Skip to content

Commit

Permalink
Merge pull request #191 from Abhishek-121/main
Browse files Browse the repository at this point in the history
Fix the issue while creating building site, Swim to skip unmatched filtered devices when distribution and activating images, Add the log message while editing the device role, Return correct log message if customer wants to update management IP.
  • Loading branch information
madhansansel authored Mar 13, 2024
2 parents 6268644 + 95bd7ba commit 8c88ac2
Show file tree
Hide file tree
Showing 6 changed files with 213 additions and 64 deletions.
60 changes: 56 additions & 4 deletions plugins/modules/inventory_intent.py
Original file line number Diff line number Diff line change
Expand Up @@ -956,7 +956,7 @@ def validate_input(self):
def get_device_ips_from_config_priority(self):
"""
Retrieve device IPs based on the configuration.
Args:
Parameters:
- self (object): An instance of a class used for interacting with Cisco Cisco Catalyst Center.
Returns:
list: A list containing device IPs.
Expand Down Expand Up @@ -1329,6 +1329,7 @@ def export_device_details(self):
self.log(self.msg, "INFO")
self.status = "success"
self.result['changed'] = True
self.result['response'] = self.msg

except Exception as e:
self.msg = "Error while exporting device details into CSV file for device(s): '{0}'".format(str(device_ips))
Expand Down Expand Up @@ -2762,7 +2763,7 @@ def clear_mac_address(self, interface_id, deploy_mode, interface_name):
def update_interface_detail_of_device(self, device_to_update):
"""
Update interface details for a device in Cisco Catalyst Center.
Args:
Parameters:
self (object): An instance of a class used for interacting with Cisco Catalyst Center.
device_to_update (list): A list of IP addresses of devices to be updated.
Returns:
Expand Down Expand Up @@ -2938,6 +2939,39 @@ def check_device_update_execution_response(self, response, device_ip):

return self

def is_device_exist_in_ccc(self, device_ip):
"""
Check if a device with the given IP exists in Cisco Catalyst Center.
Parameters:
self (object): An instance of a class used for interacting with Cisco Catalyst Center.
device_ip (str): The IP address of the device to check.
Returns:
bool: True if the device exists, False otherwise.
Description:
This method queries Cisco Catalyst Center to check if a device with the specified
management IP address exists. If the device exists, it returns True; otherwise,
it returns False. If an error occurs during the process, it logs an error message
and raises an exception.
"""

try:
response = self.dnac._exec(
family="devices",
function='get_device_list',
params={"managementIpAddress": device_ip}
)
response = response.get('response')
if not response:
self.log("Device with given IP '{0}' is not present in Cisco Catalyst Center".format(device_ip), "INFO")
return False

return True

except Exception as e:
error_message = "Error while getting the response of device '{0}' from Cisco Catalyst Center: {1}".format(device_ip, str(e))
self.log(error_message, "ERROR")
raise Exception(error_message)

def get_want(self, config):
"""
Get all the device related information from playbook that is needed to be
Expand Down Expand Up @@ -2990,6 +3024,17 @@ def get_diff_merged(self, config):

config['ip_address_list'] = devices_to_add

if self.config[0].get('update_mgmt_ipaddresslist'):
device_ip = self.config[0].get('update_mgmt_ipaddresslist')[0].get('existMgmtIpAddress')
is_device_exists = self.is_device_exist_in_ccc(device_ip)

if not is_device_exists:
self.status = "failed"
self.msg = """Unable to update the Management IP address because the device with IP '{0}' is not
found in Cisco Catalyst Center.""".format(device_ip)
self.log(self.msg, "ERROR")
return self

if not config['ip_address_list']:
self.msg = "Devices '{0}' already present in Cisco Catalyst Center".format(self.have['devices_in_playbook'])
self.log(self.msg, "INFO")
Expand Down Expand Up @@ -3154,6 +3199,8 @@ def get_diff_merged(self, config):
if device_data['snmpv3_privacy_password']:
csv_data_dict['snmp_auth_passphrase'] = device_data['snmpv3_auth_password']
csv_data_dict['snmp_priv_passphrase'] = device_data['snmpv3_privacy_password']
else:
csv_data_dict['snmp_username'] = None

device_key_mapping = {
'username': 'userName',
Expand Down Expand Up @@ -3212,6 +3259,9 @@ def get_diff_merged(self, config):
for param in params_to_remove:
playbook_params.pop(param, None)

if not playbook_params['snmpROCommunity']:
playbook_params['snmpROCommunity'] = device_data.get('snmp_community', None)

try:
if playbook_params['updateMgmtIPaddressList']:
new_mgmt_ipaddress = playbook_params['updateMgmtIPaddressList'][0]['newMgmtIpAddress']
Expand Down Expand Up @@ -3267,6 +3317,7 @@ def get_diff_merged(self, config):
self.status = "failed"
self.msg = "Mandatory parameter (role) to update Device Role is missing"
self.log(self.msg, "WARNING")
self.result['response'] = self.msg
return self

# Check if the same role of device is present in dnac then no need to change the state
Expand Down Expand Up @@ -3309,8 +3360,8 @@ def get_diff_merged(self, config):
if 'successfully' in progress or 'succesfully' in progress:
self.status = "success"
self.result['changed'] = True
self.result['response'] = execution_details
self.msg = "Device(s) '{0}' role updated successfully".format(str(device_to_update))
self.msg = "Device(s) '{0}' role updated successfully to '{1}'".format(str(device_to_update), device_role_args.get('role'))
self.result['response'] = self.msg
self.log(self.msg, "INFO")
break
elif execution_details.get("isError"):
Expand All @@ -3321,6 +3372,7 @@ def get_diff_merged(self, config):
else:
self.msg = "Device role updation get failed"
self.log(self.msg, "ERROR")
self.result['response'] = self.msg
break

except Exception as e:
Expand Down
60 changes: 56 additions & 4 deletions plugins/modules/inventory_workflow_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -956,7 +956,7 @@ def validate_input(self):
def get_device_ips_from_config_priority(self):
"""
Retrieve device IPs based on the configuration.
Args:
Parameters:
- self (object): An instance of a class used for interacting with Cisco Cisco Catalyst Center.
Returns:
list: A list containing device IPs.
Expand Down Expand Up @@ -1328,6 +1328,7 @@ def export_device_details(self):
self.log(self.msg, "INFO")
self.status = "success"
self.result['changed'] = True
self.result['response'] = self.msg

except Exception as e:
self.msg = "Error while exporting device details into CSV file for device(s): '{0}'".format(str(device_ips))
Expand Down Expand Up @@ -2756,7 +2757,7 @@ def clear_mac_address(self, interface_id, deploy_mode, interface_name):
def update_interface_detail_of_device(self, device_to_update):
"""
Update interface details for a device in Cisco Catalyst Center.
Args:
Parameters:
self (object): An instance of a class used for interacting with Cisco Catalyst Center.
device_to_update (list): A list of IP addresses of devices to be updated.
Returns:
Expand Down Expand Up @@ -2932,6 +2933,39 @@ def check_device_update_execution_response(self, response, device_ip):

return self

def is_device_exist_in_ccc(self, device_ip):
"""
Check if a device with the given IP exists in Cisco Catalyst Center.
Parameters:
self (object): An instance of a class used for interacting with Cisco Catalyst Center.
device_ip (str): The IP address of the device to check.
Returns:
bool: True if the device exists, False otherwise.
Description:
This method queries Cisco Catalyst Center to check if a device with the specified
management IP address exists. If the device exists, it returns True; otherwise,
it returns False. If an error occurs during the process, it logs an error message
and raises an exception.
"""

try:
response = self.dnac._exec(
family="devices",
function='get_device_list',
params={"managementIpAddress": device_ip}
)
response = response.get('response')
if not response:
self.log("Device with given IP '{0}' is not present in Cisco Catalyst Center".format(device_ip), "INFO")
return False

return True

except Exception as e:
error_message = "Error while getting the response of device '{0}' from Cisco Catalyst Center: {1}".format(device_ip, str(e))
self.log(error_message, "ERROR")
raise Exception(error_message)

def get_want(self, config):
"""
Get all the device related information from playbook that is needed to be
Expand Down Expand Up @@ -2983,6 +3017,17 @@ def get_diff_merged(self, config):

config['ip_address_list'] = devices_to_add

if self.config[0].get('update_mgmt_ipaddresslist'):
device_ip = self.config[0].get('update_mgmt_ipaddresslist')[0].get('existMgmtIpAddress')
is_device_exists = self.is_device_exist_in_ccc(device_ip)

if not is_device_exists:
self.status = "failed"
self.msg = """Unable to update the Management IP address because the device with IP '{0}' is not
found in Cisco Catalyst Center.""".format(device_ip)
self.log(self.msg, "ERROR")
return self

if not config['ip_address_list']:
self.msg = "Devices '{0}' already present in Cisco Catalyst Center".format(self.have['devices_in_playbook'])
self.log(self.msg, "INFO")
Expand Down Expand Up @@ -3147,6 +3192,8 @@ def get_diff_merged(self, config):
if device_data['snmpv3_privacy_password']:
csv_data_dict['snmp_auth_passphrase'] = device_data['snmpv3_auth_password']
csv_data_dict['snmp_priv_passphrase'] = device_data['snmpv3_privacy_password']
else:
csv_data_dict['snmp_username'] = None

device_key_mapping = {
'username': 'userName',
Expand Down Expand Up @@ -3205,6 +3252,9 @@ def get_diff_merged(self, config):
for param in params_to_remove:
playbook_params.pop(param, None)

if not playbook_params['snmpROCommunity']:
playbook_params['snmpROCommunity'] = device_data.get('snmp_community', None)

try:
if playbook_params['updateMgmtIPaddressList']:
new_mgmt_ipaddress = playbook_params['updateMgmtIPaddressList'][0]['newMgmtIpAddress']
Expand Down Expand Up @@ -3260,6 +3310,7 @@ def get_diff_merged(self, config):
self.status = "failed"
self.msg = "Mandatory parameter (role) to update Device Role is missing"
self.log(self.msg, "WARNING")
self.result['response'] = self.msg
return self

# Check if the same role of device is present in ccc then no need to change the state
Expand Down Expand Up @@ -3302,9 +3353,9 @@ def get_diff_merged(self, config):
if 'successfully' in progress or 'succesfully' in progress:
self.status = "success"
self.result['changed'] = True
self.result['response'] = execution_details
self.msg = "Device(s) '{0}' role updated successfully".format(str(device_to_update))
self.msg = "Device(s) '{0}' role updated successfully to '{1}'".format(str(device_to_update), device_role_args.get('role'))
self.log(self.msg, "INFO")
self.result['response'] = self.msg
break
elif execution_details.get("isError"):
self.status = "failed"
Expand All @@ -3314,6 +3365,7 @@ def get_diff_merged(self, config):
else:
self.msg = "Device role updation get failed"
self.log(self.msg, "ERROR")
self.result['response'] = self.msg
break

except Exception as e:
Expand Down
23 changes: 15 additions & 8 deletions plugins/modules/site_intent.py
Original file line number Diff line number Diff line change
Expand Up @@ -645,7 +645,7 @@ def is_building_updated(self, updated_site, requested_site):
updated_site['parentName'] == requested_site['parentName'] and
self.compare_float_values(updated_site['latitude'], requested_site['latitude']) and
self.compare_float_values(updated_site['longitude'], requested_site['longitude']) and
(requested_site['address'] is None or updated_site['address'] == requested_site['address'])
('address' in requested_site and (requested_site['address'] is None or updated_site.get('address') == requested_site['address']))
)

def is_floor_updated(self, updated_site, requested_site):
Expand Down Expand Up @@ -807,11 +807,18 @@ def get_diff_merged(self, config):
else:
# Creating New Site
site_params = self.want.get("site_params")
if site_params['site']['building']:
building_details = {}
for key, value in site_params['site']['building'].items():
if value is not None:
building_details[key] = value
site_params['site']['building'] = building_details

response = self.dnac._exec(
family="sites",
function='create_site',
op_modifies=True,
params=self.want.get("site_params"),
params=site_params,
)
self.log("Received API response from 'create_site': {0}".format(str(response)), "DEBUG")
site_created = True
Expand All @@ -832,20 +839,20 @@ def get_diff_merged(self, config):
break

if site_updated:
log_msg = "Site - {0} Updated Successfully".format(self.want.get("site_name"))
self.log(log_msg, "INFO")
self.result['msg'] = log_msg
self.msg = "Site - {0} Updated Successfully".format(self.want.get("site_name"))
self.log(self.msg, "INFO")
self.result['msg'] = self.msg
self.result['response'].update({"siteId": self.have.get("site_id")})

else:
# Get the site id of the newly created site.
(site_exists, current_site) = self.site_exists()

if site_exists:
log_msg = "Site '{0}' created successfully".format(self.want.get("site_name"))
self.log(log_msg, "INFO")
self.msg = "Site '{0}' created successfully".format(self.want.get("site_name"))
self.log(self.msg, "INFO")
self.log("Current site (have): {0}".format(str(current_site)), "DEBUG")
self.result['msg'] = log_msg
self.result['msg'] = self.msg
self.result['response'].update({"siteId": current_site.get('site_id')})

return self
Expand Down
23 changes: 15 additions & 8 deletions plugins/modules/site_workflow_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -644,7 +644,7 @@ def is_building_updated(self, updated_site, requested_site):
updated_site['parentName'] == requested_site['parentName'] and
self.compare_float_values(updated_site['latitude'], requested_site['latitude']) and
self.compare_float_values(updated_site['longitude'], requested_site['longitude']) and
(requested_site['address'] is None or updated_site['address'] == requested_site['address'])
('address' in requested_site and (requested_site['address'] is None or updated_site.get('address') == requested_site['address']))
)

def is_floor_updated(self, updated_site, requested_site):
Expand Down Expand Up @@ -806,11 +806,18 @@ def get_diff_merged(self, config):
else:
# Creating New Site
site_params = self.want.get("site_params")
if site_params['site']['building']:
building_details = {}
for key, value in site_params['site']['building'].items():
if value is not None:
building_details[key] = value
site_params['site']['building'] = building_details

response = self.dnac._exec(
family="sites",
function='create_site',
op_modifies=True,
params=self.want.get("site_params"),
params=site_params,
)
self.log("Received API response from 'create_site': {0}".format(str(response)), "DEBUG")
site_created = True
Expand All @@ -831,20 +838,20 @@ def get_diff_merged(self, config):
break

if site_updated:
log_msg = "Site - {0} Updated Successfully".format(self.want.get("site_name"))
self.log(log_msg, "INFO")
self.result['msg'] = log_msg
self.msg = "Site - {0} Updated Successfully".format(self.want.get("site_name"))
self.log(self.msg, "INFO")
self.result['msg'] = self.msg
self.result['response'].update({"siteId": self.have.get("site_id")})

else:
# Get the site id of the newly created site.
(site_exists, current_site) = self.site_exists()

if site_exists:
log_msg = "Site '{0}' created successfully".format(self.want.get("site_name"))
self.log(log_msg, "INFO")
self.msg = "Site '{0}' created successfully".format(self.want.get("site_name"))
self.log(self.msg, "INFO")
self.log("Current site (have): {0}".format(str(current_site)), "DEBUG")
self.result['msg'] = log_msg
self.result['msg'] = self.msg
self.result['response'].update({"siteId": current_site.get('site_id')})

return self
Expand Down
Loading

0 comments on commit 8c88ac2

Please sign in to comment.