summaryrefslogtreecommitdiff
path: root/lib/ansible/module_utils/aos.py
blob: e0c00ea06b6f65e10c4e5c60e985743a5ab4a774 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
#
# Copyright (c) 2017 Apstra Inc, <community@apstra.com>
#
# This code is part of Ansible, but is an independent component.
# This particular file snippet, and this file snippet only, is BSD licensed.
# Modules you write using this snippet, which is embedded dynamically by Ansible
# still belong to the author of the module, and may assign their own license
# to the complete work.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
#    * Redistributions of source code must retain the above copyright
#      notice, this list of conditions and the following disclaimer.
#    * Redistributions in binary form must reproduce the above copyright notice,
#      this list of conditions and the following disclaimer in the documentation
#      and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#

"""
This module adds shared support for Apstra AOS modules

In order to use this module, include it as part of your module

from ansible.module_utils.aos import *

"""
import json

from distutils.version import LooseVersion
from ansible.module_utils.pycompat24 import get_exception

try:
    import yaml
    HAS_YAML = True
except ImportError:
    HAS_YAML = False

try:
    from apstra.aosom.session import Session

    HAS_AOS_PYEZ = True
except ImportError:
    HAS_AOS_PYEZ = False

def check_aos_version(module, min=False):
    """
    Check if the library aos-pyez is present.
    If provided, also check if the minimum version requirement is met
    """
    if not HAS_AOS_PYEZ:
        module.fail_json(msg='aos-pyez is not installed.  Please see details '
                             'here: https://github.com/Apstra/aos-pyez')

    elif min:
        import apstra.aosom
        AOS_PYEZ_VERSION = apstra.aosom.__version__

        if not LooseVersion(AOS_PYEZ_VERSION) >= LooseVersion(min):
            module.fail_json(msg='aos-pyez >= %s is required for this module' % min)

    return True

def get_aos_session(module, auth):
    """
    Resume an existing session and return an AOS object.

    Args:
        auth (dict): An AOS session as obtained by aos_login module blocks::

            dict( token=<token>,
                  server=<ip>,
                  port=<port>
                )

    Return:
        Aos object
    """

    check_aos_version(module)

    aos = Session()
    aos.session = auth

    return aos

def find_collection_item(collection, item_name=False, item_id=False):
    """
    Find collection_item based on name or id from a collection object
    Both Collection_item and Collection Objects are provided by aos-pyez library

    Return
        collection_item: object corresponding to the collection type
    """
    my_dict = None

    if item_name:
        my_dict = collection.find(label=item_name)
    elif item_id:
        my_dict = collection.find(uid=item_id)

    if my_dict is None:
        return collection['']
    else:
        return my_dict

def content_to_dict(module, content):
    """
    Convert 'content' into a Python Dict based on 'content_format'
    """

    # if not HAS_YAML:
    #     module.fail_json(msg="Python Library Yaml is not present, mandatory to use 'content'")

    content_dict = None

    #     try:
    #         content_dict = json.loads(content.replace("\'", '"'))
    #     except:
    #         module.fail_json(msg="Unable to convert 'content' from JSON, please check if valid")
    #
    # elif format in ['yaml', 'var']:

    try:
        content_dict = yaml.safe_load(content)

        if not isinstance(content_dict, dict):
            raise Exception()

        # Check if dict is empty and return an error if it's
        if not content_dict:
            raise Exception()

    except:
        module.fail_json(msg="Unable to convert 'content' to a dict, please check if valid")


    # replace the string with the dict
    module.params['content'] = content_dict

    return content_dict

def do_load_resource(module, collection, name):
    """
    Create a new object (collection.item) by loading a datastructure directly
    """

    try:
        item = find_collection_item(collection, name, '')
    except:
        module.fail_json(msg="An error occurred while running 'find_collection_item'")

    if item.exists:
        module.exit_json( changed=False,
                          name=item.name,
                          id=item.id,
                          value=item.value )

    # If not in check mode, apply the changes
    if not module.check_mode:
        try:
            item.datum = module.params['content']
            item.write()
        except:
            e = get_exception()
            module.fail_json(msg="Unable to write item content : %r" % e)

    module.exit_json( changed=True,
                      name=item.name,
                      id=item.id,
                      value=item.value )