summaryrefslogtreecommitdiff
path: root/lib/ansible/modules/network/netconf/netconf_config.py
blob: ac10600acce1108d9389caf66b8e0427ad870f8f (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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
#!/usr/bin/python

# (c) 2016, Leandro Lisboa Penz <lpenz at lpenz.org>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.

ANSIBLE_METADATA = {'metadata_version': '1.0',
                    'status': ['preview'],
                    'supported_by': 'community'}


DOCUMENTATION = '''
---
module: netconf_config
author: "Leandro Lisboa Penz (@lpenz)"
short_description: netconf device configuration
description:
    - Netconf is a network management protocol developed and standardized by
      the IETF. It is documented in RFC 6241.

    - This module allows the user to send a configuration XML file to a netconf
      device, and detects if there was a configuration change.
notes:
    - This module supports devices with and without the the candidate and
      confirmed-commit capabilities. It always use the safer feature.
version_added: "2.2"
options:
  host:
    description:
     - the hostname or ip address of the netconf device
    required: true
  port:
    description:
     - the netconf port
    default: 830
    required: false
  hostkey_verify:
    description:
     - if true, the ssh host key of the device must match a ssh key present on the host
     - if false, the ssh host key of the device is not checked
    default: true
    required: false
  look_for_keys:
    description:
     - if true, enables looking in the usual locations for ssh keys (e.g. ~/.ssh/id_*)
     - if false, disables looking for ssh keys
    default: true
    required: false
    version_added: "2.4"
  allow_agent:
    description:
     - if true, enables querying SSH agent (if found) for keys
     - if false, disables querying the SSH agent for ssh keys
    default: true
    required: false
    version_added: "2.4"
  datastore:
    description:
     - auto, uses candidate and fallback to running
     - candidate, edit <candidate/> datastore and then commit
     - running, edit <running/> datastore directly
    default: auto
    required: false
    version_added: "2.4"
  save:
    description:
      - The C(save) argument instructs the module to save the running-
        config to the startup-config if changed.
    required: false
    default: false
    version_added: "2.4"
  username:
    description:
     - the username to authenticate with
    required: true
  password:
    description:
     - password of the user to authenticate with
    required: true
  xml:
    description:
     - the XML content to send to the device
    required: false
  src:
    description:
      - Specifies the source path to the xml file that contains the configuration
        or configuration template to load.  The path to the source file can
        either be the full path on the Ansible control host or a relative
        path from the playbook or role root directory.  This argument is mutually
        exclusive with I(xml).
    required: false
    version_added: "2.4"


requirements:
  - "python >= 2.6"
  - "ncclient"
'''

EXAMPLES = '''
- name: set ntp server in the device
  netconf_config:
    host: 10.0.0.1
    username: admin
    password: admin
    xml: |
        <config xmlns:xc="urn:ietf:params:xml:ns:netconf:base:1.0">
            <system xmlns="urn:ietf:params:xml:ns:yang:ietf-system">
                <ntp>
                    <enabled>true</enabled>
                    <server>
                        <name>ntp1</name>
                        <udp><address>127.0.0.1</address></udp>
                    </server>
                </ntp>
            </system>
        </config>

- name: wipe ntp configuration
  netconf_config:
    host: 10.0.0.1
    username: admin
    password: admin
    xml: |
        <config xmlns:xc="urn:ietf:params:xml:ns:netconf:base:1.0">
            <system xmlns="urn:ietf:params:xml:ns:yang:ietf-system">
                <ntp>
                    <enabled>false</enabled>
                    <server operation="remove">
                        <name>ntp1</name>
                    </server>
                </ntp>
            </system>
        </config>

'''

RETURN = '''
server_capabilities:
    description: list of capabilities of the server
    returned: success
    type: list
    sample: ['urn:ietf:params:netconf:base:1.1','urn:ietf:params:netconf:capability:confirmed-commit:1.0','urn:ietf:params:netconf:capability:candidate:1.0']

'''

import xml.dom.minidom
try:
    import ncclient.manager
    HAS_NCCLIENT = True
except ImportError:
    HAS_NCCLIENT = False


import logging


def netconf_edit_config(m, xml, commit, retkwargs, datastore):
    m.lock(target=datastore)
    try:
        if datastore == "candidate":
            m.discard_changes()
        config_before = m.get_config(source=datastore)
        m.edit_config(target=datastore, config=xml)
        config_after = m.get_config(source=datastore)
        changed = config_before.data_xml != config_after.data_xml
        if changed and commit and datastore == "candidate":
            if ":confirmed-commit" in m.server_capabilities:
                m.commit(confirmed=True)
                m.commit()
            else:
                m.commit()
        return changed
    finally:
        m.unlock(target=datastore)


# ------------------------------------------------------------------- #
# Main


def main():

    module = AnsibleModule(
        argument_spec=dict(
            host=dict(type='str', required=True),
            port=dict(type='int', default=830),
            hostkey_verify=dict(type='bool', default=True),
            allow_agent=dict(type='bool', default=True),
            look_for_keys=dict(type='bool', default=True),
            datastore=dict(choices=['auto', 'candidate', 'running'], default='auto'),
            save=dict(type='bool', default=False),
            username=dict(type='str', required=True, no_log=True),
            password=dict(type='str', required=True, no_log=True),
            xml=dict(type='str', required=False),
            src=dict(type='path', required=False),
        ),
        mutually_exclusive=[('xml', 'src')]
    )

    if not HAS_NCCLIENT:
        module.fail_json(msg='could not import the python library '
                         'ncclient required by this module')

    if (module.params['src']):
        config_xml = str(module.params['src'])
    elif module.params['xml']:
        config_xml = str(module.params['xml'])
    else:
        module.fail_json(msg='Option src or xml must be provided')

    try:
        xml.dom.minidom.parseString(config_xml)

    except:
        e = get_exception()
        module.fail_json(
            msg='error parsing XML: ' + str(e)
        )

    nckwargs = dict(
        host=module.params['host'],
        port=module.params['port'],
        hostkey_verify=module.params['hostkey_verify'],
        allow_agent=module.params['allow_agent'],
        look_for_keys=module.params['look_for_keys'],
        username=module.params['username'],
        password=module.params['password'],
    )

    try:
        m = ncclient.manager.connect(**nckwargs)
    except ncclient.transport.errors.AuthenticationError:
        module.fail_json(
            msg='authentication failed while connecting to device'
        )
    except:
        e = get_exception()
        module.fail_json(
            msg='error connecting to the device: ' + str(e)
        )

    retkwargs = dict()
    retkwargs['server_capabilities'] = list(m.server_capabilities)

    if module.params['datastore'] == 'candidate':
        if ':candidate' in m.server_capabilities:
            datastore = 'candidate'
        else:
            m.close_session()
            module.fail_json(
                msg=':candidate is not supported by this netconf server'
            )
    elif module.params['datastore'] == 'running':
        if ':writable-running' in m.server_capabilities:
            datastore = 'running'
        else:
            m.close_session()
            module.fail_json(
                msg=':writable-running is not supported by this netconf server'
            )
    elif module.params['datastore'] == 'auto':
        if ':candidate' in m.server_capabilities:
            datastore = 'candidate'
        elif ':writable-running' in m.server_capabilities:
            datastore = 'running'
        else:
            m.close_session()
            module.fail_json(
                msg='neither :candidate nor :writable-running are supported by this netconf server'
            )
    else:
        m.close_session()
        module.fail_json(
            msg=module.params['datastore'] + ' datastore is not supported by this ansible module'
        )

    if module.params['save']:
        if ':startup' not in m.server_capabilities:
            module.fail_json(
                msg='cannot copy <running/> to <startup/>, while :startup is not supported'
            )

    try:
        changed = netconf_edit_config(
            m=m,
            xml=config_xml,
            commit=True,
            retkwargs=retkwargs,
            datastore=datastore,
        )
        if changed and module.params['save']:
            m.copy_config(source="running", target="startup")
    except:
        e = get_exception()
        module.fail_json(
            msg='error editing configuration: ' + str(e)
        )
    finally:
        m.close_session()

    module.exit_json(changed=changed, **retkwargs)

# import module snippets
from ansible.module_utils.basic import *

if __name__ == '__main__':
    main()