mirror of https://github.com/ansible/ansible.git
Adds the bigip_data_group module (#39180)
This module can be used to manipulate bigip data groups.pull/39161/head
parent
c262dbfd30
commit
d38ae9b6c9
@ -0,0 +1,367 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
#
|
||||||
|
# Copyright: (c) 2017, F5 Networks Inc.
|
||||||
|
# GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||||
|
|
||||||
|
from __future__ import absolute_import, division, print_function
|
||||||
|
__metaclass__ = type
|
||||||
|
|
||||||
|
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
from ansible.module_utils.urls import open_url, fetch_url
|
||||||
|
from ansible.module_utils.parsing.convert_bool import BOOLEANS
|
||||||
|
from ansible.module_utils.six import string_types
|
||||||
|
from ansible.module_utils.six import iteritems
|
||||||
|
from ansible.module_utils.urls import urllib_error
|
||||||
|
from ansible.module_utils._text import to_native
|
||||||
|
from ansible.module_utils.six import PY3
|
||||||
|
|
||||||
|
try:
|
||||||
|
import json as _json
|
||||||
|
except ImportError:
|
||||||
|
import simplejson as _json
|
||||||
|
|
||||||
|
try:
|
||||||
|
from library.module_utils.network.f5.common import F5ModuleError
|
||||||
|
except ImportError:
|
||||||
|
from ansible.module_utils.network.f5.common import F5ModuleError
|
||||||
|
|
||||||
|
|
||||||
|
"""An F5 REST API URI handler.
|
||||||
|
|
||||||
|
Use this module to make calls to an F5 REST server. It is influenced by the same
|
||||||
|
API that the Python ``requests`` tool uses, but the two are not the same, as the
|
||||||
|
library here is **much** more simple and targeted specifically to F5's needs.
|
||||||
|
|
||||||
|
The ``requests`` design was chosen due to familiarity with the tool. Internals though
|
||||||
|
use Ansible native libraries.
|
||||||
|
|
||||||
|
The means by which you should use it are similar to ``requests`` basic usage.
|
||||||
|
|
||||||
|
Authentication is not handled for you automatically by this library, however it *is*
|
||||||
|
handled automatically for you in the supporting F5 module_utils code; specifically the
|
||||||
|
different product module_util files (bigip.py, bigiq.py, etc).
|
||||||
|
|
||||||
|
Internal (non-module) usage of this library looks like this.
|
||||||
|
|
||||||
|
```
|
||||||
|
# Create a session instance
|
||||||
|
mgmt = iControlRestSession()
|
||||||
|
mgmt.verify = False
|
||||||
|
|
||||||
|
server = '1.1.1.1'
|
||||||
|
port = 443
|
||||||
|
|
||||||
|
# Payload used for getting an initial authentication token
|
||||||
|
payload = {
|
||||||
|
'username': 'admin',
|
||||||
|
'password': 'secret',
|
||||||
|
'loginProviderName': 'tmos'
|
||||||
|
}
|
||||||
|
|
||||||
|
# Create URL to call, injecting server and port
|
||||||
|
url = f"https://{server}:{port}/mgmt/shared/authn/login"
|
||||||
|
|
||||||
|
# Call the API
|
||||||
|
resp = session.post(url, json=payload)
|
||||||
|
|
||||||
|
# View the response
|
||||||
|
print(resp.json())
|
||||||
|
|
||||||
|
# Update the session with the authentication token
|
||||||
|
session.headers['X-F5-Auth-Token'] = resp.json()['token']['token']
|
||||||
|
|
||||||
|
# Create another URL to call, injecting server and port
|
||||||
|
url = f"https://{server}:{port}/mgmt/tm/ltm/virtual/~Common~virtual1"
|
||||||
|
|
||||||
|
# Call the API
|
||||||
|
resp = session.get(url)
|
||||||
|
|
||||||
|
# View the details of a virtual payload
|
||||||
|
print(resp.json())
|
||||||
|
```
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
class Request(object):
|
||||||
|
def __init__(self, method=None, url=None, headers=None, data=None, params=None,
|
||||||
|
auth=None, json=None):
|
||||||
|
self.method = method
|
||||||
|
self.url = url
|
||||||
|
self.headers = headers or {}
|
||||||
|
self.data = data or []
|
||||||
|
self.json = json
|
||||||
|
self.params = params or {}
|
||||||
|
self.auth = auth
|
||||||
|
|
||||||
|
def prepare(self):
|
||||||
|
p = PreparedRequest()
|
||||||
|
p.prepare(
|
||||||
|
method=self.method,
|
||||||
|
url=self.url,
|
||||||
|
headers=self.headers,
|
||||||
|
data=self.data,
|
||||||
|
json=self.json,
|
||||||
|
params=self.params,
|
||||||
|
)
|
||||||
|
return p
|
||||||
|
|
||||||
|
|
||||||
|
class PreparedRequest(object):
|
||||||
|
def __init__(self):
|
||||||
|
self.method = None
|
||||||
|
self.url = None
|
||||||
|
self.headers = None
|
||||||
|
self.body = None
|
||||||
|
|
||||||
|
def prepare(self, method=None, url=None, headers=None, data=None, params=None, json=None):
|
||||||
|
self.prepare_method(method)
|
||||||
|
self.prepare_url(url, params)
|
||||||
|
self.prepare_headers(headers)
|
||||||
|
self.prepare_body(data, json)
|
||||||
|
|
||||||
|
def prepare_url(self, url, params):
|
||||||
|
self.url = url
|
||||||
|
|
||||||
|
def prepare_method(self, method):
|
||||||
|
self.method = method
|
||||||
|
if self.method:
|
||||||
|
self.method = self.method.upper()
|
||||||
|
|
||||||
|
def prepare_headers(self, headers):
|
||||||
|
self.headers = {}
|
||||||
|
if headers:
|
||||||
|
for k, v in iteritems(headers):
|
||||||
|
self.headers[k] = v
|
||||||
|
|
||||||
|
def prepare_body(self, data, json=None):
|
||||||
|
body = None
|
||||||
|
content_type = None
|
||||||
|
|
||||||
|
if not data and json is not None:
|
||||||
|
self.headers['Content-Type'] = 'application/json'
|
||||||
|
body = _json.dumps(json)
|
||||||
|
if not isinstance(body, bytes):
|
||||||
|
body = body.encode('utf-8')
|
||||||
|
|
||||||
|
if data:
|
||||||
|
body = data
|
||||||
|
content_type = None
|
||||||
|
|
||||||
|
if content_type and 'content-type' not in self.headers:
|
||||||
|
self.headers['Content-Type'] = content_type
|
||||||
|
|
||||||
|
self.body = body
|
||||||
|
|
||||||
|
|
||||||
|
class Response(object):
|
||||||
|
def __init__(self):
|
||||||
|
self._content = None
|
||||||
|
self.status_code = None
|
||||||
|
self.headers = dict()
|
||||||
|
self.url = None
|
||||||
|
self.reason = None
|
||||||
|
self.request = None
|
||||||
|
|
||||||
|
def json(self):
|
||||||
|
return _json.loads(self._content)
|
||||||
|
|
||||||
|
|
||||||
|
class iControlRestSession(object):
|
||||||
|
"""Represents a session that communicates with a BigIP.
|
||||||
|
|
||||||
|
Instantiate one of these when you want to communicate with an F5 REST
|
||||||
|
Server, it will handle F5-specific authentication.
|
||||||
|
|
||||||
|
Pass an existing authentication token to the ``token`` argument to re-use
|
||||||
|
that token for authentication. Otherwise, token authentication is handled
|
||||||
|
automatically for you.
|
||||||
|
|
||||||
|
On BIG-IQ, it may be necessary to pass the ``auth_provider`` argument if the
|
||||||
|
user has a different authentication handler configured. Otherwise, the system
|
||||||
|
defaults for the different products will be used.
|
||||||
|
"""
|
||||||
|
def __init__(self):
|
||||||
|
self.headers = self.default_headers()
|
||||||
|
self.verify = True
|
||||||
|
self.params = {}
|
||||||
|
self.auth = None
|
||||||
|
self.timeout = 30
|
||||||
|
|
||||||
|
def _normalize_headers(self, headers):
|
||||||
|
result = {}
|
||||||
|
result.update(dict((k.lower(), v) for k, v in headers))
|
||||||
|
|
||||||
|
# Don't be lossy, append header values for duplicate headers
|
||||||
|
# In Py2 there is nothing that needs done, py2 does this for us
|
||||||
|
if PY3:
|
||||||
|
temp_headers = {}
|
||||||
|
for name, value in headers:
|
||||||
|
# The same as above, lower case keys to match py2 behavior, and create more consistent results
|
||||||
|
name = name.lower()
|
||||||
|
if name in temp_headers:
|
||||||
|
temp_headers[name] = ', '.join((temp_headers[name], value))
|
||||||
|
else:
|
||||||
|
temp_headers[name] = value
|
||||||
|
result.update(temp_headers)
|
||||||
|
return result
|
||||||
|
|
||||||
|
def default_headers(self):
|
||||||
|
return {
|
||||||
|
'connection': 'keep-alive',
|
||||||
|
'accept': '*/*',
|
||||||
|
}
|
||||||
|
|
||||||
|
def prepare_request(self, request):
|
||||||
|
headers = self.headers.copy()
|
||||||
|
params = self.params.copy()
|
||||||
|
|
||||||
|
if request.headers is not None:
|
||||||
|
headers.update(request.headers)
|
||||||
|
if request.params is not None:
|
||||||
|
params.update(request.params)
|
||||||
|
|
||||||
|
prepared = PreparedRequest()
|
||||||
|
prepared.prepare(
|
||||||
|
method=request.method,
|
||||||
|
url=request.url,
|
||||||
|
data=request.data,
|
||||||
|
json=request.json,
|
||||||
|
headers=headers,
|
||||||
|
params=params,
|
||||||
|
)
|
||||||
|
return prepared
|
||||||
|
|
||||||
|
def request(self, method, url, params=None, data=None, headers=None, auth=None,
|
||||||
|
timeout=None, verify=None, json=None):
|
||||||
|
request = Request(
|
||||||
|
method=method.upper(),
|
||||||
|
url=url,
|
||||||
|
headers=headers,
|
||||||
|
json=json,
|
||||||
|
data=data or {},
|
||||||
|
params=params or {},
|
||||||
|
auth=auth
|
||||||
|
)
|
||||||
|
kwargs = dict(
|
||||||
|
timeout=timeout,
|
||||||
|
verify=verify
|
||||||
|
)
|
||||||
|
prepared = self.prepare_request(request)
|
||||||
|
return self.send(prepared, **kwargs)
|
||||||
|
|
||||||
|
def send(self, request, **kwargs):
|
||||||
|
response = Response()
|
||||||
|
|
||||||
|
params = dict(
|
||||||
|
method=request.method,
|
||||||
|
data=request.body,
|
||||||
|
timeout=kwargs.get('timeout', None) or self.timeout,
|
||||||
|
headers=request.headers
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
result = open_url(request.url, **params)
|
||||||
|
response._content = result.read()
|
||||||
|
response.status = result.getcode()
|
||||||
|
response.url = result.geturl()
|
||||||
|
response.msg = "OK (%s bytes)" % result.headers.get('Content-Length', 'unknown')
|
||||||
|
response.headers = self._normalize_headers(result.headers.items())
|
||||||
|
response.request = request
|
||||||
|
except urllib_error.HTTPError as e:
|
||||||
|
try:
|
||||||
|
response._content = e.read()
|
||||||
|
except AttributeError:
|
||||||
|
response._content = ''
|
||||||
|
|
||||||
|
response.reason = to_native(e)
|
||||||
|
response.status_code = e.code
|
||||||
|
return response
|
||||||
|
|
||||||
|
def delete(self, url, **kwargs):
|
||||||
|
"""Sends a HTTP DELETE command to an F5 REST Server.
|
||||||
|
|
||||||
|
Use this method to send a DELETE command to an F5 product.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
url (string): URL to call.
|
||||||
|
data (bytes): An object specifying additional data to send to the server,
|
||||||
|
or ``None`` if no such data is needed. Currently HTTP requests are the
|
||||||
|
only ones that use data. The supported object types include bytes,
|
||||||
|
file-like objects, and iterables.
|
||||||
|
See https://docs.python.org/3/library/urllib.request.html#urllib.request.Request
|
||||||
|
\\*\\*kwargs (dict): Optional arguments to send to the request.
|
||||||
|
"""
|
||||||
|
return self.request('DELETE', url, **kwargs)
|
||||||
|
|
||||||
|
def get(self, url, **kwargs):
|
||||||
|
"""Sends a HTTP GET command to an F5 REST Server.
|
||||||
|
|
||||||
|
Use this method to send a GET command to an F5 product.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
url (string): URL to call.
|
||||||
|
\\*\\*kwargs (dict): Optional arguments to send to the request.
|
||||||
|
"""
|
||||||
|
return self.request('GET', url, **kwargs)
|
||||||
|
|
||||||
|
def patch(self, url, data=None, **kwargs):
|
||||||
|
"""Sends a HTTP PATCH command to an F5 REST Server.
|
||||||
|
|
||||||
|
Use this method to send a PATCH command to an F5 product.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
url (string): URL to call.
|
||||||
|
data (bytes): An object specifying additional data to send to the server,
|
||||||
|
or ``None`` if no such data is needed. Currently HTTP requests are the
|
||||||
|
only ones that use data. The supported object types include bytes,
|
||||||
|
file-like objects, and iterables.
|
||||||
|
See https://docs.python.org/3/library/urllib.request.html#urllib.request.Request
|
||||||
|
\\*\\*kwargs (dict): Optional arguments to send to the request.
|
||||||
|
"""
|
||||||
|
return self.request('PATCH', url, data=data, **kwargs)
|
||||||
|
|
||||||
|
def post(self, url, data=None, json=None, **kwargs):
|
||||||
|
"""Sends a HTTP POST command to an F5 REST Server.
|
||||||
|
|
||||||
|
Use this method to send a POST command to an F5 product.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
url (string): URL to call.
|
||||||
|
data (dict): An object specifying additional data to send to the server,
|
||||||
|
or ``None`` if no such data is needed. Currently HTTP requests are the
|
||||||
|
only ones that use data. The supported object types include bytes,
|
||||||
|
file-like objects, and iterables.
|
||||||
|
See https://docs.python.org/3/library/urllib.request.html#urllib.request.Request
|
||||||
|
\\*\\*kwargs (dict): Optional arguments to the request.
|
||||||
|
"""
|
||||||
|
return self.request('POST', url, data=data, json=json, **kwargs)
|
||||||
|
|
||||||
|
def put(self, url, data=None, **kwargs):
|
||||||
|
"""Sends a HTTP PUT command to an F5 REST Server.
|
||||||
|
|
||||||
|
Use this method to send a PUT command to an F5 product.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
url (string): URL to call.
|
||||||
|
data (bytes): An object specifying additional data to send to the server,
|
||||||
|
or ``None`` if no such data is needed. Currently HTTP requests are the
|
||||||
|
only ones that use data. The supported object types include bytes,
|
||||||
|
file-like objects, and iterables.
|
||||||
|
See https://docs.python.org/3/library/urllib.request.html#urllib.request.Request
|
||||||
|
\\*\\*kwargs (dict): Optional arguments to the request.
|
||||||
|
"""
|
||||||
|
return self.request('PUT', url, data=data, **kwargs)
|
||||||
|
|
||||||
|
|
||||||
|
def debug_prepared_request(url, method, headers, data=None):
|
||||||
|
result = "curl -k -X {0} {1}".format(method.upper(), url)
|
||||||
|
for k, v in iteritems(headers):
|
||||||
|
result = result + " -H '{0}: {1}'".format(k, v)
|
||||||
|
if any(v == 'application/json' for k, v in iteritems(headers)):
|
||||||
|
if data:
|
||||||
|
kwargs = _json.loads(data.decode('utf-8'))
|
||||||
|
result = result + " -d '" + _json.dumps(kwargs, sort_keys=True) + "'"
|
||||||
|
return result
|
@ -0,0 +1,121 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
#
|
||||||
|
# Copyright (c) 2017 F5 Networks Inc.
|
||||||
|
# GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||||
|
|
||||||
|
from __future__ import absolute_import, division, print_function
|
||||||
|
__metaclass__ = type
|
||||||
|
|
||||||
|
try:
|
||||||
|
import bigsuds
|
||||||
|
bigsuds_found = True
|
||||||
|
except ImportError:
|
||||||
|
bigsuds_found = False
|
||||||
|
|
||||||
|
|
||||||
|
from ansible.module_utils.basic import env_fallback
|
||||||
|
|
||||||
|
|
||||||
|
def f5_argument_spec():
|
||||||
|
return dict(
|
||||||
|
server=dict(
|
||||||
|
type='str',
|
||||||
|
required=True,
|
||||||
|
fallback=(env_fallback, ['F5_SERVER'])
|
||||||
|
),
|
||||||
|
user=dict(
|
||||||
|
type='str',
|
||||||
|
required=True,
|
||||||
|
fallback=(env_fallback, ['F5_USER'])
|
||||||
|
),
|
||||||
|
password=dict(
|
||||||
|
type='str',
|
||||||
|
aliases=['pass', 'pwd'],
|
||||||
|
required=True,
|
||||||
|
no_log=True,
|
||||||
|
fallback=(env_fallback, ['F5_PASSWORD'])
|
||||||
|
),
|
||||||
|
validate_certs=dict(
|
||||||
|
default='yes',
|
||||||
|
type='bool',
|
||||||
|
fallback=(env_fallback, ['F5_VALIDATE_CERTS'])
|
||||||
|
),
|
||||||
|
server_port=dict(
|
||||||
|
type='int',
|
||||||
|
default=443,
|
||||||
|
fallback=(env_fallback, ['F5_SERVER_PORT'])
|
||||||
|
),
|
||||||
|
state=dict(
|
||||||
|
type='str',
|
||||||
|
default='present',
|
||||||
|
choices=['present', 'absent']
|
||||||
|
),
|
||||||
|
partition=dict(
|
||||||
|
type='str',
|
||||||
|
default='Common',
|
||||||
|
fallback=(env_fallback, ['F5_PARTITION'])
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def f5_parse_arguments(module):
|
||||||
|
if not bigsuds_found:
|
||||||
|
module.fail_json(msg="the python bigsuds module is required")
|
||||||
|
|
||||||
|
if module.params['validate_certs']:
|
||||||
|
import ssl
|
||||||
|
if not hasattr(ssl, 'SSLContext'):
|
||||||
|
module.fail_json(
|
||||||
|
msg="bigsuds does not support verifying certificates with python < 2.7.9."
|
||||||
|
"Either update python or set validate_certs=False on the task'")
|
||||||
|
|
||||||
|
return (
|
||||||
|
module.params['server'],
|
||||||
|
module.params['user'],
|
||||||
|
module.params['password'],
|
||||||
|
module.params['state'],
|
||||||
|
module.params['partition'],
|
||||||
|
module.params['validate_certs'],
|
||||||
|
module.params['server_port']
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def bigip_api(bigip, user, password, validate_certs, port=443):
|
||||||
|
try:
|
||||||
|
if bigsuds.__version__ >= '1.0.4':
|
||||||
|
api = bigsuds.BIGIP(hostname=bigip, username=user, password=password, verify=validate_certs, port=port)
|
||||||
|
elif bigsuds.__version__ == '1.0.3':
|
||||||
|
api = bigsuds.BIGIP(hostname=bigip, username=user, password=password, verify=validate_certs)
|
||||||
|
else:
|
||||||
|
api = bigsuds.BIGIP(hostname=bigip, username=user, password=password)
|
||||||
|
except TypeError:
|
||||||
|
# bigsuds < 1.0.3, no verify param
|
||||||
|
if validate_certs:
|
||||||
|
# Note: verified we have SSLContext when we parsed params
|
||||||
|
api = bigsuds.BIGIP(hostname=bigip, username=user, password=password)
|
||||||
|
else:
|
||||||
|
import ssl
|
||||||
|
if hasattr(ssl, 'SSLContext'):
|
||||||
|
# Really, you should never do this. It disables certificate
|
||||||
|
# verification *globally*. But since older bigip libraries
|
||||||
|
# don't give us a way to toggle verification we need to
|
||||||
|
# disable it at the global level.
|
||||||
|
# From https://www.python.org/dev/peps/pep-0476/#id29
|
||||||
|
ssl._create_default_https_context = ssl._create_unverified_context
|
||||||
|
api = bigsuds.BIGIP(hostname=bigip, username=user, password=password)
|
||||||
|
|
||||||
|
return api
|
||||||
|
|
||||||
|
|
||||||
|
# Fully Qualified name (with the partition)
|
||||||
|
def fq_name(partition, name):
|
||||||
|
if name is not None and not name.startswith('/'):
|
||||||
|
return '/%s/%s' % (partition, name)
|
||||||
|
return name
|
||||||
|
|
||||||
|
|
||||||
|
# Fully Qualified name (with partition) for a list
|
||||||
|
def fq_list_names(partition, list_names):
|
||||||
|
if list_names is None:
|
||||||
|
return None
|
||||||
|
return map(lambda x: fq_name(partition, x), list_names)
|
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,5 @@
|
|||||||
|
network 10.0.0.0 prefixlen 8 := "Network1",
|
||||||
|
network 172.16.0.0 prefixlen 12 := "Network2",
|
||||||
|
network 192.168.0.0 prefixlen 16 := "Network3",
|
||||||
|
host 192.168.20.1 := "Host1",
|
||||||
|
host 172.16.1.1 := "Host2",
|
@ -0,0 +1,6 @@
|
|||||||
|
1 := alpha
|
||||||
|
2 := bravo
|
||||||
|
3 := charlie
|
||||||
|
4 := x-ray
|
||||||
|
5 := yankee
|
||||||
|
6 := zulu
|
@ -0,0 +1,6 @@
|
|||||||
|
a := alpha
|
||||||
|
b := bravo
|
||||||
|
c := charlie
|
||||||
|
x := x-ray
|
||||||
|
y := yankee
|
||||||
|
z := zulu
|
@ -0,0 +1,463 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
#
|
||||||
|
# Copyright: (c) 2017, F5 Networks Inc.
|
||||||
|
# GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||||
|
|
||||||
|
from __future__ import (absolute_import, division, print_function)
|
||||||
|
__metaclass__ = type
|
||||||
|
|
||||||
|
import os
|
||||||
|
import json
|
||||||
|
import pytest
|
||||||
|
import sys
|
||||||
|
|
||||||
|
from nose.plugins.skip import SkipTest
|
||||||
|
if sys.version_info < (2, 7):
|
||||||
|
raise SkipTest("F5 Ansible modules require Python >= 2.7")
|
||||||
|
|
||||||
|
from ansible.compat.tests import unittest
|
||||||
|
from ansible.compat.tests.mock import Mock
|
||||||
|
from ansible.compat.tests.mock import patch
|
||||||
|
from ansible.module_utils.basic import AnsibleModule
|
||||||
|
|
||||||
|
try:
|
||||||
|
from library.modules.bigip_data_group import ModuleParameters
|
||||||
|
from library.modules.bigip_data_group import ModuleManager
|
||||||
|
from library.modules.bigip_data_group import ExternalManager
|
||||||
|
from library.modules.bigip_data_group import InternalManager
|
||||||
|
from library.modules.bigip_data_group import ArgumentSpec
|
||||||
|
from library.module_utils.network.f5.common import F5ModuleError
|
||||||
|
from library.module_utils.network.f5.common import iControlUnexpectedHTTPError
|
||||||
|
from test.unit.modules.utils import set_module_args
|
||||||
|
except ImportError:
|
||||||
|
try:
|
||||||
|
from ansible.modules.network.f5.bigip_data_group import ModuleParameters
|
||||||
|
from ansible.modules.network.f5.bigip_data_group import ModuleManager
|
||||||
|
from ansible.modules.network.f5.bigip_data_group import ExternalManager
|
||||||
|
from ansible.modules.network.f5.bigip_data_group import InternalManager
|
||||||
|
from ansible.modules.network.f5.bigip_data_group import ArgumentSpec
|
||||||
|
from ansible.module_utils.network.f5.common import F5ModuleError
|
||||||
|
from ansible.module_utils.network.f5.common import iControlUnexpectedHTTPError
|
||||||
|
from units.modules.utils import set_module_args
|
||||||
|
except ImportError:
|
||||||
|
raise SkipTest("F5 Ansible modules require the f5-sdk Python library")
|
||||||
|
|
||||||
|
fixture_path = os.path.join(os.path.dirname(__file__), 'fixtures')
|
||||||
|
fixture_data = {}
|
||||||
|
|
||||||
|
|
||||||
|
def load_fixture(name):
|
||||||
|
path = os.path.join(fixture_path, name)
|
||||||
|
|
||||||
|
if path in fixture_data:
|
||||||
|
return fixture_data[path]
|
||||||
|
|
||||||
|
with open(path) as f:
|
||||||
|
data = f.read()
|
||||||
|
|
||||||
|
try:
|
||||||
|
data = json.loads(data)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
fixture_data[path] = data
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
class TestParameters(unittest.TestCase):
|
||||||
|
def test_module_parameters(self):
|
||||||
|
args = dict(
|
||||||
|
name='foo',
|
||||||
|
type='address',
|
||||||
|
delete_data_group_file=False,
|
||||||
|
internal=False,
|
||||||
|
records=[
|
||||||
|
dict(
|
||||||
|
key='10.10.10.10/32',
|
||||||
|
value='bar'
|
||||||
|
)
|
||||||
|
],
|
||||||
|
separator=':=',
|
||||||
|
state='present',
|
||||||
|
partition='Common'
|
||||||
|
)
|
||||||
|
|
||||||
|
p = ModuleParameters(params=args)
|
||||||
|
assert p.name == 'foo'
|
||||||
|
assert p.type == 'ip'
|
||||||
|
assert p.delete_data_group_file is False
|
||||||
|
assert len(p.records) == 1
|
||||||
|
assert 'data' in p.records[0]
|
||||||
|
assert 'name' in p.records[0]
|
||||||
|
assert p.records[0]['data'] == 'bar'
|
||||||
|
assert p.records[0]['name'] == '10.10.10.10/32'
|
||||||
|
assert p.separator == ':='
|
||||||
|
assert p.state == 'present'
|
||||||
|
assert p.partition == 'Common'
|
||||||
|
|
||||||
|
|
||||||
|
@patch('ansible.module_utils.f5_utils.AnsibleF5Client._get_mgmt_root',
|
||||||
|
return_value=True)
|
||||||
|
class TestManager(unittest.TestCase):
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
self.spec = ArgumentSpec()
|
||||||
|
|
||||||
|
def test_create_external_datagroup_type_string(self, *args):
|
||||||
|
set_module_args(dict(
|
||||||
|
name='foo',
|
||||||
|
delete_data_group_file=False,
|
||||||
|
internal=False,
|
||||||
|
records_src="{0}/data-group-string.txt".format(fixture_path),
|
||||||
|
separator=':=',
|
||||||
|
state='present',
|
||||||
|
partition='Common',
|
||||||
|
server='localhost',
|
||||||
|
password='password',
|
||||||
|
user='admin'
|
||||||
|
))
|
||||||
|
|
||||||
|
module = AnsibleModule(
|
||||||
|
argument_spec=self.spec.argument_spec,
|
||||||
|
supports_check_mode=self.spec.supports_check_mode,
|
||||||
|
mutually_exclusive=self.spec.mutually_exclusive,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Override methods in the specific type of manager
|
||||||
|
mm1 = ExternalManager(module=module, params=module.params)
|
||||||
|
mm1.exists = Mock(side_effect=[False, True])
|
||||||
|
mm1.create_on_device = Mock(return_value=True)
|
||||||
|
|
||||||
|
# Override methods to force specific logic in the module to happen
|
||||||
|
mm0 = ModuleManager(module=module)
|
||||||
|
mm0.get_manager = Mock(return_value=mm1)
|
||||||
|
|
||||||
|
results = mm0.exec_module()
|
||||||
|
|
||||||
|
assert results['changed'] is True
|
||||||
|
|
||||||
|
def test_create_external_incorrect_address_data(self, *args):
|
||||||
|
set_module_args(dict(
|
||||||
|
name='foo',
|
||||||
|
delete_data_group_file=False,
|
||||||
|
internal=False,
|
||||||
|
type='address',
|
||||||
|
records_src="{0}/data-group-string.txt".format(fixture_path),
|
||||||
|
separator=':=',
|
||||||
|
state='present',
|
||||||
|
partition='Common',
|
||||||
|
server='localhost',
|
||||||
|
password='password',
|
||||||
|
user='admin'
|
||||||
|
))
|
||||||
|
|
||||||
|
module = AnsibleModule(
|
||||||
|
argument_spec=self.spec.argument_spec,
|
||||||
|
supports_check_mode=self.spec.supports_check_mode,
|
||||||
|
mutually_exclusive=self.spec.mutually_exclusive,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Override methods in the specific type of manager
|
||||||
|
mm1 = ExternalManager(module=module, params=module.params)
|
||||||
|
mm1.exists = Mock(side_effect=[False, True])
|
||||||
|
mm1.create_on_device = Mock(return_value=True)
|
||||||
|
|
||||||
|
# Override methods to force specific logic in the module to happen
|
||||||
|
mm0 = ModuleManager(module=module)
|
||||||
|
mm0.get_manager = Mock(return_value=mm1)
|
||||||
|
|
||||||
|
with pytest.raises(F5ModuleError) as ex:
|
||||||
|
mm0.exec_module()
|
||||||
|
|
||||||
|
assert "When specifying an 'address' type, the value to the left of the separator must be an IP." == str(ex.value)
|
||||||
|
|
||||||
|
def test_create_external_incorrect_integer_data(self, *args):
|
||||||
|
set_module_args(dict(
|
||||||
|
name='foo',
|
||||||
|
delete_data_group_file=False,
|
||||||
|
internal=False,
|
||||||
|
type='integer',
|
||||||
|
records_src="{0}/data-group-string.txt".format(fixture_path),
|
||||||
|
separator=':=',
|
||||||
|
state='present',
|
||||||
|
partition='Common',
|
||||||
|
server='localhost',
|
||||||
|
password='password',
|
||||||
|
user='admin'
|
||||||
|
))
|
||||||
|
|
||||||
|
module = AnsibleModule(
|
||||||
|
argument_spec=self.spec.argument_spec,
|
||||||
|
supports_check_mode=self.spec.supports_check_mode,
|
||||||
|
mutually_exclusive=self.spec.mutually_exclusive,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Override methods in the specific type of manager
|
||||||
|
mm1 = ExternalManager(module=module, params=module.params)
|
||||||
|
mm1.exists = Mock(side_effect=[False, True])
|
||||||
|
mm1.create_on_device = Mock(return_value=True)
|
||||||
|
|
||||||
|
# Override methods to force specific logic in the module to happen
|
||||||
|
mm0 = ModuleManager(module=module)
|
||||||
|
mm0.get_manager = Mock(return_value=mm1)
|
||||||
|
|
||||||
|
with pytest.raises(F5ModuleError) as ex:
|
||||||
|
mm0.exec_module()
|
||||||
|
|
||||||
|
assert "When specifying an 'integer' type, the value to the left of the separator must be a number." == str(ex.value)
|
||||||
|
|
||||||
|
def test_remove_data_group_keep_file(self, *args):
|
||||||
|
set_module_args(dict(
|
||||||
|
name='foo',
|
||||||
|
delete_data_group_file=False,
|
||||||
|
internal=False,
|
||||||
|
state='absent',
|
||||||
|
partition='Common',
|
||||||
|
server='localhost',
|
||||||
|
password='password',
|
||||||
|
user='admin'
|
||||||
|
))
|
||||||
|
|
||||||
|
module = AnsibleModule(
|
||||||
|
argument_spec=self.spec.argument_spec,
|
||||||
|
supports_check_mode=self.spec.supports_check_mode,
|
||||||
|
mutually_exclusive=self.spec.mutually_exclusive,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Override methods in the specific type of manager
|
||||||
|
mm1 = ExternalManager(module=module, params=module.params)
|
||||||
|
mm1.exists = Mock(side_effect=[True, False])
|
||||||
|
mm1.remove_from_device = Mock(return_value=True)
|
||||||
|
mm1.external_file_exists = Mock(return_value=True)
|
||||||
|
|
||||||
|
# Override methods to force specific logic in the module to happen
|
||||||
|
mm0 = ModuleManager(module=module)
|
||||||
|
mm0.get_manager = Mock(return_value=mm1)
|
||||||
|
|
||||||
|
results = mm0.exec_module()
|
||||||
|
|
||||||
|
assert results['changed'] is True
|
||||||
|
|
||||||
|
def test_remove_data_group_remove_file(self, *args):
|
||||||
|
set_module_args(dict(
|
||||||
|
name='foo',
|
||||||
|
delete_data_group_file=True,
|
||||||
|
internal=False,
|
||||||
|
state='absent',
|
||||||
|
partition='Common',
|
||||||
|
server='localhost',
|
||||||
|
password='password',
|
||||||
|
user='admin'
|
||||||
|
))
|
||||||
|
|
||||||
|
module = AnsibleModule(
|
||||||
|
argument_spec=self.spec.argument_spec,
|
||||||
|
supports_check_mode=self.spec.supports_check_mode,
|
||||||
|
mutually_exclusive=self.spec.mutually_exclusive,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Override methods in the specific type of manager
|
||||||
|
mm1 = ExternalManager(module=module, params=module.params)
|
||||||
|
mm1.exists = Mock(side_effect=[True, False])
|
||||||
|
mm1.remove_from_device = Mock(return_value=True)
|
||||||
|
mm1.external_file_exists = Mock(return_value=True)
|
||||||
|
mm1.remove_data_group_file_from_device = Mock(return_value=True)
|
||||||
|
|
||||||
|
# Override methods to force specific logic in the module to happen
|
||||||
|
mm0 = ModuleManager(module=module)
|
||||||
|
mm0.get_manager = Mock(return_value=mm1)
|
||||||
|
|
||||||
|
results = mm0.exec_module()
|
||||||
|
|
||||||
|
assert results['changed'] is True
|
||||||
|
|
||||||
|
def test_create_internal_datagroup_type_string(self, *args):
|
||||||
|
set_module_args(dict(
|
||||||
|
name='foo',
|
||||||
|
delete_data_group_file=False,
|
||||||
|
internal=True,
|
||||||
|
records_src="{0}/data-group-string.txt".format(fixture_path),
|
||||||
|
separator=':=',
|
||||||
|
state='present',
|
||||||
|
partition='Common',
|
||||||
|
server='localhost',
|
||||||
|
password='password',
|
||||||
|
user='admin'
|
||||||
|
))
|
||||||
|
|
||||||
|
module = AnsibleModule(
|
||||||
|
argument_spec=self.spec.argument_spec,
|
||||||
|
supports_check_mode=self.spec.supports_check_mode,
|
||||||
|
mutually_exclusive=self.spec.mutually_exclusive,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Override methods in the specific type of manager
|
||||||
|
mm1 = InternalManager(module=module, params=module.params)
|
||||||
|
mm1.exists = Mock(side_effect=[False, True])
|
||||||
|
mm1.create_on_device = Mock(return_value=True)
|
||||||
|
|
||||||
|
# Override methods to force specific logic in the module to happen
|
||||||
|
mm0 = ModuleManager(module=module)
|
||||||
|
mm0.get_manager = Mock(return_value=mm1)
|
||||||
|
|
||||||
|
results = mm0.exec_module()
|
||||||
|
|
||||||
|
assert results['changed'] is True
|
||||||
|
|
||||||
|
def test_create_internal_incorrect_integer_data(self, *args):
|
||||||
|
set_module_args(dict(
|
||||||
|
name='foo',
|
||||||
|
delete_data_group_file=False,
|
||||||
|
internal=True,
|
||||||
|
type='integer',
|
||||||
|
records_src="{0}/data-group-string.txt".format(fixture_path),
|
||||||
|
separator=':=',
|
||||||
|
state='present',
|
||||||
|
partition='Common',
|
||||||
|
server='localhost',
|
||||||
|
password='password',
|
||||||
|
user='admin'
|
||||||
|
))
|
||||||
|
|
||||||
|
module = AnsibleModule(
|
||||||
|
argument_spec=self.spec.argument_spec,
|
||||||
|
supports_check_mode=self.spec.supports_check_mode,
|
||||||
|
mutually_exclusive=self.spec.mutually_exclusive,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Override methods in the specific type of manager
|
||||||
|
mm1 = InternalManager(module=module, params=module.params)
|
||||||
|
mm1.exists = Mock(side_effect=[False, True])
|
||||||
|
mm1.create_on_device = Mock(return_value=True)
|
||||||
|
|
||||||
|
# Override methods to force specific logic in the module to happen
|
||||||
|
mm0 = ModuleManager(module=module)
|
||||||
|
mm0.get_manager = Mock(return_value=mm1)
|
||||||
|
|
||||||
|
with pytest.raises(F5ModuleError) as ex:
|
||||||
|
mm0.exec_module()
|
||||||
|
|
||||||
|
assert "When specifying an 'integer' type, the value to the left of the separator must be a number." == str(ex.value)
|
||||||
|
|
||||||
|
def test_create_internal_datagroup_type_integer(self, *args):
|
||||||
|
set_module_args(dict(
|
||||||
|
name='foo',
|
||||||
|
delete_data_group_file=False,
|
||||||
|
internal=True,
|
||||||
|
type='integer',
|
||||||
|
records_src="{0}/data-group-integer.txt".format(fixture_path),
|
||||||
|
separator=':=',
|
||||||
|
state='present',
|
||||||
|
partition='Common',
|
||||||
|
server='localhost',
|
||||||
|
password='password',
|
||||||
|
user='admin'
|
||||||
|
))
|
||||||
|
|
||||||
|
module = AnsibleModule(
|
||||||
|
argument_spec=self.spec.argument_spec,
|
||||||
|
supports_check_mode=self.spec.supports_check_mode,
|
||||||
|
mutually_exclusive=self.spec.mutually_exclusive,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Override methods in the specific type of manager
|
||||||
|
mm1 = InternalManager(module=module, params=module.params)
|
||||||
|
mm1.exists = Mock(side_effect=[False, True])
|
||||||
|
mm1.create_on_device = Mock(return_value=True)
|
||||||
|
|
||||||
|
# Override methods to force specific logic in the module to happen
|
||||||
|
mm0 = ModuleManager(module=module)
|
||||||
|
mm0.get_manager = Mock(return_value=mm1)
|
||||||
|
|
||||||
|
results = mm0.exec_module()
|
||||||
|
|
||||||
|
assert results['changed'] is True
|
||||||
|
|
||||||
|
def test_create_internal_datagroup_type_address(self, *args):
|
||||||
|
set_module_args(dict(
|
||||||
|
name='foo',
|
||||||
|
delete_data_group_file=False,
|
||||||
|
internal=True,
|
||||||
|
type='address',
|
||||||
|
records_src="{0}/data-group-address.txt".format(fixture_path),
|
||||||
|
separator=':=',
|
||||||
|
state='present',
|
||||||
|
partition='Common',
|
||||||
|
server='localhost',
|
||||||
|
password='password',
|
||||||
|
user='admin'
|
||||||
|
))
|
||||||
|
|
||||||
|
module = AnsibleModule(
|
||||||
|
argument_spec=self.spec.argument_spec,
|
||||||
|
supports_check_mode=self.spec.supports_check_mode,
|
||||||
|
mutually_exclusive=self.spec.mutually_exclusive,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Override methods in the specific type of manager
|
||||||
|
mm1 = InternalManager(module=module, params=module.params)
|
||||||
|
mm1.exists = Mock(side_effect=[False, True])
|
||||||
|
mm1.create_on_device = Mock(return_value=True)
|
||||||
|
|
||||||
|
# Override methods to force specific logic in the module to happen
|
||||||
|
mm0 = ModuleManager(module=module)
|
||||||
|
mm0.get_manager = Mock(return_value=mm1)
|
||||||
|
|
||||||
|
results = mm0.exec_module()
|
||||||
|
|
||||||
|
assert results['changed'] is True
|
||||||
|
|
||||||
|
def test_create_internal_datagroup_type_address_list(self, *args):
|
||||||
|
set_module_args(dict(
|
||||||
|
name='foo',
|
||||||
|
delete_data_group_file=False,
|
||||||
|
internal=True,
|
||||||
|
type='address',
|
||||||
|
records=[
|
||||||
|
dict(
|
||||||
|
key='10.0.0.0/8',
|
||||||
|
value='Network1'
|
||||||
|
),
|
||||||
|
dict(
|
||||||
|
key='172.16.0.0/12',
|
||||||
|
value='Network2'
|
||||||
|
),
|
||||||
|
dict(
|
||||||
|
key='192.168.20.1/16',
|
||||||
|
value='Network3'
|
||||||
|
),
|
||||||
|
dict(
|
||||||
|
key='192.168.20.1',
|
||||||
|
value='Host1'
|
||||||
|
),
|
||||||
|
dict(
|
||||||
|
key='172.16.1.1',
|
||||||
|
value='Host2'
|
||||||
|
)
|
||||||
|
],
|
||||||
|
separator=':=',
|
||||||
|
state='present',
|
||||||
|
partition='Common',
|
||||||
|
server='localhost',
|
||||||
|
password='password',
|
||||||
|
user='admin'
|
||||||
|
))
|
||||||
|
|
||||||
|
module = AnsibleModule(
|
||||||
|
argument_spec=self.spec.argument_spec,
|
||||||
|
supports_check_mode=self.spec.supports_check_mode,
|
||||||
|
mutually_exclusive=self.spec.mutually_exclusive,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Override methods in the specific type of manager
|
||||||
|
mm1 = InternalManager(module=module, params=module.params)
|
||||||
|
mm1.exists = Mock(side_effect=[False, True])
|
||||||
|
mm1.create_on_device = Mock(return_value=True)
|
||||||
|
|
||||||
|
# Override methods to force specific logic in the module to happen
|
||||||
|
mm0 = ModuleManager(module=module)
|
||||||
|
mm0.get_manager = Mock(return_value=mm1)
|
||||||
|
|
||||||
|
results = mm0.exec_module()
|
||||||
|
|
||||||
|
assert results['changed'] is True
|
Loading…
Reference in New Issue