Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
1. plugins/modules/dcnm_log.py

An Ansible module for the DCNM Collection to log to the file pointed to by NDFC_LOGGING_CONFIG.

2. tests/integration/targets/dcnm_log/*

Integration tests for dcnm_log.py
  • Loading branch information
allenrobel committed Jan 31, 2025
1 parent b179ee4 commit ead2215
Show file tree
Hide file tree
Showing 6 changed files with 334 additions and 0 deletions.
162 changes: 162 additions & 0 deletions plugins/modules/dcnm_log.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
#!/usr/bin/python
#
# Copyright (c) 2020-2022 Cisco and/or its affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import, division, print_function

__metaclass__ = type
__author__ = "Mike Wiebe"

DOCUMENTATION = """
---
module: dcnm_log
short_description: Log messages to the target pointed to by env variable NDFC_LOGGING_CONFIG.
version_added: "3.6.1"
description:
- "Log messages to the target pointed to by env variable NDFC_LOGGING_CONFIG."
options:
message:
description:
- The message to log
required: yes
type: str
severity:
description:
- Case-insensitive logging severity with which to log the message
required: no
default: DEBUG
choices: ['CRITICAL', 'critical', 'DEBUG', 'debug', 'ERROR', 'error', 'INFO', 'info', 'WARNING', 'warning']
type: str
author:
- Allen Robel (@quantumonion)
"""

EXAMPLES = """
# This module can be used to correlate Ansible DCNM task execution with the
# log messages generated by the DCNM Ansible modules (when the NDFC_LOGGING_CONFIG
# environment variable is set to point to a valid python logging configuration)
#
- name: Log
cisco.dcnm.dcnm_log:
message: dcnm_vrf.merged - Create VRF myVrf
severity: INFO
- name: dcnm_vrf.merged - Create VRF myVrf
cisco.dcnm.dcnm_vrf:
fabric: vxlan-fabric
state: merged
config:
- vrf_name: myVrf
vrf_id: 9008011
vrf_template: Default_VRF_Universal
vrf_extension_template: Default_VRF_Extension_Universal
vlan_id: 2000
service_vrf_template: null
attach:
- ip_address: 192.168.1.224
- ip_address: 192.168.1.225
- name: Log
cisco.dcnm.dcnm_log:
message: dcnm_vrf.merged - Create VRF myVrf DONE
severity: INFO
""" # noqa

RETURN = """
response:
description:
- result dictionary containing keys changed, msg, results, skipped
returned: always
type: dict
elements: dict
"""
import logging

from ansible.module_utils.basic import AnsibleModule

from ..module_utils.common.log_v2 import Log

class DcnmLog:
"""
- name: Log message
cisco.dcnm.dcnm_log:
message: This is a log message.
"""
def __init__(self, module):
self.class_name = self.__class__.__name__

self.log = logging.getLogger(f"dcnm.{self.class_name}")

self.module = module
self.params = module.params
self.message = self.params.get("message")
self.severity = self.params.get("severity")
self.severity = self.severity.upper()

self.result = dict()
self.result["changed"] = False
self.result["failed"] = False

def log_message(self):
try:
if self.severity == "CRITICAL":
self.log.critical(self.message)
if self.severity == "DEBUG":
self.log.debug(self.message)
if self.severity == "ERROR":
self.log.error(self.message)
if self.severity == "INFO":
self.log.info(self.message)
if self.severity == "WARNING":
self.log.warning(self.message)
except ValueError as error:
raise ValueError from error

def main():
# Logging setup
try:
log = Log()
log.commit()
except (TypeError, ValueError):
pass

# choices = []
# choices.append("CRITICAL")
# choices.append("")
element_spec = dict(
message=dict(
default="",
),
severity=dict(
default="DEBUG",
choices=["CRITICAL", "critical", "DEBUG", "debug", "ERROR", "INFO", "WARNING"]
# choices=["CRITICAL", "critical", "DEBUG", "debug", "ERROR", "INFO", "WARNING"]
)
)

module = AnsibleModule(argument_spec=element_spec, supports_check_mode=False)
dcnm_log = DcnmLog(module)
try:
dcnm_log.log_message()
except ValueError as error:
dcnm_log.result["failed"] = True
module.fail_json(msg=error)

module.exit_json(**dcnm_log.result)

if __name__ == "__main__":
main()
2 changes: 2 additions & 0 deletions tests/integration/targets/dcnm_log/defaults/main.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
---
testcase: "*"
1 change: 1 addition & 0 deletions tests/integration/targets/dcnm_log/meta/main.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
dependencies: []
32 changes: 32 additions & 0 deletions tests/integration/targets/dcnm_log/tasks/dcnm.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
---
- name: collect dcnm test cases
find:
paths: ["{{ role_path }}/tests/dcnm"]
patterns: "{{ testcase }}.yaml"
connection: local
register: dcnm_cases
tags: sanity

- set_fact:
test_cases:
files: "{{ dcnm_cases.files }}"
tags: sanity

- name: set test_items
set_fact: test_items="{{ test_cases.files | map(attribute='path') | list }}"
tags: sanity

- name: Debug test_items
debug:
var: test_items

- name: Debug tesetcase
debug:
var: testcase

- name: run test cases (connection=httpapi)
include_tasks: "{{ test_case_to_run }}"
with_items: "{{ test_items }}"
loop_control:
loop_var: test_case_to_run
tags: sanity
5 changes: 5 additions & 0 deletions tests/integration/targets/dcnm_log/tasks/main.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---

- name: Import Role Tasks
ansible.builtin.import_tasks: dcnm.yaml
tags: ['dcnm']
132 changes: 132 additions & 0 deletions tests/integration/targets/dcnm_log/tests/dcnm/test_logging.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
##############################################
## TESTCASE ##
##############################################
# test_logging
#
##############################################
## PREREQUISITES ##
##############################################
#
# The environment variable NDFC_LOGGING_CONFIG must be set.
# The value is an absolute path to the logging config file.
#
# Example:
#
# export NDFC_LOGGING_CONFIG=$HOME/repos/ansible/collections/ansible_collections/cisco/dcnm/plugins/module_utils/common/logging_config.json
#
##############################################
## SETUP ##
##############################################

- name: SETUP.1 set value of Verify NDFC_LOGGING_CONFIG
ansible.builtin.set_fact:
ndfc_logging_config: "{{ lookup('env','NDFC_LOGGING_CONFIG', errors='strict') }}"
register: result_setup_1

- name: debug ndfc_logging_config
ansible.builtin.debug:
var: ndfc_logging_config

- assert:
that:
- ndfc_logging_config != ""

##############################################
## TESTS ##
##############################################

- name: TEST.1 - Verify DEBUG severity.
cisco.dcnm.dcnm_log:
message: Testing DEBUG severity
severity: DEBUG
register: result_1

- name: debug result_1
ansible.builtin.debug:
var: result_1

- assert:
that:
- 'result_1.changed == false'
- 'result_1.failed == false'


- name: TEST.2 - Verify ERROR severity.
cisco.dcnm.dcnm_log:
message: Testing ERROR severity
severity: ERROR
register: result_2

- name: debug result_2
ansible.builtin.debug:
var: result_2

- assert:
that:
- 'result_2.changed == false'
- 'result_2.failed == false'

- name: TEST.3 - Verify INFO severity.
cisco.dcnm.dcnm_log:
message: Testing INFO severity
severity: INFO
register: result_3

- name: debug result_3
ansible.builtin.debug:
var: result_3

- assert:
that:
- 'result_3.changed == false'
- 'result_3.failed == false'

- name: TEST.4 - Verify WARNING severity.
cisco.dcnm.dcnm_log:
message: Testing WARNING severity
severity: WARNING
register: result_4

- name: debug result_4
ansible.builtin.debug:
var: result_4

- assert:
that:
- 'result_4.changed == false'
- 'result_4.failed == false'

- name: TEST.5 - Verify lowercase (debug) severity.
cisco.dcnm.dcnm_log:
message: Testing debug severity
severity: debug
register: result_5

- name: debug result_5
ansible.builtin.debug:
var: result_5

- assert:
that:
- 'result_5.changed == false'
- 'result_5.failed == false'

- name: TEST.6 - Negative. Verify invalid severity (FOO).
cisco.dcnm.dcnm_log:
message: Testing FOO severity
severity: FOO
register: result_6
ignore_errors: true

- name: debug result_6
ansible.builtin.debug:
var: result_6

- set_fact:
message: value of severity must be one of

- assert:
that:
- 'result_6.changed == false'
- 'result_6.failed == true'
- message in result_6.msg

0 comments on commit ead2215

Please sign in to comment.