Removes deprecated "append" param from snat pool (#32953)

This param was deprecated in 2.4 and slated for removal in 2.5. This
patch removes it.
pull/32881/head
Tim Rupp 7 years ago committed by GitHub
parent aeb896375d
commit 3f3c526026
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -1,47 +1,46 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2017 F5 Networks Inc.
# Copyright (c) 2016 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
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
DOCUMENTATION = r'''
---
module: bigip_snat_pool
short_description: Manage SNAT pools on a BIG-IP.
short_description: Manage SNAT pools on a BIG-IP
description:
- Manage SNAT pools on a BIG-IP.
version_added: "2.3"
options:
append:
description:
- When C(yes), will only add members to the SNAT pool. When C(no), will
replace the existing member list with the provided member list.
choices:
- yes
- no
default: no
members:
description:
- List of members to put in the SNAT pool. When a C(state) of present is
provided, this parameter is required. Otherwise, it is optional.
required: false
default: None
aliases: ['member']
aliases:
- member
name:
description: The name of the SNAT pool.
required: True
state:
description:
- Whether the SNAT pool should exist or not.
required: false
default: present
choices:
- present
- absent
partition:
description:
- Device partition to manage resources on.
default: 'Common'
version_added: 2.5
notes:
- Requires the f5-sdk Python package on the host. This is as easy as
pip install f5-sdk
@ -54,66 +53,57 @@ author:
- Tim Rupp (@caphrim007)
'''
EXAMPLES = '''
EXAMPLES = r'''
- name: Add the SNAT pool 'my-snat-pool'
bigip_snat_pool:
server: "lb.mydomain.com"
user: "admin"
password: "secret"
name: "my-snat-pool"
state: "present"
members:
- 10.10.10.10
- 20.20.20.20
server: lb.mydomain.com
user: admin
password: secret
name: my-snat-pool
state: present
members:
- 10.10.10.10
- 20.20.20.20
delegate_to: localhost
- name: Change the SNAT pool's members to a single member
bigip_snat_pool:
server: "lb.mydomain.com"
user: "admin"
password: "secret"
name: "my-snat-pool"
state: "present"
member: "30.30.30.30"
delegate_to: localhost
- name: Append a new list of members to the existing pool
bigip_snat_pool:
server: "lb.mydomain.com"
user: "admin"
password: "secret"
name: "my-snat-pool"
state: "present"
members:
- 10.10.10.10
- 20.20.20.20
server: lb.mydomain.com
user: admin
password: secret
name: my-snat-pool
state: present
member: 30.30.30.30
delegate_to: localhost
- name: Remove the SNAT pool 'my-snat-pool'
bigip_snat_pool:
server: "lb.mydomain.com"
user: "admin"
password: "secret"
name: "johnd"
state: "absent"
server: lb.mydomain.com
user: admin
password: secret
name: johnd
state: absent
delegate_to: localhost
'''
RETURN = '''
RETURN = r'''
members:
description:
- List of members that are part of the SNAT pool.
returned: changed and success
type: list
sample: "['10.10.10.10']"
description:
- List of members that are part of the SNAT pool.
returned: changed and success
type: list
sample: "['10.10.10.10']"
'''
try:
from f5.bigip.contexts import TransactionContextManager
from f5.bigip import ManagementRoot
from icontrol.session import iControlUnexpectedHTTPError
import os
from ansible.module_utils.f5_utils import AnsibleF5Client
from ansible.module_utils.f5_utils import AnsibleF5Parameters
from ansible.module_utils.f5_utils import HAS_F5SDK
from ansible.module_utils.f5_utils import F5ModuleError
HAS_F5SDK = True
try:
from ansible.module_utils.f5_utils import iControlUnexpectedHTTPError
except ImportError:
HAS_F5SDK = False
@ -123,259 +113,259 @@ try:
except ImportError:
HAS_NETADDR = False
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.ec2 import camel_dict_to_snake_dict
from ansible.module_utils.f5_utils import F5ModuleError, f5_argument_spec
class Parameters(AnsibleF5Parameters):
api_map = {}
class BigIpSnatPoolManager(object):
def __init__(self, *args, **kwargs):
self.changed_params = dict()
self.params = kwargs
self.api = None
updatables = [
'members'
]
def apply_changes(self):
result = dict()
returnables = [
'members'
]
changed = self.apply_to_running_config()
if changed:
self.save_running_config()
api_attributes = [
'members'
]
result.update(**self.changed_params)
result.update(dict(changed=changed))
def to_return(self):
result = {}
for returnable in self.returnables:
result[returnable] = getattr(self, returnable)
result = self._filter_params(result)
return result
def apply_to_running_config(self):
try:
self.api = self.connect_to_bigip(**self.params)
if self.params['state'] == "present":
return self.present()
elif self.params['state'] == "absent":
return self.absent()
except iControlUnexpectedHTTPError as e:
raise F5ModuleError(str(e))
def api_params(self):
result = {}
for api_attribute in self.api_attributes:
if self.api_map is not None and api_attribute in self.api_map:
result[api_attribute] = getattr(self, self.api_map[api_attribute])
else:
result[api_attribute] = getattr(self, api_attribute)
result = self._filter_params(result)
return result
@property
def members(self):
if self._values['members'] is None:
return None
result = set()
for member in self._values['members']:
member = self._clear_member_prefix(member)
address = self._format_member_address(member)
result.update([address])
return list(result)
def save_running_config(self):
self.api.tm.sys.config.exec_cmd('save')
def _clear_member_prefix(self, member):
result = os.path.basename(member)
return result
def present(self):
if self.params['members'] is None:
def _format_member_address(self, member):
try:
address = str(IPAddress(member))
address = '/{0}/{1}'.format(self.partition, address)
return address
except (AddrFormatError, ValueError):
raise F5ModuleError(
"The members parameter must be specified"
'The provided member address is not a valid IP address'
)
if self.snat_pool_exists():
return self.update_snat_pool()
else:
return self.ensure_snat_pool_is_present()
def absent(self):
changed = False
if self.snat_pool_exists():
changed = self.ensure_snat_pool_is_absent()
return changed
def connect_to_bigip(self, **kwargs):
return ManagementRoot(kwargs['server'],
kwargs['user'],
kwargs['password'],
port=kwargs['server_port'])
class Difference(object):
def __init__(self, want, have=None):
self.want = want
self.have = have
def read_snat_pool_information(self):
pool = self.load_snat_pool()
return self.format_snat_pool_information(pool)
def compare(self, param):
try:
result = getattr(self, param)
return result
except AttributeError:
return self.__default(param)
@property
def members(self):
if self.want.members is None:
return None
if set(self.want.members) == set(self.have.members):
return None
result = list(set(self.want.members))
return result
def format_snat_pool_information(self, pool):
"""Ensure that the pool information is in a standard format
def __default(self, param):
attr1 = getattr(self.want, param)
try:
attr2 = getattr(self.have, param)
if attr1 != attr2:
return attr1
except AttributeError:
return attr1
class ModuleManager(object):
def __init__(self, client):
self.client = client
self.have = None
self.want = Parameters(self.client.module.params)
self.changes = Parameters()
def _set_changed_options(self):
changed = {}
for key in Parameters.returnables:
if getattr(self.want, key) is not None:
changed[key] = getattr(self.want, key)
if changed:
self.changes = Parameters(changed)
def _update_changed_options(self):
diff = Difference(self.want, self.have)
updatables = Parameters.updatables
changed = dict()
for k in updatables:
change = diff.compare(k)
if change is None:
continue
else:
changed[k] = change
if changed:
self.changes = Parameters(changed)
return True
return False
The SDK provides information back in a format that may change with
the version of BIG-IP being worked with. Therefore, we need to make
sure that the data is formatted in a way that our module expects it.
def exec_module(self):
changed = False
result = dict()
state = self.want.state
Additionally, this takes care of minor variations between Python 2
and Python 3.
try:
if state == "present":
changed = self.present()
elif state == "absent":
changed = self.absent()
except iControlUnexpectedHTTPError as e:
raise F5ModuleError(str(e))
:param pool:
:return:
"""
result = dict()
result['name'] = str(pool.name)
if hasattr(pool, 'members'):
result['members'] = self.format_current_members(pool)
changes = self.changes.to_return()
result.update(**changes)
result.update(dict(changed=changed))
self._announce_deprecations()
return result
def format_current_members(self, pool):
result = set()
partition_prefix = "/{0}/".format(self.params['partition'])
def _announce_deprecations(self):
warnings = []
if self.want:
warnings += self.want._values.get('__warnings', [])
if self.have:
warnings += self.have._values.get('__warnings', [])
for warning in warnings:
self.client.module.deprecate(
msg=warning['msg'],
version=warning['version']
)
for member in pool.members:
member = str(member.replace(partition_prefix, ''))
result.update([member])
return list(result)
def present(self):
if self.exists():
return self.update()
else:
return self.create()
def load_snat_pool(self):
return self.api.tm.ltm.snatpools.snatpool.load(
name=self.params['name'],
partition=self.params['partition']
)
def absent(self):
changed = False
if self.exists():
changed = self.remove()
return changed
def snat_pool_exists(self):
return self.api.tm.ltm.snatpools.snatpool.exists(
name=self.params['name'],
partition=self.params['partition']
def read_current_from_device(self):
resource = self.client.api.tm.ltm.snatpools.snatpool.load(
name=self.want.name,
partition=self.want.partition
)
result = resource.attrs
return Parameters(result)
def update_snat_pool(self):
params = self.get_changed_parameters()
if params:
self.changed_params = camel_dict_to_snake_dict(params)
if self.params['check_mode']:
return True
else:
return False
params['name'] = self.params['name']
params['partition'] = self.params['partition']
self.update_snat_pool_on_device(params)
return True
def update_snat_pool_on_device(self, params):
tx = self.api.tm.transactions.transaction
with TransactionContextManager(tx) as api:
r = api.tm.ltm.snatpools.snatpool.load(
name=self.params['name'],
partition=self.params['partition']
)
r.modify(**params)
def get_changed_parameters(self):
result = dict()
current = self.read_snat_pool_information()
if self.are_members_changed(current):
result['members'] = self.get_new_member_list(current['members'])
def exists(self):
result = self.client.api.tm.ltm.snatpools.snatpool.exists(
name=self.want.name,
partition=self.want.partition
)
return result
def are_members_changed(self, current):
if self.params['members'] is None:
return False
if 'members' not in current:
return True
if set(self.params['members']) == set(current['members']):
return False
if not self.params['append']:
def should_update(self):
result = self._update_changed_options()
if result:
return True
return False
# Checking to see if the supplied list is a subset of the current
# list is only relevant if the `append` parameter is provided.
new_members = set(self.params['members'])
current_members = set(current['members'])
if new_members.issubset(current_members):
def update(self):
self.have = self.read_current_from_device()
if not self.should_update():
return False
else:
if self.client.check_mode:
return True
self.update_on_device()
return True
def get_new_member_list(self, current_members):
result = set()
def update_on_device(self):
params = self.changes.api_params()
if self.params['append']:
result.update(set(current_members))
result.update(set(self.params['members']))
else:
result.update(set(self.params['members']))
return list(result)
resource = self.client.api.tm.ltm.snatpools.snatpool.load(
name=self.want.name,
partition=self.want.partition
)
resource.modify(**params)
def ensure_snat_pool_is_present(self):
params = self.get_snat_pool_creation_parameters()
self.changed_params = camel_dict_to_snake_dict(params)
if self.params['check_mode']:
return True
self.create_snat_pool_on_device(params)
if self.snat_pool_exists():
def create(self):
self._set_changed_options()
if self.client.check_mode:
return True
else:
self.create_on_device()
if not self.exists():
raise F5ModuleError("Failed to create the SNAT pool")
return True
def get_snat_pool_creation_parameters(self):
members = self.get_formatted_members_list()
return dict(
name=self.params['name'],
partition=self.params['partition'],
members=members
def create_on_device(self):
params = self.want.api_params()
self.client.api.tm.ltm.snatpools.snatpool.create(
name=self.want.name,
partition=self.want.partition,
**params
)
def get_formatted_members_list(self):
result = set()
try:
for ip in self.params['members']:
address = str(IPAddress(ip))
result.update([address])
return list(result)
except AddrFormatError:
raise F5ModuleError(
'The provided member address is not a valid IP address'
)
def create_snat_pool_on_device(self, params):
tx = self.api.tm.transactions.transaction
with TransactionContextManager(tx) as api:
api.tm.ltm.snatpools.snatpool.create(**params)
def ensure_snat_pool_is_absent(self):
if self.params['check_mode']:
def remove(self):
if self.client.check_mode:
return True
self.delete_snat_pool_from_device()
if self.snat_pool_exists():
self.remove_from_device()
if self.exists():
raise F5ModuleError("Failed to delete the SNAT pool")
return True
def delete_snat_pool_from_device(self):
tx = self.api.tm.transactions.transaction
with TransactionContextManager(tx) as api:
pool = api.tm.ltm.snatpools.snatpool.load(
name=self.params['name'],
partition=self.params['partition']
)
pool.delete()
def remove_from_device(self):
resource = self.client.api.tm.ltm.snatpools.snatpool.load(
name=self.want.name,
partition=self.want.partition
)
resource.delete()
class BigIpSnatPoolModuleConfig(object):
class ArgumentSpec(object):
def __init__(self):
self.argument_spec = dict()
self.meta_args = dict()
self.supports_check_mode = True
self.states = ['absent', 'present']
self.initialize_meta_args()
self.initialize_argument_spec()
def initialize_meta_args(self):
args = dict(
append=dict(
default=False,
type='bool',
),
self.argument_spec = dict(
name=dict(required=True),
members=dict(
required=False,
default=None,
type='list',
aliases=['member']
),
state=dict(
default='present',
choices=self.states
choices=['absent', 'present']
)
)
self.meta_args = args
def initialize_argument_spec(self):
self.argument_spec = f5_argument_spec()
self.argument_spec.update(self.meta_args)
def create(self):
return AnsibleModule(
argument_spec=self.argument_spec,
supports_check_mode=self.supports_check_mode
)
self.required_if = [
['state', 'present', ['members']]
]
self.f5_product_name = 'bigip'
def main():
@ -385,19 +375,21 @@ def main():
if not HAS_NETADDR:
raise F5ModuleError("The python netaddr module is required")
config = BigIpSnatPoolModuleConfig()
module = config.create()
spec = ArgumentSpec()
try:
obj = BigIpSnatPoolManager(
check_mode=module.check_mode, **module.params
)
result = obj.apply_changes()
client = AnsibleF5Client(
argument_spec=spec.argument_spec,
supports_check_mode=spec.supports_check_mode,
f5_product_name=spec.f5_product_name,
required_if=spec.required_if
)
module.exit_json(**result)
try:
mm = ModuleManager(client)
results = mm.exec_module()
client.module.exit_json(**results)
except F5ModuleError as e:
module.fail_json(msg=str(e))
client.module.fail_json(msg=str(e))
if __name__ == '__main__':
main()

@ -0,0 +1,20 @@
{
"kind": "tm:ltm:snatpool:snatpoolstate",
"name": "asdasd",
"partition": "Common",
"fullPath": "/Common/asdasd",
"generation": 40,
"selfLink": "https://localhost/mgmt/tm/ltm/snatpool/~Common~asdasd?ver=12.1.2",
"members": [
"/Common/1.1.1.1",
"/Common/2.2.2.2"
],
"membersReference": [
{
"link": "https://localhost/mgmt/tm/ltm/snat-translation/~Common~1.1.1.1?ver=12.1.2"
},
{
"link": "https://localhost/mgmt/tm/ltm/snat-translation/~Common~2.2.2.2?ver=12.1.2"
}
]
}

@ -0,0 +1,180 @@
# -*- 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 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 patch, Mock
from ansible.module_utils import basic
from ansible.module_utils._text import to_bytes
from ansible.module_utils.f5_utils import AnsibleF5Client
try:
from library.bigip_snat_pool import Parameters
from library.bigip_snat_pool import ModuleManager
from library.bigip_snat_pool import ArgumentSpec
from ansible.module_utils.f5_utils import iControlUnexpectedHTTPError
except ImportError:
try:
from ansible.modules.network.f5.bigip_snat_pool import Parameters
from ansible.modules.network.f5.bigip_snat_pool import ModuleManager
from ansible.modules.network.f5.bigip_snat_pool import ArgumentSpec
from ansible.module_utils.f5_utils import iControlUnexpectedHTTPError
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 set_module_args(args):
args = json.dumps({'ANSIBLE_MODULE_ARGS': args})
basic._ANSIBLE_ARGS = to_bytes(args)
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='my-snat-pool',
state='present',
members=['10.10.10.10', '20.20.20.20'],
partition='Common'
)
p = Parameters(args)
assert p.name == 'my-snat-pool'
assert p.state == 'present'
assert len(p.members) == 2
assert '/Common/10.10.10.10' in p.members
assert '/Common/20.20.20.20' in p.members
def test_api_parameters(self):
args = dict(
members=['/Common/10.10.10.10', '/foo/20.20.20.20']
)
p = Parameters(args)
assert len(p.members) == 2
assert '/Common/10.10.10.10' in p.members
assert '/Common/20.20.20.20' in p.members
@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_snat_pool(self, *args):
set_module_args(dict(
name='my-snat-pool',
state='present',
members=['10.10.10.10', '20.20.20.20'],
password='passsword',
server='localhost',
user='admin'
))
client = AnsibleF5Client(
argument_spec=self.spec.argument_spec,
supports_check_mode=self.spec.supports_check_mode,
f5_product_name=self.spec.f5_product_name
)
mm = ModuleManager(client)
# Override methods to force specific logic in the module to happen
mm.exists = Mock(side_effect=[False, True])
mm.create_on_device = Mock(return_value=True)
results = mm.exec_module()
assert results['changed'] is True
assert len(results['members']) == 2
assert '/Common/10.10.10.10' in results['members']
assert '/Common/20.20.20.20' in results['members']
def test_create_snat_pool_idempotent(self, *args):
set_module_args(dict(
name='asdasd',
state='present',
members=['1.1.1.1', '2.2.2.2'],
password='passsword',
server='localhost',
user='admin'
))
current = Parameters(load_fixture('load_ltm_snatpool.json'))
client = AnsibleF5Client(
argument_spec=self.spec.argument_spec,
supports_check_mode=self.spec.supports_check_mode,
f5_product_name=self.spec.f5_product_name
)
mm = ModuleManager(client)
# Override methods to force specific logic in the module to happen
mm.exists = Mock(side_effect=[True, True])
mm.read_current_from_device = Mock(return_value=current)
results = mm.exec_module()
assert results['changed'] is False
def test_update_snat_pool(self, *args):
set_module_args(dict(
name='asdasd',
state='present',
members=['30.30.30.30'],
password='passsword',
server='localhost',
user='admin'
))
current = Parameters(load_fixture('load_ltm_snatpool.json'))
client = AnsibleF5Client(
argument_spec=self.spec.argument_spec,
supports_check_mode=self.spec.supports_check_mode,
f5_product_name=self.spec.f5_product_name
)
mm = ModuleManager(client)
# Override methods to force specific logic in the module to happen
mm.read_current_from_device = Mock(return_value=current)
mm.update_on_device = Mock(return_value=True)
mm.exists = Mock(return_value=True)
mm.create_on_device = Mock(return_value=True)
results = mm.exec_module()
assert results['changed'] is True
assert len(results['members']) == 1
assert '/Common/30.30.30.30' in results['members']
Loading…
Cancel
Save