Migrated to cisco.asa

pull/68298/head
Ansible Core Team 4 years ago committed by Matt Martz
parent 3f1cea89fb
commit ab5a3b4305

@ -1,173 +0,0 @@
# 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.
#
# (c) 2016 Red Hat Inc.
#
# 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.
#
from ansible.module_utils._text import to_text
from ansible.module_utils.basic import env_fallback
from ansible.module_utils.network.common.utils import to_list, EntityCollection
from ansible.module_utils.connection import exec_command
from ansible.module_utils.connection import Connection, ConnectionError
_DEVICE_CONFIGS = {}
_CONNECTION = None
asa_provider_spec = {
'host': dict(),
'port': dict(type='int'),
'username': dict(fallback=(env_fallback, ['ANSIBLE_NET_USERNAME'])),
'password': dict(fallback=(env_fallback, ['ANSIBLE_NET_PASSWORD']), no_log=True),
'ssh_keyfile': dict(fallback=(env_fallback, ['ANSIBLE_NET_SSH_KEYFILE']), type='path'),
'authorize': dict(fallback=(env_fallback, ['ANSIBLE_NET_AUTHORIZE']), type='bool'),
'auth_pass': dict(fallback=(env_fallback, ['ANSIBLE_NET_AUTH_PASS']), no_log=True),
'timeout': dict(type='int'),
'context': dict(),
'passwords': dict()
}
asa_argument_spec = {
'provider': dict(type='dict', options=asa_provider_spec),
}
asa_top_spec = {
'host': dict(removed_in_version=2.9),
'port': dict(removed_in_version=2.9, type='int'),
'username': dict(removed_in_version=2.9),
'password': dict(removed_in_version=2.9, no_log=True),
'ssh_keyfile': dict(removed_in_version=2.9, type='path'),
'authorize': dict(type='bool'),
'auth_pass': dict(removed_in_version=2.9, no_log=True),
'timeout': dict(removed_in_version=2.9, type='int'),
'context': dict(),
'passwords': dict()
}
asa_argument_spec.update(asa_top_spec)
command_spec = {
'command': dict(key=True),
'prompt': dict(),
'answer': dict()
}
def get_provider_argspec():
return asa_provider_spec
def check_args(module):
pass
def get_connection(module):
global _CONNECTION
if _CONNECTION:
return _CONNECTION
_CONNECTION = Connection(module._socket_path)
# Not all modules include the 'context' key.
context = module.params.get('context')
if context:
if context == 'system':
command = 'changeto system'
else:
command = 'changeto context %s' % context
_CONNECTION.get(command)
return _CONNECTION
def to_commands(module, commands):
if not isinstance(commands, list):
raise AssertionError('argument must be of type <list>')
transform = EntityCollection(module, command_spec)
commands = transform(commands)
for index, item in enumerate(commands):
if module.check_mode and not item['command'].startswith('show'):
module.warn('only show commands are supported when using check '
'mode, not executing `%s`' % item['command'])
return commands
def run_commands(module, commands, check_rc=True):
connection = get_connection(module)
commands = to_commands(module, to_list(commands))
responses = list()
for cmd in commands:
out = connection.get(**cmd)
responses.append(to_text(out, errors='surrogate_then_replace'))
return responses
def get_config(module, flags=None):
flags = [] if flags is None else flags
# Not all modules include the 'passwords' key.
passwords = module.params.get('passwords', False)
if passwords:
cmd = 'more system:running-config'
else:
cmd = 'show running-config '
cmd += ' '.join(flags)
cmd = cmd.strip()
try:
return _DEVICE_CONFIGS[cmd]
except KeyError:
conn = get_connection(module)
out = conn.get(cmd)
cfg = to_text(out, errors='surrogate_then_replace').strip()
_DEVICE_CONFIGS[cmd] = cfg
return cfg
def load_config(module, config):
try:
conn = get_connection(module)
conn.edit_config(config)
except ConnectionError as exc:
module.fail_json(msg=to_text(exc))
def get_defaults_flag(module):
rc, out, err = exec_command(module, 'show running-config ?')
out = to_text(out, errors='surrogate_then_replace')
commands = set()
for line in out.splitlines():
if line:
commands.add(line.strip().split()[0])
if 'all' in commands:
return 'all'
else:
return 'full'

@ -1,222 +0,0 @@
#!/usr/bin/python
#
# Copyright: Ansible Project
# 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 = """
---
module: asa_acl
version_added: "2.2"
author: "Patrick Ogenstad (@ogenstad)"
short_description: Manage access-lists on a Cisco ASA
description:
- This module allows you to work with access-lists on a Cisco ASA device.
extends_documentation_fragment: asa
options:
lines:
description:
- The ordered set of commands that should be configured in the
section. The commands must be the exact same commands as found
in the device running-config. Be sure to note the configuration
command syntax as some commands are automatically modified by the
device config parser.
required: true
aliases: [commands]
before:
description:
- The ordered set of commands to push on to the command stack if
a change needs to be made. This allows the playbook designer
the opportunity to perform configuration commands prior to pushing
any changes without affecting how the set of commands are matched
against the system.
after:
description:
- The ordered set of commands to append to the end of the command
stack if a changed needs to be made. Just like with I(before) this
allows the playbook designer to append a set of commands to be
executed after the command set.
match:
description:
- Instructs the module on the way to perform the matching of
the set of commands against the current device config. If
match is set to I(line), commands are matched line by line. If
match is set to I(strict), command lines are matched with respect
to position. Finally if match is set to I(exact), command lines
must be an equal match.
default: line
choices: ['line', 'strict', 'exact']
replace:
description:
- Instructs the module on the way to perform the configuration
on the device. If the replace argument is set to I(line) then
the modified lines are pushed to the device in configuration
mode. If the replace argument is set to I(block) then the entire
command block is pushed to the device in configuration mode if any
line is not correct.
default: line
choices: ['line', 'block']
force:
description:
- The force argument instructs the module to not consider the
current devices running-config. When set to true, this will
cause the module to push the contents of I(src) into the device
without first checking if already configured.
type: bool
default: 'no'
config:
description:
- The module, by default, will connect to the remote device and
retrieve the current running-config to use as a base for comparing
against the contents of source. There are times when it is not
desirable to have the task get the current running-config for
every task in a playbook. The I(config) argument allows the
implementer to pass in the configuration to use as the base
config for comparison.
"""
EXAMPLES = """
# Note: examples below use the following provider dict to handle
# transport and authentication to the node.
---
vars:
cli:
host: "{{ inventory_hostname }}"
username: cisco
password: cisco
transport: cli
authorize: yes
auth_pass: cisco
---
- asa_acl:
lines:
- access-list ACL-ANSIBLE extended permit tcp any any eq 82
- access-list ACL-ANSIBLE extended permit tcp any any eq www
- access-list ACL-ANSIBLE extended permit tcp any any eq 97
- access-list ACL-ANSIBLE extended permit tcp any any eq 98
- access-list ACL-ANSIBLE extended permit tcp any any eq 99
before: clear configure access-list ACL-ANSIBLE
match: strict
replace: block
provider: "{{ cli }}"
- asa_acl:
lines:
- access-list ACL-OUTSIDE extended permit tcp any any eq www
- access-list ACL-OUTSIDE extended permit tcp any any eq https
context: customer_a
provider: "{{ cli }}"
"""
RETURN = """
updates:
description: The set of commands that will be pushed to the remote device
returned: always
type: list
sample: ['access-list ACL-OUTSIDE extended permit tcp any any eq www']
"""
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.network.asa.asa import asa_argument_spec, check_args
from ansible.module_utils.network.asa.asa import get_config, load_config, run_commands
from ansible.module_utils.network.common.config import NetworkConfig, dumps
def get_acl_config(module, acl_name):
contents = module.params['config']
if not contents:
contents = get_config(module)
filtered_config = list()
for item in contents.split('\n'):
if item.startswith('access-list %s ' % acl_name):
filtered_config.append(item)
return NetworkConfig(indent=1, contents='\n'.join(filtered_config))
def parse_acl_name(module):
first_line = True
for line in module.params['lines']:
ace = line.split()
if ace[0] != 'access-list':
module.fail_json(msg='All lines/commands must begin with "access-list" %s is not permitted' % ace[0])
if len(ace) <= 1:
module.fail_json(msg='All lines/commands must contain the name of the access-list')
if first_line:
acl_name = ace[1]
else:
if acl_name != ace[1]:
module.fail_json(msg='All lines/commands must use the same access-list %s is not %s' % (ace[1], acl_name))
first_line = False
return acl_name
def main():
argument_spec = dict(
lines=dict(aliases=['commands'], required=True, type='list'),
before=dict(type='list'),
after=dict(type='list'),
match=dict(default='line', choices=['line', 'strict', 'exact']),
replace=dict(default='line', choices=['line', 'block']),
force=dict(default=False, type='bool'),
config=dict()
)
argument_spec.update(asa_argument_spec)
module = AnsibleModule(argument_spec=argument_spec,
supports_check_mode=True)
lines = module.params['lines']
result = {'changed': False}
if len(lines) > 0:
candidate = NetworkConfig(indent=1)
candidate.add(lines)
acl_name = parse_acl_name(module)
if not module.params['force']:
contents = get_acl_config(module, acl_name)
config = NetworkConfig(indent=1, contents=contents)
commands = candidate.difference(config)
commands = dumps(commands, 'commands').split('\n')
commands = [str(c) for c in commands if c]
else:
commands = str(candidate).split('\n')
if commands:
if module.params['before']:
commands[:0] = module.params['before']
if module.params['after']:
commands.extend(module.params['after'])
if not module.check_mode:
load_config(module, commands)
result['changed'] = True
result['updates'] = commands
module.exit_json(**result)
if __name__ == '__main__':
main()

@ -1,186 +0,0 @@
#!/usr/bin/python
#
# Copyright: Ansible Project
# 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 = """
---
module: asa_command
version_added: "2.2"
author: "Peter Sprygada (@privateip), Patrick Ogenstad (@ogenstad)"
short_description: Run arbitrary commands on Cisco ASA devices
description:
- Sends arbitrary commands to an ASA node and returns the results
read from the device. The C(asa_command) module includes an
argument that will cause the module to wait for a specific condition
before returning or timing out if the condition is not met.
extends_documentation_fragment: asa
options:
commands:
description:
- List of commands to send to the remote device over the
configured provider. The resulting output from the command
is returned. If the I(wait_for) argument is provided, the
module is not returned until the condition is satisfied or
the number of retires as expired.
required: true
wait_for:
description:
- List of conditions to evaluate against the output of the
command. The task will wait for each condition to be true
before moving forward. If the conditional is not true
within the configured number of retries, the task fails.
See examples.
aliases: ['waitfor']
match:
description:
- The I(match) argument is used in conjunction with the
I(wait_for) argument to specify the match policy. Valid
values are C(all) or C(any). If the value is set to C(all)
then all conditionals in the wait_for must be satisfied. If
the value is set to C(any) then only one of the values must be
satisfied.
default: all
choices: ['any', 'all']
retries:
description:
- Specifies the number of retries a command should by tried
before it is considered failed. The command is run on the
target device every retry and evaluated against the
I(wait_for) conditions.
default: 10
interval:
description:
- Configures the interval in seconds to wait between retries
of the command. If the command does not pass the specified
conditions, the interval indicates how long to wait before
trying the command again.
default: 1
"""
EXAMPLES = """
---
- name: "Show the ASA version"
asa_command:
commands:
- show version
- name: "Show ASA drops and memory"
asa_command:
commands:
- show asp drop
- show memory
- name: "Send repeat pings and wait for the result to pass 100%"
asa_command:
commands:
- ping 8.8.8.8 repeat 20 size 350
wait_for:
- result[0] contains 100
retries: 2
"""
RETURN = """
stdout:
description: the set of responses from the commands
returned: always
type: list
sample: ['...', '...']
stdout_lines:
description: The value of stdout split into a list
returned: always
type: list
sample: [['...', '...'], ['...'], ['...']]
failed_conditions:
description: the conditionals that failed
returned: failed
type: list
sample: ['...', '...']
"""
import time
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.network.asa.asa import asa_argument_spec, check_args
from ansible.module_utils.network.asa.asa import run_commands
from ansible.module_utils.network.common.parsing import Conditional
from ansible.module_utils.six import string_types
def to_lines(stdout):
for item in stdout:
if isinstance(item, string_types):
item = str(item).split('\n')
yield item
def main():
spec = dict(
# { command: <str>, prompt: <str>, response: <str> }
commands=dict(type='list', required=True),
wait_for=dict(type='list', aliases=['waitfor']),
match=dict(default='all', choices=['all', 'any']),
retries=dict(default=10, type='int'),
interval=dict(default=1, type='int')
)
spec.update(asa_argument_spec)
module = AnsibleModule(argument_spec=spec, supports_check_mode=True)
check_args(module)
result = {'changed': False}
wait_for = module.params['wait_for'] or list()
conditionals = [Conditional(c) for c in wait_for]
commands = module.params['commands']
retries = module.params['retries']
interval = module.params['interval']
match = module.params['match']
while retries > 0:
responses = run_commands(module, commands)
for item in list(conditionals):
if item(responses):
if match == 'any':
conditionals = list()
break
conditionals.remove(item)
if not conditionals:
break
time.sleep(interval)
retries -= 1
if conditionals:
failed_conditions = [item.raw for item in conditionals]
msg = 'One or more conditional statements have not be satisfied'
module.fail_json(msg=msg, failed_conditions=failed_conditions)
result.update({
'changed': False,
'stdout': responses,
'stdout_lines': list(to_lines(responses))
})
module.exit_json(**result)
if __name__ == '__main__':
main()

@ -1,371 +0,0 @@
#!/usr/bin/python
#
# Copyright: Ansible Project
# 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 = """
---
module: asa_config
version_added: "2.2"
author: "Peter Sprygada (@privateip), Patrick Ogenstad (@ogenstad)"
short_description: Manage configuration sections on Cisco ASA devices
description:
- Cisco ASA configurations use a simple block indent file syntax
for segmenting configuration into sections. This module provides
an implementation for working with ASA configuration sections in
a deterministic way.
extends_documentation_fragment: asa
options:
lines:
description:
- The ordered set of commands that should be configured in the
section. The commands must be the exact same commands as found
in the device running-config. Be sure to note the configuration
command syntax as some commands are automatically modified by the
device config parser.
aliases: ['commands']
parents:
description:
- The ordered set of parents that uniquely identify the section or hierarchy
the commands should be checked against. If the parents argument
is omitted, the commands are checked against the set of top
level or global commands.
src:
description:
- Specifies the source path to the 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(lines), I(parents).
before:
description:
- The ordered set of commands to push on to the command stack if
a change needs to be made. This allows the playbook designer
the opportunity to perform configuration commands prior to pushing
any changes without affecting how the set of commands are matched
against the system.
after:
description:
- The ordered set of commands to append to the end of the command
stack if a change needs to be made. Just like with I(before) this
allows the playbook designer to append a set of commands to be
executed after the command set.
match:
description:
- Instructs the module on the way to perform the matching of
the set of commands against the current device config. If
match is set to I(line), commands are matched line by line. If
match is set to I(strict), command lines are matched with respect
to position. If match is set to I(exact), command lines
must be an equal match. Finally, if match is set to I(none), the
module will not attempt to compare the source configuration with
the running configuration on the remote device.
default: line
choices: ['line', 'strict', 'exact', 'none']
replace:
description:
- Instructs the module on the way to perform the configuration
on the device. If the replace argument is set to I(line) then
the modified lines are pushed to the device in configuration
mode. If the replace argument is set to I(block) then the entire
command block is pushed to the device in configuration mode if any
line is not correct
default: line
choices: ['line', 'block']
backup:
description:
- This argument will cause the module to create a full backup of
the current C(running-config) from the remote device before any
changes are made. If the C(backup_options) value is not given,
the backup file is written to the C(backup) folder in the
playbook root directory. If the directory does not exist, it is created.
type: bool
default: 'no'
config:
description:
- The C(config) argument allows the playbook designer to supply
the base configuration to be used to validate configuration
changes necessary. If this argument is provided, the module
will not download the running-config from the remote node.
defaults:
description:
- This argument specifies whether or not to collect all defaults
when getting the remote device running config. When enabled,
the module will get the current config by issuing the command
C(show running-config all).
type: bool
default: 'no'
passwords:
description:
- This argument specifies to include passwords in the config
when retrieving the running-config from the remote device. This
includes passwords related to VPN endpoints. This argument is
mutually exclusive with I(defaults).
type: bool
default: 'no'
save:
description:
- The C(save) argument instructs the module to save the running-
config to the startup-config at the conclusion of the module
running. If check mode is specified, this argument is ignored.
type: bool
default: 'no'
backup_options:
description:
- This is a dict object containing configurable options related to backup file path.
The value of this option is read only when C(backup) is set to I(yes), if C(backup) is set
to I(no) this option will be silently ignored.
suboptions:
filename:
description:
- The filename to be used to store the backup configuration. If the filename
is not given it will be generated based on the hostname, current time and date
in format defined by <hostname>_config.<current-date>@<current-time>
dir_path:
description:
- This option provides the path ending with directory name in which the backup
configuration file will be stored. If the directory does not exist it will be first
created and the filename is either the value of C(filename) or default filename
as described in C(filename) options description. If the path value is not given
in that case a I(backup) directory will be created in the current working directory
and backup configuration will be copied in C(filename) within I(backup) directory.
type: path
type: dict
version_added: "2.8"
"""
EXAMPLES = """
# Note: examples below use the following provider dict to handle
# transport and authentication to the node.
---
vars:
cli:
host: "{{ inventory_hostname }}"
username: cisco
password: cisco
authorize: yes
auth_pass: cisco
---
- asa_config:
lines:
- network-object host 10.80.30.18
- network-object host 10.80.30.19
- network-object host 10.80.30.20
parents: ['object-group network OG-MONITORED-SERVERS']
provider: "{{ cli }}"
- asa_config:
host: "{{ inventory_hostname }}"
lines:
- message-length maximum client auto
- message-length maximum 512
match: line
parents: ['policy-map type inspect dns PM-DNS', 'parameters']
authorize: yes
auth_pass: cisco
username: admin
password: cisco
context: ansible
- asa_config:
lines:
- ikev1 pre-shared-key MyS3cretVPNK3y
parents: tunnel-group 1.1.1.1 ipsec-attributes
passwords: yes
provider: "{{ cli }}"
- name: attach ASA acl on interface vlan13/nameif cloud13
asa_config:
lines:
- access-group cloud-acl_access_in in interface cloud13
provider: "{{ cli }}"
- name: configure ASA (>=9.2) default BGP
asa_config:
lines:
- bgp log-neighbor-changes
- bgp bestpath compare-routerid
provider: "{{ cli }}"
parents:
- router bgp 65002
register: bgp
when: bgp_default_config is defined
- name: configure ASA (>=9.2) BGP neighbor in default/single context mode
asa_config:
lines:
- "bgp router-id {{ bgp_router_id }}"
- "neighbor {{ bgp_neighbor_ip }} remote-as {{ bgp_neighbor_as }}"
- "neighbor {{ bgp_neighbor_ip }} description {{ bgp_neighbor_name }}"
provider: "{{ cli }}"
parents:
- router bgp 65002
- address-family ipv4 unicast
register: bgp
when: bgp_neighbor_as is defined
- name: configure ASA interface with standby
asa_config:
lines:
- description my cloud interface
- nameif cloud13
- security-level 50
- ip address 192.168.13.1 255.255.255.0 standby 192.168.13.2
provider: "{{ cli }}"
parents: ["interface Vlan13"]
register: interface
- name: Show changes to interface from task above
debug:
var: interface
- name: configurable backup path
asa_config:
lines:
- access-group cloud-acl_access_in in interface cloud13
provider: "{{ cli }}"
backup: yes
backup_options:
filename: backup.cfg
dir_path: /home/user
"""
RETURN = """
updates:
description: The set of commands that will be pushed to the remote device
returned: always
type: list
sample: ['...', '...']
backup_path:
description: The full path to the backup file
returned: when backup is yes
type: str
sample: /playbooks/ansible/backup/asa_config.2016-07-16@22:28:34
"""
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.network.asa.asa import asa_argument_spec, check_args
from ansible.module_utils.network.asa.asa import get_config, load_config, run_commands
from ansible.module_utils.network.common.config import NetworkConfig, dumps
from ansible.module_utils._text import to_native
def get_candidate(module):
candidate = NetworkConfig(indent=1)
if module.params['src']:
candidate.load(module.params['src'])
elif module.params['lines']:
parents = module.params['parents'] or list()
candidate.add(module.params['lines'], parents=parents)
return candidate
def run(module, result):
match = module.params['match']
replace = module.params['replace']
path = module.params['parents']
candidate = get_candidate(module)
if match != 'none':
contents = module.params['config']
if not contents:
contents = get_config(module)
config = NetworkConfig(indent=1, contents=contents)
configobjs = candidate.difference(config, path=path, match=match,
replace=replace)
else:
configobjs = candidate.items
if configobjs:
commands = dumps(configobjs, 'commands').split('\n')
if module.params['lines']:
if module.params['before']:
commands[:0] = module.params['before']
if module.params['after']:
commands.extend(module.params['after'])
result['updates'] = commands
# send the configuration commands to the device and merge
# them with the current running config
if not module.check_mode:
load_config(module, commands)
result['changed'] = True
if module.params['save']:
if not module.check_mode:
run_commands(module, 'write mem')
result['changed'] = True
def main():
""" main entry point for module execution
"""
backup_spec = dict(
filename=dict(),
dir_path=dict(type='path')
)
argument_spec = dict(
src=dict(type='path'),
lines=dict(aliases=['commands'], type='list'),
parents=dict(type='list'),
before=dict(type='list'),
after=dict(type='list'),
match=dict(default='line', choices=['line', 'strict', 'exact', 'none']),
replace=dict(default='line', choices=['line', 'block']),
backup_options=dict(type='dict', options=backup_spec),
config=dict(),
defaults=dict(type='bool', default=False),
passwords=dict(type='bool', default=False),
backup=dict(type='bool', default=False),
save=dict(type='bool', default=False),
)
argument_spec.update(asa_argument_spec)
mutually_exclusive = [('lines', 'src'),
('parents', 'src'),
('defaults', 'passwords')]
required_if = [('match', 'strict', ['lines']),
('match', 'exact', ['lines']),
('replace', 'block', ['lines'])]
module = AnsibleModule(argument_spec=argument_spec,
mutually_exclusive=mutually_exclusive,
required_if=required_if,
supports_check_mode=True)
result = {'changed': False}
check_args(module)
config = None
if module.params['backup']:
result['__backup__'] = get_config(module)
run(module, result)
module.exit_json(**result)
if __name__ == '__main__':
main()

@ -1,801 +0,0 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2019, Ansible by Red Hat, 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 = """
---
module: asa_og
version_added: "2.8"
author:
- "Federico Olivieri (@Federico87)"
short_description: Manage object groups on a Cisco ASA
description:
- This module allows you to create and update object-group network/service on Cisco ASA device.
options:
name:
description:
- Name of the object group.
required: true
group_type:
description:
- The object group type.
choices: ['network-object', 'service-object', 'port-object']
required: true
protocol:
description:
- The protocol for object-group service with port-object.
choices: ['udp', 'tcp', 'tcp-udp']
host_ip:
description:
- The host IP address for object-group network.
type: list
description:
description:
- The description for the object-group.
group_object:
description:
- The group-object for network object-group.
type: list
ip_mask:
description:
- The IP address and mask for network object-group.
type: list
port_range:
description:
- The port range for port-object.
port_eq:
description:
- The single port for port-object.
service_cfg:
description:
- The service-object configuration protocol, direction, range or port.
state:
description:
- Manage the state of the resource.
default: present
choices: ['present', 'absent', 'replace']
"""
EXAMPLES = """
---
- name: configure network object-group
asa_og:
name: ansible_test_0
group_type: network-object
state: present
description: ansible_test object-group description
host_ip:
- 8.8.8.8
- 8.8.4.4
ip_mask:
- 10.0.0.0 255.255.255.0
- 192.168.0.0 255.255.0.0
group_object:
- awx_lon
- awx_ams
- name: configure port-object object-group
asa_og:
name: ansible_test_1
group_type: port-object
state: replace
description: ansible_test object-group description
protocol: tcp-udp
port_eq:
- 1025
- kerberos
port_range:
- 1025 5201
- 0 1024
- name: configure service-object object-group
asa_og:
name: ansible_test_2
group_type: service-object
state: absent
description: ansible_test object-group description
service_cfg:
- tcp destination eq 8080
- tcp destination eq www
"""
RETURN = """
commands:
description: command sent to the device
returned: always
type: list
sample: [
"object-group network ansible_test_0",
"description ansible_test object-group description",
"network-object host 8.8.8.8",
"network-object host 8.8.4.4",
"network-object 10.0.0.0 255.255.255.0",
"network-object 192.168.0.0 255.255.0.0",
"network-object 192.168.0.0 255.255.0.0",
"group-object awx_lon",
"group-object awx_ams",
]
"""
import re
import sys
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.network.asa.asa import check_args
from ansible.module_utils.network.asa.asa import get_config, load_config, run_commands
from ansible.module_utils.network.common.config import NetworkConfig, dumps
class Parser():
'''Regex class for outputs parsing'''
def __init__(self, config, protocol):
'''Parser __init__ method'''
self.config = config
self.protocol = protocol
def parse_obj_grp_name(self):
list_return = list()
match = re.search(r'(?:object-group\s)(network\s|service\s)(\w+)\s?(tcp-udp|tcp|udp)?', self.config, re.M)
if match:
if match.group(3):
list_return.append(str(match.group(3)))
else:
list_return.append(False)
if match.group(2):
list_return.append(str(match.group(2)))
if match.group(1):
list_return.append(str(match.group(1)))
return list_return
def parse_description(self):
match = re.search(r'(description\s)(.*)', self.config, re.M)
if match:
description = match.group(2)
return description
def parse_host(self):
list_return = list()
match = re.findall(r'(host\s)(\d+\.\d+\.\d+\.\d+)', self.config, re.M)
if match:
for i in match:
if i[1]:
list_return.append(str(i[1]))
return list_return
def parse_group_object(self):
list_return = list()
match = re.findall(r'(group-object\s)(.*)', self.config, re.M)
if match:
for i in match:
if i[1]:
list_return.append(str(i[1]))
return list_return
def parse_address(self):
list_return = list()
match = re.findall(r'(network-object\s)(\d+\.\d+\.\d+\.\d+\s\d+\.\d+\.\d+\.\d+)', self.config, re.M)
if match:
for i in match:
if i[1]:
list_return.append(str(i[1]))
return list_return
def parse_port_range(self):
list_return = list()
match = re.findall(r'(range\s)(.*)', self.config, re.M)
if match:
for i in match:
if i[1]:
list_return.append(str(i[1]))
return list_return
def parse_port_eq(self):
list_return = list()
match = re.findall(r'(eq\s)(.*)', self.config, re.M)
if match:
for i in match:
if i[1]:
list_return.append(str(i[1]))
return list_return
def parse_service_cfg(self):
list_return = list()
match = re.findall(r'(service-object\s)(.*)', self.config, re.M)
if match:
for i in match:
if i[1]:
list_return.append(str(i[1]))
return list_return
def map_config_to_obj(module):
obj = list()
obj_dict = dict()
group_type = module.params['group_type']
group_name = module.params['name']
protocol = module.params['protocol']
sh_run_group_name = get_config(module, flags=['object-group | include {0}'.format(group_name)])
run_group_name = Parser(sh_run_group_name, protocol).parse_obj_grp_name()
obj_dict['have_name'] = run_group_name
if run_group_name:
if run_group_name[0] is not False:
obj_dict['have_group_type'] = "port-object"
obj_dict['have_protocol'] = run_group_name[0]
elif 'network' in run_group_name[2]:
obj_dict['have_group_type'] = "network-object"
elif 'service' in run_group_name[2] and run_group_name[0] is False:
obj_dict['have_group_type'] = "service-object"
else:
obj_dict['have_group_type'] = None
sh_run_group_type = get_config(module, flags=['object-group id {0}'.format(group_name)])
have_description = Parser(sh_run_group_type, protocol).parse_description()
obj_dict['have_description'] = have_description
have_host_ip = Parser(sh_run_group_type, protocol).parse_host()
obj_dict['have_host_ip'] = have_host_ip
have_group_object = Parser(sh_run_group_type, protocol).parse_group_object()
obj_dict['have_group_object'] = have_group_object
have_ip_mask = Parser(sh_run_group_type, protocol).parse_address()
obj_dict['have_ip_mask'] = have_ip_mask
have_port_range = Parser(sh_run_group_type, protocol).parse_port_range()
obj_dict['have_port_range'] = have_port_range
have_port_eq = Parser(sh_run_group_type, protocol).parse_port_eq()
obj_dict['have_port_eq'] = have_port_eq
have_service_cfg = Parser(sh_run_group_type, protocol).parse_service_cfg()
if have_service_cfg:
have_lines = list()
for i in have_service_cfg:
have_lines.append(i.rstrip(' '))
obj_dict['have_service_cfg'] = have_lines
elif have_service_cfg is None:
obj_dict['have_service_cfg'] = have_service_cfg
obj.append(obj_dict)
return obj
def replace(want_dict, have):
commands = list()
add_lines = list()
remove_lines = list()
have_name = have[0].get('have_name')
have_group_type = have[0].get('have_group_type')
have_config = have[0].get('have_lines')
have_description = have[0].get('have_description')
have_host_ip = have[0].get('have_host_ip')
have_group_object = have[0].get('have_group_object')
have_ip_mask = have[0].get('have_ip_mask')
have_protocol = have[0].get('have_protocol')
have_port_range = have[0].get('have_port_range')
have_port_eq = have[0].get('have_port_eq')
have_service_cfg = have[0].get('have_service_cfg')
name = want_dict['name']
group_type = want_dict['group_type']
protocol = want_dict['protocol']
description = want_dict['description']
host = want_dict['host_ip']
group_object = want_dict['group_object']
address = want_dict['ip_mask']
port_range = want_dict['port_range']
port_eq = want_dict['port_eq']
service_cfg = want_dict['service_cfg']
if 'network-object' in group_type:
if have_group_type is None:
commands.append('object-group network {0}'.format(name))
if host:
for i in host:
commands.append('network-object host ' + i)
if description:
if have_description is None:
commands.append('description {0}'.format(description))
if group_object:
for i in group_object:
if i not in have_group_object:
commands.append('group-object ' + i)
if address:
for i in address:
commands.append('network-object ' + i)
elif 'network' in have_group_type:
if host:
if sorted(host) != sorted(have_host_ip):
for i in host:
if i not in have_host_ip:
if 'object-group network {0}'.format(name) not in commands:
commands.append('object-group network {0}'.format(name))
add_lines.append('network-object host ' + i)
for i in have_host_ip:
if i not in host:
if 'object-group network {0}'.format(name) not in commands:
commands.append('object-group network {0}'.format(name))
remove_lines.append('no network-object host ' + i)
if description:
if description != have_description:
if 'object-group network {0}'.format(name) not in commands:
commands.append('object-group network {0}'.format(name))
add_lines.append('description {0}'.format(description))
if group_object:
if sorted(group_object) != sorted(have_group_object):
for i in group_object:
if i not in have_group_object:
if 'object-group network {0}'.format(name) not in commands:
commands.append('object-group network {0}'.format(name))
add_lines.append('group-object ' + i)
for i in have_group_object:
if i not in group_object:
if 'object-group network {0}'.format(name) not in commands:
commands.append('object-group network {0}'.format(name))
remove_lines.append('no group-object ' + i)
if address:
if sorted(address) != sorted(have_ip_mask):
for i in address:
if i not in have_ip_mask:
if 'object-group network {0}'.format(name) not in commands:
commands.append('object-group network {0}'.format(name))
add_lines.append('network-object ' + i)
for i in have_ip_mask:
if i not in address:
if 'object-group network {0}'.format(name) not in commands:
commands.append('object-group network {0}'.format(name))
remove_lines.append('no network-object ' + i)
elif 'port-object' in group_type:
if have_group_type is None and have_protocol != protocol:
commands.append('object-group service {0} {1}'.format(name, protocol))
if port_range:
for i in port_range:
commands.append('port-object range ' + i)
if port_eq:
for i in port_eq:
commands.append('port-object eq ' + i)
if description:
commands.append('description {0}'.format(description))
elif 'port' in have_group_type and have_protocol == protocol:
if port_range:
if sorted(port_range) != sorted(have_port_range):
for i in port_range:
if i not in have_port_range:
if 'object-group service {0} {1}'.format(name, protocol) not in commands:
commands.append('object-group service {0} {1}'.format(name, protocol))
add_lines.append('port-object range ' + i)
for i in have_port_range:
if i not in port_range:
if 'object-group service {0} {1}'.format(name, protocol) not in commands:
commands.append('object-group service {0} {1}'.format(name, protocol))
remove_lines.append('no port-object range ' + i)
if port_eq:
if sorted(port_eq) != sorted(have_port_eq):
for i in port_eq:
if i not in have_port_eq:
if 'object-group service {0} {1}'.format(name, protocol) not in commands:
commands.append('object-group service {0} {1}'.format(name, protocol))
add_lines.append('port-object eq ' + i)
for i in have_port_eq:
if i not in port_eq:
if 'object-group service {0} {1}'.format(name, protocol) not in commands:
commands.append('object-group service {0} {1}'.format(name, protocol))
remove_lines.append('no port-object eq ' + i)
if description:
if description != have_description:
if 'object-group service {0} {1}'.format(name, protocol) not in commands:
commands.append('object-group service {0} {1}'.format(name, protocol))
commands.append('description {0}'.format(description))
elif 'service-object' in group_type:
if have_group_type is None:
commands.append('object-group service {0}'.format(name))
if description:
if have_description is None:
commands.append('description {0}'.format(description))
if service_cfg:
for i in service_cfg:
commands.append('service-object ' + i)
elif 'service' in have_group_type:
if description:
if description != have_description:
if 'object-group service {0}'.format(name) not in commands:
commands.append('object-group service {0}'.format(name))
commands.append('description {0}'.format(description))
if service_cfg:
for i in service_cfg:
if i not in have_service_cfg:
if 'object-group service {0}'.format(name) not in commands:
commands.append('object-group service {0}'.format(name))
add_lines.append('service ' + i)
for i in have_service_cfg:
if i not in service_cfg:
if 'object-group service {0}'.format(name) not in commands:
commands.append('object-group service {0}'.format(name))
remove_lines.append('no service ' + i)
set_add_lines = set(add_lines)
set_remove_lines = set(remove_lines)
for i in list(set_add_lines) + list(set_remove_lines):
commands.append(i)
return commands
def present(want_dict, have):
commands = list()
have_name = have[0].get('have_name')
have_group_type = have[0].get('have_group_type')
have_config = have[0].get('have_lines')
have_description = have[0].get('have_description')
have_host_ip = have[0].get('have_host_ip')
have_group_object = have[0].get('have_group_object')
have_ip_mask = have[0].get('have_ip_mask')
have_protocol = have[0].get('have_protocol')
have_port_range = have[0].get('have_port_range')
have_port_eq = have[0].get('have_port_eq')
have_service_cfg = have[0].get('have_service_cfg')
name = want_dict['name']
group_type = want_dict['group_type']
protocol = want_dict['protocol']
description = want_dict['description']
host = want_dict['host_ip']
group_object = want_dict['group_object']
address = want_dict['ip_mask']
port_range = want_dict['port_range']
port_eq = want_dict['port_eq']
service_cfg = want_dict['service_cfg']
if 'network-object' in group_type:
if have_group_type is None:
commands.append('object-group network {0}'.format(name))
if host:
for i in host:
commands.append('network-object host ' + i)
if description:
if have_description is None:
commands.append('description {0}'.format(description))
if group_object:
for i in group_object:
commands.append('group-object ' + i)
if address:
for i in address:
commands.append('network-object ' + i)
elif 'network' in have_group_type:
if host:
for i in host:
if i not in have_host_ip:
if 'object-group network {0}'.format(name) not in commands:
commands.append('object-group network {0}'.format(name))
commands.append('network-object host ' + i)
if description:
if description != have_description:
if 'object-group network {0}'.format(name) not in commands:
commands.append('object-group network {0}'.format(name))
commands.append('description {0}'.format(description))
if group_object:
for i in group_object:
if i not in have_group_object:
if 'object-group network {0}'.format(name) not in commands:
commands.append('object-group network {0}'.format(name))
commands.append('group-object ' + i)
if address:
for i in address:
if i not in have_ip_mask:
if 'object-group network {0}'.format(name) not in commands:
commands.append('object-group network {0}'.format(name))
commands.append('network-object ' + i)
elif 'port-object' in group_type:
if have_group_type is None and have_protocol != protocol:
commands.append('object-group service {0} {1}'.format(name, protocol))
if port_range:
for i in port_range:
commands.append('port-object range ' + i)
if port_eq:
for i in port_eq:
commands.append('port-object eq ' + i)
if description:
commands.append('description {0}'.format(description))
elif 'port' in have_group_type and have_protocol == protocol:
if port_range:
for i in port_range:
if i not in have_port_range:
if 'object-group service {0} {1}'.format(name, protocol) not in commands:
commands.append('object-group service {0} {1}'.format(name, protocol))
commands.append('port-object range ' + i)
if port_eq:
for i in port_eq:
if i not in have_port_eq:
if 'object-group service {0} {1}'.format(name, protocol) not in commands:
commands.append('object-group service {0} {1}'.format(name, protocol))
commands.append('port-object eq ' + i)
if description:
if description != have_description:
if 'object-group service {0} {1}'.format(name, protocol) not in commands:
commands.append('object-group service {0} {1}'.format(name, protocol))
commands.append('description {0}'.format(description))
elif 'service-object' in group_type:
if have_group_type is None:
commands.append('object-group service {0}'.format(name))
if description:
if have_description is None:
commands.append('description {0}'.format(description))
if service_cfg:
for i in service_cfg:
commands.append('service-object ' + i)
elif 'service' in have_group_type:
if description:
if description != have_description:
if 'object-group service {0}'.format(name) not in commands:
commands.append('object-group service {0}'.format(name))
commands.append('description {0}'.format(description))
if service_cfg:
for i in service_cfg:
if i not in have_service_cfg:
if 'object-group service {0}'.format(name) not in commands:
commands.append('object-group service {0}'.format(name))
commands.append('service ' + i)
return commands
def absent(want_dict, have):
commands = list()
have_name = have[0].get('have_name')
have_group_type = have[0].get('have_group_type')
have_config = have[0].get('have_lines')
have_description = have[0].get('have_description')
have_host_ip = have[0].get('have_host_ip')
have_group_object = have[0].get('have_group_object')
have_ip_mask = have[0].get('have_ip_mask')
have_protocol = have[0].get('have_protocol')
have_port_range = have[0].get('have_port_range')
have_port_eq = have[0].get('have_port_eq')
have_service_cfg = have[0].get('have_service_cfg')
name = want_dict['name']
group_type = want_dict['group_type']
protocol = want_dict['protocol']
description = want_dict['description']
host = want_dict['host_ip']
group_object = want_dict['group_object']
address = want_dict['ip_mask']
port_range = want_dict['port_range']
port_eq = want_dict['port_eq']
service_cfg = want_dict['service_cfg']
if 'network-object' in group_type:
if have_group_type is None:
return commands
elif 'network' in have_group_type:
if host:
for i in host:
if i in have_host_ip:
if 'object-group network {0}'.format(name) not in commands:
commands.append('object-group network {0}'.format(name))
commands.append('no network-object host ' + i)
if description:
if description == have_description:
if 'object-group network {0}'.format(name) not in commands:
commands.append('object-group network {0}'.format(name))
commands.append('no description {0}'.format(description))
if group_object:
for i in group_object:
if i in have_group_object:
if 'object-group network {0}'.format(name) not in commands:
commands.append('object-group network {0}'.format(name))
commands.append('no group-object ' + i)
if address:
for i in address:
if i in have_ip_mask:
if 'object-group network {0}'.format(name) not in commands:
commands.append('object-group network {0}'.format(name))
commands.append('no network-object ' + i)
elif 'port-object' in group_type:
if have_group_type is None and have_protocol is None:
return commands
elif 'port' in have_group_type and have_protocol == protocol:
if port_range:
for i in port_range:
if i in have_port_range:
if 'object-group service {0} {1}'.format(name, protocol) not in commands:
commands.append('object-group service {0} {1}'.format(name, protocol))
commands.append('no port-object range ' + i)
if port_eq:
for i in port_eq:
if i in have_port_eq:
if 'object-group service {0} {1}'.format(name, protocol) not in commands:
commands.append('object-group service {0} {1}'.format(name, protocol))
commands.append('no port-object eq ' + i)
if description:
if description == have_description:
if 'object-group service {0} {1}'.format(name, protocol) not in commands:
commands.append('object-group service {0} {1}'.format(name, protocol))
commands.append('no description {0}'.format(description))
elif 'service-object' in group_type:
if have_group_type is None:
return commands
elif 'service' in have_group_type:
if description:
if description == have_description:
if 'object-group service {0}'.format(name) not in commands:
commands.append('object-group service {0}'.format(name))
commands.append('no description {0}'.format(description))
if service_cfg:
for i in service_cfg:
if i in have_service_cfg:
if 'object-group service {0}'.format(name) not in commands:
commands.append('object-group service {0}'.format(name))
commands.append('no service ' + i)
return commands
def map_obj_to_commands(want, have, module):
for w in want:
want_dict = dict()
want_dict['name'] = w['name']
want_dict['group_type'] = w['group_type']
want_dict['protocol'] = w['protocol']
want_dict['description'] = w['description']
want_dict['host_ip'] = w['host_ip']
want_dict['group_object'] = w['group_object']
want_dict['ip_mask'] = w['ip_mask']
want_dict['port_range'] = w['port_range']
want_dict['port_eq'] = w['port_eq']
want_dict['service_cfg'] = w['service_cfg']
state = w['state']
if state == 'replace':
return replace(want_dict, have)
elif state == 'present':
return present(want_dict, have)
elif state == 'absent':
return absent(want_dict, have)
def map_params_to_obj(module):
obj = list()
obj.append({
'name': module.params['name'],
'group_type': module.params['group_type'],
'protocol': module.params['protocol'],
'state': module.params['state'],
'description': module.params['description'],
'host_ip': module.params['host_ip'],
'group_object': module.params['group_object'],
'port_range': module.params['port_range'],
'port_eq': module.params['port_eq'],
'service_cfg': module.params['service_cfg'],
'ip_mask': module.params['ip_mask']
})
return obj
def main():
argument_spec = dict(
name=dict(required=True),
group_type=dict(choices=['network-object', 'service-object', 'port-object'], required=True),
protocol=dict(choices=['udp', 'tcp', 'tcp-udp']),
host_ip=dict(type='list'),
description=dict(),
group_object=dict(type='list'),
ip_mask=dict(type='list'),
port_range=dict(type='list'),
port_eq=dict(type='list'),
service_cfg=dict(type='list'),
state=dict(choices=['present', 'absent', 'replace'], default='present')
)
required_if = [('group_type', 'port-object', ['protocol']),
('group_type', 'service-object', ['service_cfg'])]
module = AnsibleModule(argument_spec=argument_spec,
required_if=required_if,
supports_check_mode=True)
result = {'changed': False}
want = map_params_to_obj(module)
have = map_config_to_obj(module)
config_commans = map_obj_to_commands(want, have, module)
result['commands'] = config_commans
if config_commans:
if not module.check_mode:
load_config(module, config_commans)
result['changed'] = True
module.exit_json(**result)
if __name__ == '__main__':
main()

@ -1,74 +0,0 @@
#
# (c) 2016 Red Hat Inc.
#
# 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/>.
#
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import sys
import copy
import json
from ansible import constants as C
from ansible.plugins.action.network import ActionModule as ActionNetworkModule
from ansible.module_utils.network.asa.asa import asa_provider_spec
from ansible.module_utils.network.common.utils import load_provider
from ansible.utils.display import Display
display = Display()
class ActionModule(ActionNetworkModule):
def run(self, tmp=None, task_vars=None):
del tmp # tmp no longer has any effect
module_name = self._task.action.split('.')[-1]
self._config_module = True if module_name == 'asa_config' else False
if self._play_context.connection == 'local':
provider = load_provider(asa_provider_spec, self._task.args)
pc = copy.deepcopy(self._play_context)
pc.connection = 'network_cli'
pc.network_os = 'asa'
pc.remote_addr = provider['host'] or self._play_context.remote_addr
pc.port = int(provider['port'] or self._play_context.port or 22)
pc.remote_user = provider['username'] or self._play_context.connection_user
pc.password = provider['password'] or self._play_context.password
pc.private_key_file = provider['ssh_keyfile'] or self._play_context.private_key_file
command_timeout = int(provider['timeout'] or C.PERSISTENT_COMMAND_TIMEOUT)
pc.become = provider['authorize'] or False
pc.become_pass = provider['auth_pass']
pc.become_method = 'enable'
display.vvv('using connection plugin %s (was local)' % pc.connection, pc.remote_addr)
connection = self._shared_loader_obj.connection_loader.get('persistent', pc, sys.stdin, task_uuid=self._task._uuid)
connection.set_options(direct={'persistent_command_timeout': command_timeout})
socket_path = connection.run()
display.vvvv('socket_path: %s' % socket_path, pc.remote_addr)
if not socket_path:
return {'failed': True,
'msg': 'unable to open shell. Please see: ' +
'https://docs.ansible.com/ansible/network_debug_troubleshooting.html#unable-to-open-shell'}
task_vars['ansible_socket'] = socket_path
result = super(ActionModule, self).run(task_vars=task_vars)
return result

@ -1,85 +0,0 @@
#
# (c) 2017 Red Hat Inc.
#
# 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/>.
#
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = """
---
cliconf: asa
short_description: Use asa cliconf to run command on Cisco ASA platform
description:
- This asa plugin provides low level abstraction apis for
sending and receiving CLI commands from Cisco ASA network devices.
version_added: 2.4
"""
import re
import json
from itertools import chain
from ansible.module_utils._text import to_bytes, to_text
from ansible.module_utils.network.common.utils import to_list
from ansible.plugins.cliconf import CliconfBase, enable_mode
class Cliconf(CliconfBase):
def get_device_info(self):
device_info = {}
device_info['network_os'] = 'asa'
reply = self.get('show version')
data = to_text(reply, errors='surrogate_or_strict').strip()
match = re.search(r'Version (\S+),', data)
if match:
device_info['network_os_version'] = match.group(1)
match = re.search(r'^Model Id:\s+(.+) \(revision', data, re.M)
if match:
device_info['network_os_model'] = match.group(1)
match = re.search(r'^(.+) up', data, re.M)
if match:
device_info['network_os_hostname'] = match.group(1)
return device_info
@enable_mode
def get_config(self, source='running', format='text', flags=None):
if source not in ('running', 'startup'):
return self.invalid_params("fetching configuration from %s is not supported" % source)
if source == 'running':
cmd = 'show running-config all'
else:
cmd = 'show startup-config'
return self.send_command(cmd)
@enable_mode
def edit_config(self, command):
for cmd in chain(['configure terminal'], to_list(command), ['end']):
self.send_command(cmd)
def get(self, command, prompt=None, answer=None, sendonly=False, newline=True, check_all=False):
return self.send_command(command=command, prompt=prompt, answer=answer, sendonly=sendonly, newline=newline, check_all=check_all)
def get_capabilities(self):
result = super(Cliconf, self).get_capabilities()
return json.dumps(result)

@ -1,98 +0,0 @@
# -*- coding: utf-8 -*-
# Copyright: (c) 2016, Peter Sprygada <psprygada@ansible.com>
# Copyright: (c) 2016, Patrick Ogenstad <@ogenstad>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
class ModuleDocFragment(object):
# Standard files documentation fragment
DOCUMENTATION = r'''
options:
authorize:
description:
- B(Deprecated)
- "Starting with Ansible 2.5 we recommend using C(connection: network_cli) and C(become: yes)."
- For more information please see the L(Network Guide, ../network/getting_started/network_differences.html#multiple-communication-protocols).
- HORIZONTALLINE
- Instructs the module to enter privileged mode on the remote device
before sending any commands. If not specified, the device will
attempt to execute all commands in non-privileged mode. If the value
is not specified in the task, the value of environment variable
C(ANSIBLE_NET_AUTHORIZE) will be used instead.
type: bool
default: no
context:
description:
- Specifies which context to target if you are running in the ASA in
multiple context mode. Defaults to the current context you login to.
type: str
provider:
description:
- B(Deprecated)
- "Starting with Ansible 2.5 we recommend using C(connection: network_cli)."
- For more information please see the L(Network Guide, ../network/getting_started/network_differences.html#multiple-communication-protocols).
- HORIZONTALLINE
- A dict object containing connection details.
suboptions:
host:
description:
- Specifies the DNS host name or address for connecting to the remote
device over the specified transport. The value of host is used as
the destination address for the transport.
type: str
port:
description:
- Specifies the port to use when building the connection to the remote
device.
type: int
default: 22
username:
description:
- Configures the username to use to authenticate the connection to
the remote device. This value is used to authenticate
the SSH session. If the value is not specified in the task, the
value of environment variable C(ANSIBLE_NET_USERNAME) will be used instead.
type: str
password:
description:
- Specifies the password to use to authenticate the connection to
the remote device. This value is used to authenticate
the SSH session. If the value is not specified in the task, the
value of environment variable C(ANSIBLE_NET_PASSWORD) will be used instead.
type: str
ssh_keyfile:
description:
- Specifies the SSH key to use to authenticate the connection to
the remote device. This value is the path to the
key used to authenticate the SSH session. If the value is not specified
in the task, the value of environment variable C(ANSIBLE_NET_SSH_KEYFILE)
will be used instead.
type: path
authorize:
description:
- Instructs the module to enter privileged mode on the remote device
before sending any commands. If not specified, the device will
attempt to execute all commands in non-privileged mode. If the value
is not specified in the task, the value of environment variable
C(ANSIBLE_NET_AUTHORIZE) will be used instead.
type: bool
default: no
auth_pass:
description:
- Specifies the password to use if required to enter privileged mode
on the remote device. If I(authorize) is false, then this argument
does nothing. If the value is not specified in the task, the value of
environment variable C(ANSIBLE_NET_AUTH_PASS) will be used instead.
type: str
timeout:
description:
- Specifies idle timeout in seconds for the connection, in seconds. Useful
if the console freezes before continuing. For example when saving
configurations.
type: int
default: 10
notes:
- For more information on using Ansible to manage network devices see the :ref:`Ansible Network Guide <network_guide>`
'''

@ -1,70 +0,0 @@
#
# (c) 2016 Red Hat Inc.
#
# 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/>.
#
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import re
import json
from ansible.errors import AnsibleConnectionFailure
from ansible.module_utils._text import to_text, to_bytes
from ansible.plugins.terminal import TerminalBase
class TerminalModule(TerminalBase):
terminal_stdout_re = [
re.compile(br"[\r\n]?[\w+\-\.:\/\[\]]+(?:\([^\)]+\)){,3}(?:>|#) ?$"),
re.compile(br"\[\w+\@[\w\-\.]+(?: [^\]])\] ?[>#\$] ?$")
]
terminal_stderr_re = [
re.compile(br"error:", re.I),
re.compile(br"Removing.* not allowed, it is being used"),
re.compile(br"^Command authorization failed\r?$", re.MULTILINE)
]
def on_open_shell(self):
if self._get_prompt().strip().endswith(b'#'):
self.disable_pager()
def disable_pager(self):
cmd = {u'command': u'no terminal pager'}
try:
self._exec_cli_command(u'no terminal pager')
except AnsibleConnectionFailure:
raise AnsibleConnectionFailure('unable to disable terminal pager')
def on_become(self, passwd=None):
if self._get_prompt().strip().endswith(b'#'):
return
cmd = {u'command': u'enable'}
if passwd:
# Note: python-3.5 cannot combine u"" and r"" together. Thus make
# an r string and use to_text to ensure it's text on both py2 and py3.
cmd[u'prompt'] = to_text(r"[\r\n]?[Pp]assword: $", errors='surrogate_or_strict')
cmd[u'answer'] = passwd
try:
self._exec_cli_command(to_bytes(json.dumps(cmd), errors='surrogate_or_strict'))
except AnsibleConnectionFailure:
raise AnsibleConnectionFailure('unable to elevate privilege to enable mode')
self.disable_pager()

@ -1,3 +0,0 @@
---
testcase: "*"
test_items: []

@ -1,16 +0,0 @@
---
- name: collect all cli test cases
find:
paths: "{{ role_path }}/tests/cli"
patterns: "{{ testcase }}.yaml"
register: test_cases
- name: set test_items
set_fact: test_items="{{ test_cases.files | map(attribute='path') | list }}"
- name: run test case
include: "{{ test_case_to_run }}"
with_items: "{{ test_items }}"
loop_control:
loop_var: test_case_to_run

@ -1,2 +0,0 @@
---
- { include: cli.yaml, tags: ['cli'] }

@ -1,41 +0,0 @@
---
- debug: msg="START cli/basic.yaml"
- name: setup
asa_config:
commands:
- clear configure access-list ACL-BASIC
provider: "{{ cli }}"
ignore_errors: yes
- name: Basic ACL
asa_acl:
provider: "{{ cli }}"
lines:
- access-list ACL-BASIC extended permit tcp any any eq www
- access-list ACL-BASIC extended permit tcp any any eq https
register: result
- assert:
that:
- "result.changed == true"
- name: Basic ACL idempotency
asa_acl:
provider: "{{ cli }}"
lines:
- access-list ACL-BASIC extended permit tcp any any eq www
- access-list ACL-BASIC extended permit tcp any any eq https
register: result
- assert:
that:
- "result.changed == false"
- name: teardown
asa_config:
commands:
- clear configure access-list ACL-BASIC
provider: "{{ cli }}"
- debug: msg="END cli/basic.yaml"

@ -1,43 +0,0 @@
---
- debug: msg="START cli/full_name_match.yaml"
- name: setup
asa_config:
commands:
- clear configure access-list ACL-BASIC
- clear configure access-list ACL-BASIC2
provider: "{{ cli }}"
ignore_errors: yes
- name: Basic ACL
asa_acl:
provider: "{{ cli }}"
lines:
- access-list ACL-BASIC2 extended permit tcp any any eq www
- access-list ACL-BASIC2 extended permit tcp any any eq https
register: result
- assert:
that:
- "result.changed == true"
- name: Should not match for ACL-BASIC2
asa_acl:
provider: "{{ cli }}"
lines:
- access-list ACL-BASIC extended permit tcp any any eq www
- access-list ACL-BASIC extended permit tcp any any eq https
register: result
- assert:
that:
- "result.changed == true"
- name: teardown
asa_config:
commands:
- clear configure access-list ACL-BASIC
- clear configure access-list ACL-BASIC2
provider: "{{ cli }}"
- debug: msg="END cli/full_name_match.yaml"

@ -1,51 +0,0 @@
---
- debug: msg="START cli/insert.yaml"
- name: setup
asa_config:
commands:
- clear configure access-list ACL-INSERT
provider: "{{ cli }}"
ignore_errors: yes
- name: Create ACL
asa_acl:
provider: "{{ cli }}"
lines:
- access-list ACL-INSERT extended permit tcp any any eq www
- access-list ACL-INSERT extended permit tcp any any eq https
register: result
- name: Insert on first line
asa_acl:
provider: "{{ cli }}"
lines:
- access-list ACL-INSERT extended permit tcp any any eq www
- access-list ACL-INSERT extended permit tcp any any eq https
- access-list ACL-INSERT line 1 extended permit tcp any any eq ssh
register: result
- name: Show ACL
asa_command:
provider: "{{ cli }}"
commands: "show run access-list ACL-INSERT"
register: result
- name: Show me
debug:
var: result
- name:
assert:
that:
- result.stdout_lines[0][0].rstrip() == 'access-list ACL-INSERT extended permit tcp any any eq ssh'
- name: teardown
asa_config:
commands:
- clear configure access-list ACL-INSERT
provider: "{{ cli }}"
- debug: msg="END cli/insert.yaml"

@ -1,3 +0,0 @@
---
testcase: "*"
test_items: []

@ -1,15 +0,0 @@
---
- name: collect all cli test cases
find:
paths: "{{ role_path }}/tests/cli"
patterns: "{{ testcase }}.yaml"
register: test_cases
- name: set test_items
set_fact: test_items="{{ test_cases.files | map(attribute='path') | list }}"
- name: run test case
include: "{{ test_case_to_run }}"
with_items: "{{ test_items }}"
loop_control:
loop_var: test_case_to_run

@ -1,2 +0,0 @@
---
- { include: cli.yaml, tags: ['cli'] }

@ -1,20 +0,0 @@
---
- debug: msg="START cli/bad_operator.yaml"
- name: test bad operator
asa_command:
commands:
- show version
- show interfaces GigabitEthernet 0/0
wait_for:
- result[0] contains 'Description: Foo'
provider: "{{ cli }}"
register: result
ignore_errors: yes
- assert:
that:
- "result.failed == true"
- "result.msg is defined"
- debug: msg="END cli/bad_operator.yaml"

@ -1,20 +0,0 @@
---
- debug: msg="START cli/contains.yaml"
- name: test contains operator
asa_command:
commands:
- show version
- show interface
wait_for:
- "result[0] contains 'Cisco Adaptive Security Appliance Software Version'"
- "result[1] contains 'Hardware'"
provider: "{{ cli }}"
register: result
- assert:
that:
- "result.changed == false"
- "result.stdout is defined"
- debug: msg="END cli/contains.yaml"

@ -1,30 +0,0 @@
---
- debug: msg="START cli/invalid.yaml"
- name: run invalid command
asa_command:
commands: ['show foo']
provider: "{{ cli }}"
register: result
ignore_errors: yes
- assert:
that:
- "result.failed"
- name: run commands that include invalid command
asa_command:
commands:
- show version
- show foo
provider: "{{ cli }}"
register: result
ignore_errors: yes
- assert:
that:
- "result.failed"
# FIXME bug https://github.com/ansible/ansible-modules-extras/issues/3048
ignore_errors: true
- debug: msg="END cli/invalid.yaml"

@ -1,29 +0,0 @@
---
- debug: msg="START cli/output.yaml"
- name: get output for single command
asa_command:
commands: ['show version']
provider: "{{ cli }}"
register: result
- assert:
that:
- "result.changed == false"
- "result.stdout is defined"
- name: get output for multiple commands
asa_command:
commands:
- show version
- show interface
provider: "{{ cli }}"
register: result
- assert:
that:
- "result.changed == false"
- "result.stdout is defined"
- "result.stdout | length == 2"
- debug: msg="END cli/output.yaml"

@ -1,19 +0,0 @@
---
- debug: msg="START cli/timeout.yaml"
- name: test bad condition
asa_command:
commands:
- show version
wait_for:
- "result[0] contains bad_value_string"
provider: "{{ cli }}"
register: result
ignore_errors: yes
- assert:
that:
- "result.failed == true"
- "result.msg is defined"
- debug: msg="END cli/timeout.yaml"

@ -1,3 +0,0 @@
---
testcase: "*"
test_items: []

@ -1,15 +0,0 @@
---
- name: collect all cli test cases
find:
paths: "{{ role_path }}/tests/cli"
patterns: "{{ testcase }}.yaml"
register: test_cases
- name: set test_items
set_fact: test_items="{{ test_cases.files | map(attribute='path') | list }}"
- name: run test case
include: "{{ test_case_to_run }}"
with_items: "{{ test_items }}"
loop_control:
loop_var: test_case_to_run

@ -1,2 +0,0 @@
---
- { include: cli.yaml, tags: ['cli'] }

@ -1,3 +0,0 @@
object-group network OG-ANSIBLE-TEMPLATE
description this is a test
network-object host 192.168.99.12

@ -1,4 +0,0 @@
object-group network OG-ANSIBLE-TEMPLATE-DEFAULT
description this is a test
network-object 10.0.0.0 255.255.255.0
network-object 10.1.0.0 255.255.255.0

@ -1,53 +0,0 @@
---
- debug: msg="START cli/backup.yaml"
- name: setup
asa_config:
commands:
- no object-group network OG-ANSIBLE-TEMPLATE
provider: "{{ cli }}"
ignore_errors: yes
- name: collect any backup files
find:
paths: "{{ role_path }}/backup"
pattern: "{{ inventory_hostname_short }}_config*"
register: backup_files
delegate_to: localhost
- name: delete backup files
file:
path: "{{ item.path }}"
state: absent
with_items: "{{backup_files.files|default([])}}"
- name: configure device with config
asa_config:
src: basic/config.j2
backup: yes
provider: "{{ cli }}"
register: result
- assert:
that:
- "result.changed == true"
- "result.updates is defined"
- name: collect any backup files
find:
paths: "{{ role_path }}/backup"
pattern: "{{ inventory_hostname_short }}_config*"
register: backup_files
delegate_to: localhost
- assert:
that:
- "backup_files.files is defined"
- name: teardown
asa_config:
commands:
- no object-group network OG-ANSIBLE-TEMPLATE
provider: "{{ cli }}"
- debug: msg="END cli/backup.yaml"

@ -1,39 +0,0 @@
---
- debug: msg="START cli/basic.yaml"
- name: setup
asa_config:
commands:
- no object-group network OG-ANSIBLE-TEMPLATE
provider: "{{ cli }}"
ignore_errors: yes
- name: configure device with config
asa_config:
src: basic/config.j2
provider: "{{ cli }}"
register: result
- assert:
that:
- "result.changed == true"
- "result.updates is defined"
- name: check device with config
asa_config:
src: basic/config.j2
provider: "{{ cli }}"
register: result
- assert:
that:
- "result.changed == false"
- "result.updates is not defined"
- name: teardown
asa_config:
commands:
- no object-group network OG-ANSIBLE-TEMPLATE
provider: "{{ cli }}"
- debug: msg="END cli/basic.yaml"

@ -1,45 +0,0 @@
---
- debug: msg="START cli/defaults.yaml"
- name: setup
asa_config:
commands:
- no object-group network OG-ANSIBLE-TEMPLATE-DEFAULT
provider: "{{ cli }}"
ignore_errors: yes
- name: configure device with defaults included
asa_config:
src: defaults/config.j2
defaults: yes
provider: "{{ cli }}"
register: result
- debug: var=result
- assert:
that:
- "result.changed == true"
- "result.updates is defined"
- name: check device with defaults included
asa_config:
src: defaults/config.j2
defaults: yes
provider: "{{ cli }}"
register: result
- debug: var=result
- assert:
that:
- "result.changed == false"
- "result.updates is not defined"
- name: teardown
asa_config:
commands:
- no object-group network OG-ANSIBLE-TEMPLATE-DEFAULT
provider: "{{ cli }}"
- debug: msg="END cli/defaults.yaml"

@ -1,41 +0,0 @@
---
- debug: msg="START cli/force.yaml"
- name: setup
asa_config:
commands:
- no object-group network OG-ANSIBLE-TEMPLATE-DEFAULT
provider: "{{ cli }}"
ignore_errors: yes
- name: configure device with config
asa_config:
src: basic/config.j2
provider: "{{ cli }}"
match: none
register: result
- assert:
that:
- "result.changed == true"
- "result.updates is defined"
- name: check device with config
asa_config:
src: basic/config.j2
provider: "{{ cli }}"
match: none
register: result
- assert:
that:
- "result.changed == true"
- "result.updates is defined"
- name: teardown
asa_config:
commands:
- no object-group network OG-ANSIBLE-TEMPLATE-DEFAULT
provider: "{{ cli }}"
- debug: msg="END cli/force.yaml"

@ -1,47 +0,0 @@
---
- debug: msg="START cli/more_system.yaml"
- name: setup
asa_config:
lines:
- "clear configure tunnel-group 192.0.2.1"
provider: "{{ cli }}"
ignore_errors: yes
- name: Prepare tunnel-group
asa_config:
before: tunnel-group 192.0.2.1 type ipsec-l2l
lines:
- "tunnel-group 192.0.2.1 ipsec-attributes"
provider: "{{ cli }}"
- name: Setup tunnel-group
asa_config:
parents: tunnel-group 192.0.2.1 ipsec-attributes
lines:
- "ikev1 pre-shared-key abc123"
passwords: yes
provider: "{{ cli }}"
- name: Test idempotency
asa_config:
parents: tunnel-group 192.0.2.1 ipsec-attributes
lines:
- "ikev1 pre-shared-key abc123"
passwords: yes
provider: "{{ cli }}"
register: result
- assert:
that:
- "result.changed == false"
- name: teardown
asa_config:
lines:
- "clear configure tunnel-group 192.0.2.1"
provider: "{{ cli }}"
- debug: msg="END cli/more_system.yaml"

@ -1,46 +0,0 @@
---
- debug: msg="START cli/removal_error.yaml"
- name: setup
asa_config:
commands:
- clear configure access-list ANSIBLE-DNS
- no object-group network OGA-GOOGLE-DNS
provider: "{{ cli }}"
ignore_errors: yes
- name: configure test object-group
asa_config:
parents: object-group network OGA-GOOGLE-DNS
lines: network-object host 8.8.8.8
provider: "{{ cli }}"
register: result
- name: configure test access-list
asa_config:
lines: access-list ANSIBLE-DNS extended permit udp any object-group OGA-GOOGLE-DNS eq domain
provider: "{{ cli }}"
- name: try to remove object-group (should fail)
asa_config:
commands:
- no object-group network OGA-GOOGLE-DNS
provider: "{{ cli }}"
ignore_errors: yes
register: result
- name: Last command should fail
assert:
that:
- "result.failed == true"
- name: teardown
asa_config:
commands:
- clear configure access-list ANSIBLE-DNS
- no object-group network OGA-GOOGLE-DNS
provider: "{{ cli }}"
- debug: msg="END cli/removal_error.yaml"

@ -1,40 +0,0 @@
---
- debug: msg="START cli/sublevel.yaml"
- name: setup test
asa_config:
lines:
- 'no object-group network OG-ANSIBLE-SUBLEVEL'
provider: "{{ cli }}"
- name: configure sub level command
asa_config:
lines: ['network-object host 192.168.10.1']
parents: ['object-group network OG-ANSIBLE-SUBLEVEL']
provider: "{{ cli }}"
register: result
- assert:
that:
- "result.changed == true"
- "'object-group network OG-ANSIBLE-SUBLEVEL' in result.updates"
- "'network-object host 192.168.10.1' in result.updates"
- name: configure sub level command idempotent check
asa_config:
lines: ['network-object host 192.168.10.1']
parents: ['object-group network OG-ANSIBLE-SUBLEVEL']
provider: "{{ cli }}"
register: result
- assert:
that:
- "result.changed == false"
- name: teardown
asa_config:
lines:
- 'no object-group network OG-ANSIBLE-SUBLEVEL'
provider: "{{ cli }}"
- debug: msg="END cli/sublevel.yaml"

@ -1,64 +0,0 @@
---
- debug: msg="START cli/sublevel_block.yaml"
- name: setup
asa_command:
commands:
- show run object-group
provider: "{{ cli }}"
register: object_group
- name: setup
asa_config:
lines:
- no object-group network OG-ANSIBLE
match: none
provider: "{{ cli }}"
#when: "'object-group network OG-ANSIBLE\n' in {{ object_group.stdout }}"
- name: configure sub level command using block replace
asa_config:
lines:
- network-object 192.168.10.0 255.255.255.0
- network-object 192.168.20.0 255.255.255.0
- network-object 192.168.30.0 255.255.255.0
- network-object 192.168.40.0 255.255.255.0
parents: ['object-group network OG-ANSIBLE']
replace: block
after: ['exit']
provider: "{{ cli }}"
register: result
- assert:
that:
- "result.changed == true"
- "'object-group network OG-ANSIBLE' in result.updates"
- "'network-object 192.168.10.0 255.255.255.0' in result.updates"
- "'network-object 192.168.20.0 255.255.255.0' in result.updates"
- "'network-object 192.168.30.0 255.255.255.0' in result.updates"
- "'network-object 192.168.40.0 255.255.255.0' in result.updates"
- name: check sub level command using block replace
asa_config:
lines:
- network-object 192.168.10.0 255.255.255.0
- network-object 192.168.20.0 255.255.255.0
- network-object 192.168.30.0 255.255.255.0
- network-object 192.168.40.0 255.255.255.0
parents: ['object-group network OG-ANSIBLE']
replace: block
after: ['exit']
provider: "{{ cli }}"
register: result
- assert:
that:
- "result.changed == false"
- name: teardown
asa_config:
lines:
- no object-group network OG-ANSIBLE
provider: "{{ cli }}"
- debug: msg="END cli/sublevel_block.yaml"

@ -1,64 +0,0 @@
---
- debug: msg="START cli/sublevel_exact.yaml"
- name: setup
asa_config:
lines:
- network-object 192.168.10.0 255.255.255.0
- network-object 192.168.20.0 255.255.255.0
- network-object 192.168.30.0 255.255.255.0
- network-object 192.168.40.0 255.255.255.0
- network-object 192.168.50.0 255.255.255.0
parents: ['object-group network OG-ANSIBLE-EXACT']
before: ['no object-group network OG-ANSIBLE-EXACT']
after: ['exit']
provider: "{{ cli }}"
- name: configure sub level command using exact match
asa_config:
lines:
- network-object 192.168.10.0 255.255.255.0
- network-object 192.168.20.0 255.255.255.0
- network-object 192.168.30.0 255.255.255.0
- network-object 192.168.40.0 255.255.255.0
parents: ['object-group network OG-ANSIBLE-EXACT']
after: ['exit']
match: exact
provider: "{{ cli }}"
register: result
- assert:
that:
- "result.changed == true"
- "'object-group network OG-ANSIBLE-EXACT' in result.updates"
- "'network-object 192.168.10.0 255.255.255.0' in result.updates"
- "'network-object 192.168.20.0 255.255.255.0' in result.updates"
- "'network-object 192.168.30.0 255.255.255.0' in result.updates"
- "'network-object 192.168.40.0 255.255.255.0' in result.updates"
- "'network-object 192.168.50.0 255.255.255.0' not in result.updates"
- name: check sub level command using exact match
asa_config:
lines:
- network-object 192.168.10.0 255.255.255.0
- network-object 192.168.20.0 255.255.255.0
- network-object 192.168.30.0 255.255.255.0
- network-object 192.168.40.0 255.255.255.0
- network-object 192.168.50.0 255.255.255.0
parents: ['object-group network OG-ANSIBLE-EXACT']
after: ['exit']
match: exact
provider: "{{ cli }}"
register: result
- assert:
that:
- "result.changed == false"
- name: teardown
asa_config:
lines:
- no object-group network OG-ANSIBLE-EXACT
provider: "{{ cli }}"
- debug: msg="END cli/sublevel_exact.yaml"

@ -1,61 +0,0 @@
---
- debug: msg="START cli/sublevel_strict.yaml"
- name: setup
asa_config:
lines:
- network-object 192.168.10.0 255.255.255.0
- network-object 192.168.20.0 255.255.255.0
- network-object 192.168.30.0 255.255.255.0
- network-object 192.168.40.0 255.255.255.0
- network-object 192.168.50.0 255.255.255.0
parents: ['object-group network OG-ANSIBLE-STRICT']
before: ['no object-group network OG-ANSIBLE-STRICT']
after: ['exit']
provider: "{{ cli }}"
- name: configure sub level command using strict match
asa_config:
lines:
- network-object 192.168.10.0 255.255.255.0
- network-object 192.168.20.0 255.255.255.0
- network-object 192.168.30.0 255.255.255.0
- network-object 192.168.40.0 255.255.255.0
parents: ['object-group network OG-ANSIBLE-STRICT']
match: strict
provider: "{{ cli }}"
register: result
- assert:
that:
- "result.changed == false"
- name: check sub level command using strict match
asa_config:
lines:
- network-object 192.168.10.0 255.255.255.0
- network-object 192.168.30.0 255.255.255.0
- network-object 192.168.30.0 255.255.255.0
parents: ['object-group network OG-ANSIBLE-STRICT']
after: ['exit']
match: strict
provider: "{{ cli }}"
register: result
- assert:
that:
- "result.changed == true"
- "'object-group network OG-ANSIBLE-STRICT' in result.updates"
- "'network-object 192.168.10.0 255.255.255.0' not in result.updates"
- "'network-object 192.168.30.0 255.255.255.0' in result.updates"
- "'network-object 192.168.30.0 255.255.255.0' in result.updates"
- "'network-object 192.168.40.0 255.255.255.0' not in result.updates"
- "'network-object 192.168.50.0 255.255.255.0' not in result.updates"
- name: teardown
asa_config:
lines:
- no object-group network OG-ANSIBLE-STRICT
provider: "{{ cli }}"
- debug: msg="END cli/sublevel_strict.yaml"

@ -1,66 +0,0 @@
---
- debug: msg="START cli/sublevel_strict_mul_parents.yaml on connection={{ ansible_connection }}"
- name: setup
asa_config:
lines:
- class-map c1
- match default-inspection-traffic
- policy-map p1
- class c1
before: ['no policy-map p1', 'no class-map c1']
match: none
- name: configure sub level command using strict match
asa_config:
lines:
- inspect ftp
- inspect tftp
parents: ['policy-map p1', 'class c1']
match: strict
register: result
- assert:
that:
- "result.changed == true"
- "'inspect ftp' in result.updates"
- "'inspect tftp' in result.updates"
- name: change sub level command order and config with strict match
asa_config:
lines:
- inspect tftp
- inspect ftp
parents: ['policy-map p1', 'class c1']
match: strict
register: result
- assert:
that:
- "result.changed == true"
- "'inspect ftp' in result.updates"
- "'inspect tftp' in result.updates"
- name: Config sub level command with strict match (Idempotency)
asa_config:
lines:
#ASA does not change order of class action if reconfigured
#so we have to use old order for Idempotency
- inspect ftp
- inspect tftp
parents: ['policy-map p1', 'class c1']
match: strict
register: result
- assert:
that:
- "result.changed == false"
- name: teardown
asa_config:
lines:
- no policy-map p1
- no class-map c1
match: strict
- debug: msg="END cli/sublevel_strict_mul_parents.yaml on connection={{ ansible_connection }}"

@ -1,35 +0,0 @@
---
- debug: msg="START cli/toplevel.yaml"
- name: setup
asa_config:
lines: ['hostname firewall']
provider: "{{ cli }}"
- name: configure top level command
asa_config:
lines: ['hostname foo']
provider: "{{ cli }}"
register: result
- assert:
that:
- "result.changed == true"
- "'hostname foo' in result.updates"
- name: configure top level command idempotent check
asa_config:
lines: ['hostname foo']
provider: "{{ cli }}"
register: result
- assert:
that:
- "result.changed == false"
- name: teardown
asa_config:
lines: ['hostname {{ inventory_hostname_short }}']
provider: "{{ cli }}"
- debug: msg="END cli/toplevel.yaml"

@ -1,42 +0,0 @@
---
- debug: msg="START cli/toplevel_after.yaml"
- name: setup
asa_config:
lines:
- "snmp-server contact ansible"
- "hostname firewall"
provider: "{{ cli }}"
- name: configure top level command with before
asa_config:
lines: ['hostname foo']
after: ['snmp-server contact bar']
provider: "{{ cli }}"
register: result
- assert:
that:
- "result.changed == true"
- "'hostname foo' in result.updates"
- "'snmp-server contact bar' in result.updates"
- name: configure top level command with before idempotent check
asa_config:
lines: ['hostname foo']
after: ['snmp-server contact foo']
provider: "{{ cli }}"
register: result
- assert:
that:
- "result.changed == false"
- name: teardown
asa_config:
lines:
- "no snmp-server contact"
- "hostname {{ inventory_hostname_short }}"
provider: "{{ cli }}"
- debug: msg="END cli/toplevel_after.yaml"

@ -1,42 +0,0 @@
---
- debug: msg="START cli/toplevel_before.yaml"
- name: setup
asa_config:
lines:
- "snmp-server contact ansible"
- "hostname firewall"
provider: "{{ cli }}"
- name: configure top level command with before
asa_config:
lines: ['hostname foo']
before: ['snmp-server contact bar']
provider: "{{ cli }}"
register: result
- assert:
that:
- "result.changed == true"
- "'hostname foo' in result.updates"
- "'snmp-server contact bar' in result.updates"
- name: configure top level command with before idempotent check
asa_config:
lines: ['hostname foo']
before: ['snmp-server contact foo']
provider: "{{ cli }}"
register: result
- assert:
that:
- "result.changed == false"
- name: teardown
asa_config:
lines:
- "no snmp-server contact"
- "hostname {{ inventory_hostname_short }}"
provider: "{{ cli }}"
- debug: msg="END cli/toplevel_before.yaml"

@ -1,38 +0,0 @@
---
- debug: msg="START cli/toplevel_nonidempotent.yaml"
- name: setup
asa_config:
backup: true
# lines: ['hostname firewall']
provider: "{{ cli }}"
- name: configure top level command
asa_config:
lines: ['hostname foo']
provider: "{{ cli }}"
match: strict
register: result
- assert:
that:
- "result.changed == true"
- "'hostname foo' in result.updates"
- name: configure top level command idempotent check
asa_config:
lines: ['hostname foo']
provider: "{{ cli }}"
match: strict
register: result
- assert:
that:
- "result.changed == true"
- name: teardown
asa_config:
lines: ['hostname {{ inventory_hostname_short }}']
provider: "{{ cli }}"
- debug: msg="END cli/toplevel_nonidempotent.yaml"

@ -1,22 +0,0 @@
---
- name: collect all cli test cases
find:
paths: "{{ role_path }}/tests/cli"
patterns: "{{ testcase }}.yaml"
register: test_cases
delegate_to: localhost
- name: set test_items
set_fact: test_items="{{ test_cases.files | map(attribute='path') | list }}"
- name: run test cases (connection=network_cli)
include: "{{ test_case_to_run }}"
with_items: "{{ test_items }}"
loop_control:
loop_var: test_case_to_run
- name: run test case (connection=local)
include: "{{ test_case_to_run }} ansible_connection=local"
with_first_found: "{{ test_items }}"
loop_control:
loop_var: test_case_to_run

@ -1,2 +0,0 @@
---
- { include: cli.yaml, tags: ['cli'] }

@ -1,541 +0,0 @@
---
- name: remove test config if any
asa_config:
lines:
- no object-group network ansible_test_0
- no object-group network ansible_test_1
- no object-group network ansible_test_2
- no object-group service ansible_test_3 tcp-udp
- no object-group service ansible_test_4
- no object-group service ansible_test_5
ignore_errors: true
- block:
- set_fact:
name: ansible_test_0
host_ip:
- 8.8.8.8
- 8.8.4.4
address:
- 10.0.0.0 255.0.0.0
- 192.168.0.0 255.255.0.0
- 172.16.0.0 255.255.0.0
description: th1s_IS-a_D3scrIPt10n_3xaMple-
group_object:
- aws_commonservices_eu_ie_pci_prv
- aws_commonservices_eu_ie_pci_elb_prv
- name: STAGE 0
asa_og: &config
name: "{{ name }}"
group_type: network-object
state: present
host_ip: "{{ host_ip }}"
ip_mask: "{{ address }}"
description: "{{ description }}"
group_object: "{{ group_object }}"
register: result
- assert: &true
that:
- "result.changed == true"
- name: idempotence check
asa_og: *config
register: result
- assert: &false
that:
- "result.changed == false"
- set_fact:
name: ansible_test_0
host_ip:
- 8.8.9.9
address:
- 8.8.8.0 255.255.255.0
group_object:
- test_network_object_1
- name: STAGE 1
asa_og: &config1
name: "{{ name }}"
group_type: network-object
state: present
host_ip: "{{ host_ip }}"
ip_mask: "{{ address }}"
group_object: "{{ group_object }}"
register: result
- assert: *true
- name: idempotence check
asa_og: *config1
register: result
- assert: *false
- name: STAGE 1/B
asa_og:
name: "{{ name }}"
group_type: network-object
state: present
register: result
- assert: *false
- set_fact:
name: ansible_test_1
host_ip:
- 8.8.9.9
address:
- 8.8.8.0 255.255.255.0
group_object:
- test_network_object_1
- name: STAGE 2
asa_og: &config2
name: "{{ name }}"
group_type: network-object
state: present
register: result
- assert: *true
- name: idempotence check
asa_og: *config2
register: result
- assert: *false
- name: STAGE 2b
asa_og: &config2b
name: "{{ name }}"
group_type: network-object
state: present
host_ip: "{{ host_ip }}"
ip_mask: "{{ address }}"
group_object: "{{ group_object }}"
register: result
- assert: *true
- name: idempotence check
asa_og: *config2b
register: result
- assert: *false
- set_fact:
name: ansible_test_0
host_ip:
- 8.8.8.8
- 8.8.4.4
address:
- 10.0.0.0 255.0.0.0
- 192.168.0.0 255.255.0.0
- 172.16.0.0 255.255.0.0
description: th1s_IS-a_D3scrIPt10n_3xaMple-
group_object:
- aws_commonservices_eu_ie_pci_prv
- aws_commonservices_eu_ie_pci_elb_prv
- name: STAGE 3
asa_og: &config3
name: "{{ name }}"
group_type: network-object
state: absent
host_ip: "{{ host_ip }}"
ip_mask: "{{ address }}"
description: "{{ description }}"
group_object: "{{ group_object }}"
register: result
- assert: *true
- name: idempotence check
asa_og: *config3
register: result
- assert: *false
- set_fact:
name: ansible_test_2
host_ip:
- 8.8.8.8
- 8.8.4.4
address:
- 10.0.0.0 255.0.0.0
- 192.168.0.0 255.255.0.0
- 172.16.0.0 255.255.0.0
description: th1s_IS-a_D3scrIPt10n_3xaMple-
group_object:
- aws_commonservices_eu_ie_pci_prv
- aws_commonservices_eu_ie_pci_elb_prv
- name: STAGE 4
asa_og: &config4
name: "{{ name }}"
group_type: network-object
state: replace
host_ip: "{{ host_ip }}"
ip_mask: "{{ address }}"
description: "{{ description }}"
group_object: "{{ group_object }}"
register: result
- assert: *true
- name: idempotence check
asa_og: *config4
register: result
- assert: *false
- set_fact:
name: ansible_test_2
host_ip:
- 8.8.8.8
address:
- 10.0.0.0 255.0.0.0
- 1.0.0.0 255.255.0.0
description: th1s_IS-a_D3scrIPt10n_3xaMple-
group_object:
- aws_commonservices_eu_ie_pci_prv
- name: STAGE 5
asa_og: &config5
name: "{{ name }}"
group_type: network-object
state: replace
host_ip: "{{ host_ip }}"
ip_mask: "{{ address }}"
description: "{{ description }}"
group_object: "{{ group_object }}"
register: result
- assert: *true
- name: idempotence check
asa_og: *config5
register: result
- assert: *false
- set_fact:
name: ansible_test_2
host_ip:
- 9.9.9.9
- 8.8.8.8
description: th1s_IS-a_D3scrIPt10n_3xaMple-
group_object:
- test_network_object_1
- name: STAGE 6
asa_og: &config6
name: "{{ name }}"
group_type: network-object
state: replace
host_ip: "{{ host_ip }}"
ip_mask: "{{ address }}"
description: "{{ description }}"
group_object: "{{ group_object }}"
register: result
- assert: *true
- name: idempotence check
asa_og: *config6
register: result
- assert: *false
- set_fact:
name: ansible_test_3
port_eq:
- www
- '1024'
description: th1s_IS-a_D3scrIPt10n_3xaMple-
port_range:
- '1024 10024'
- name: STAGE 7
asa_og: &config7
name: "{{ name }}"
protocol: tcp-udp
port_eq: "{{ port_eq }}"
port_range: "{{ port_range }}"
group_type: port-object
state: present
description: "{{ description }}"
register: result
- assert: *true
- name: idempotence check
asa_og: *config7
register: result
- assert: *false
- set_fact:
name: ansible_test_3
port_eq:
- talk
- '65535'
description: th1s_IS-a_D3scrIPt10n_3xaMple-
port_range:
- '1 100'
- name: STAGE 8
asa_og: &config8
name: "{{ name }}"
protocol: tcp-udp
port_eq: "{{ port_eq }}"
port_range: "{{ port_range }}"
group_type: port-object
state: present
description: "{{ description }}"
register: result
- assert: *true
- name: idempotence check
asa_og: *config8
register: result
- assert: *false
- name: STAGE 9
asa_og: &config9
name: "{{ name }}"
protocol: tcp-udp
port_eq: "{{ port_eq }}"
port_range: "{{ port_range }}"
group_type: port-object
state: absent
description: "{{ description }}"
register: result
- assert: *true
- name: idempotence check
asa_og: *config9
register: result
- assert: *false
- set_fact:
name: ansible_test_3
port_eq:
- talk
- '65535'
description: th1s_IS-a_D3scrIPt10n_3xaMple-
port_range:
- '1 100'
- name: STAGE 10
asa_og: &config10
name: "{{ name }}"
protocol: tcp-udp
port_eq: "{{ port_eq }}"
port_range: "{{ port_range }}"
group_type: port-object
state: replace
description: "{{ description }}"
register: result
- assert: *true
- name: idempotence check
asa_og: *config10
register: result
- assert: *false
- set_fact:
name: ansible_test_3
port_eq:
- talk
- www
- kerberos
description: th1s_ISWhatitIS
port_range:
- '1024 1234'
- name: STAGE 11
asa_og: &config11
name: "{{ name }}"
protocol: tcp-udp
port_eq: "{{ port_eq }}"
port_range: "{{ port_range }}"
group_type: port-object
state: replace
description: "{{ description }}"
register: result
- assert: *true
- name: idempotence check
asa_og: *config11
register: result
- assert: *false
- set_fact:
name: ansible_test_4
service_cfg:
- tcp destination eq 8080
- tcp destination eq www
description: th1s_ISWhatitIS
- name: STAGE 12
asa_og: &config12
name: "{{ name }}"
service_cfg: "{{ service_cfg }}"
group_type: service-object
state: present
description: "{{ description }}"
register: result
- assert: *true
- name: idempotence check
asa_og: *config12
register: result
- assert: *false
- set_fact:
name: ansible_test_4
service_cfg:
- tcp destination range 1234 5678
- tcp destination range 5678 6789
description: th1s_ISWhatitIS
- name: STAGE 13
asa_og: &config13
name: "{{ name }}"
service_cfg: "{{ service_cfg }}"
group_type: service-object
state: present
description: "{{ description }}"
register: result
- assert: *true
- name: idempotence check
asa_og: *config13
register: result
- assert: *false
- set_fact:
name: ansible_test_4
service_cfg:
- tcp destination range 1234 5678
- tcp destination range 5678 6789
description: th1s_ISWhatitIS
- name: STAGE 14
asa_og: &config14
name: "{{ name }}"
service_cfg: "{{ service_cfg }}"
group_type: service-object
state: absent
description: "{{ description }}"
register: result
- assert: *true
- name: idempotence check
asa_og: *config14
register: result
- assert: *false
- set_fact:
name: ansible_test_5
service_cfg:
- tcp destination range 1234 5678
- tcp destination range 5678 6789
description: th1s_ISWhatitIS
- name: STAGE 15
asa_og: &config15
name: "{{ name }}"
service_cfg: "{{ service_cfg }}"
group_type: service-object
state: replace
description: "{{ description }}"
register: result
- assert: *true
- name: idempotence check
asa_og: *config15
register: result
- assert: *false
- set_fact:
name: ansible_test_5
service_cfg:
- tcp destination range 1234 5678
- tcp destination range 5678 6789
- tcp destination eq www
description: th1s_ISWhatitIS
- name: STAGE 16
asa_og: &config16
name: "{{ name }}"
service_cfg: "{{ service_cfg }}"
group_type: service-object
state: replace
description: "{{ description }}"
register: result
- assert: *true
- name: idempotence check
asa_og: *config16
register: result
- assert: *false
- set_fact:
name: ansible_test_5
service_cfg:
- tcp destination eq 8080
description: th1s_ISWhatitIS
- name: STAGE 17
asa_og: &config17
name: "{{ name }}"
service_cfg: "{{ service_cfg }}"
group_type: service-object
state: replace
description: "{{ description }}"
register: result
- assert: *true
- name: idempotence check
asa_og: *config17
register: result
- assert: *false
always:
- name: remove test config if any
asa_config:
lines:
- no object-group network ansible_test_0
- no object-group network ansible_test_1
- no object-group network ansible_test_2
- no object-group service ansible_test_3 tcp-udp
- no object-group service ansible_test_4
- no object-group service ansible_test_5
ignore_errors: true

@ -86,8 +86,6 @@ lib/ansible/module_utils/gcp_utils.py future-import-boilerplate
lib/ansible/module_utils/gcp_utils.py metaclass-boilerplate
lib/ansible/module_utils/json_utils.py future-import-boilerplate
lib/ansible/module_utils/json_utils.py metaclass-boilerplate
lib/ansible/module_utils/network/asa/asa.py future-import-boilerplate
lib/ansible/module_utils/network/asa/asa.py metaclass-boilerplate
lib/ansible/module_utils/network/dellos10/dellos10.py future-import-boilerplate
lib/ansible/module_utils/network/dellos10/dellos10.py metaclass-boilerplate
lib/ansible/module_utils/network/dellos6/dellos6.py future-import-boilerplate
@ -1516,27 +1514,6 @@ lib/ansible/modules/network/aci/mso_tenant.py validate-modules:doc-required-mism
lib/ansible/modules/network/aci/mso_tenant.py validate-modules:parameter-list-no-elements
lib/ansible/modules/network/aci/mso_user.py validate-modules:doc-required-mismatch
lib/ansible/modules/network/aci/mso_user.py validate-modules:parameter-list-no-elements
lib/ansible/modules/network/asa/asa_acl.py validate-modules:doc-default-does-not-match-spec
lib/ansible/modules/network/asa/asa_acl.py validate-modules:doc-missing-type
lib/ansible/modules/network/asa/asa_acl.py validate-modules:parameter-list-no-elements
lib/ansible/modules/network/asa/asa_acl.py validate-modules:parameter-type-not-in-doc
lib/ansible/modules/network/asa/asa_acl.py validate-modules:undocumented-parameter
lib/ansible/modules/network/asa/asa_acl.py yamllint:unparsable-with-libyaml
lib/ansible/modules/network/asa/asa_command.py validate-modules:doc-default-does-not-match-spec
lib/ansible/modules/network/asa/asa_command.py validate-modules:doc-missing-type
lib/ansible/modules/network/asa/asa_command.py validate-modules:parameter-list-no-elements
lib/ansible/modules/network/asa/asa_command.py validate-modules:parameter-type-not-in-doc
lib/ansible/modules/network/asa/asa_command.py validate-modules:undocumented-parameter
lib/ansible/modules/network/asa/asa_config.py validate-modules:doc-default-does-not-match-spec
lib/ansible/modules/network/asa/asa_config.py validate-modules:doc-missing-type
lib/ansible/modules/network/asa/asa_config.py validate-modules:implied-parameter-type-mismatch
lib/ansible/modules/network/asa/asa_config.py validate-modules:parameter-list-no-elements
lib/ansible/modules/network/asa/asa_config.py validate-modules:parameter-type-not-in-doc
lib/ansible/modules/network/asa/asa_config.py validate-modules:undocumented-parameter
lib/ansible/modules/network/asa/asa_config.py yamllint:unparsable-with-libyaml
lib/ansible/modules/network/asa/asa_og.py validate-modules:doc-missing-type
lib/ansible/modules/network/asa/asa_og.py validate-modules:parameter-list-no-elements
lib/ansible/modules/network/asa/asa_og.py validate-modules:parameter-type-not-in-doc
lib/ansible/modules/network/dellos10/dellos10_command.py validate-modules:doc-default-does-not-match-spec
lib/ansible/modules/network/dellos10/dellos10_command.py validate-modules:doc-missing-type
lib/ansible/modules/network/dellos10/dellos10_command.py validate-modules:doc-required-mismatch
@ -3151,7 +3128,6 @@ lib/ansible/playbook/base.py pylint:blacklisted-name
lib/ansible/playbook/collectionsearch.py required-and-default-attributes # https://github.com/ansible/ansible/issues/61460
lib/ansible/playbook/helpers.py pylint:blacklisted-name
lib/ansible/playbook/role/__init__.py pylint:blacklisted-name
lib/ansible/plugins/action/asa.py action-plugin-docs # base class for deprecated network platform modules using `connection: local`
lib/ansible/plugins/action/bigip.py action-plugin-docs # undocumented action plugin to fix, existed before sanity test was added
lib/ansible/plugins/action/bigiq.py action-plugin-docs # undocumented action plugin to fix, existed before sanity test was added
lib/ansible/plugins/action/dellos10.py action-plugin-docs # base class for deprecated network platform modules using `connection: local`
@ -3164,8 +3140,6 @@ lib/ansible/plugins/action/normal.py action-plugin-docs # default action plugin
lib/ansible/plugins/action/nxos.py action-plugin-docs # base class for deprecated network platform modules using `connection: local`
lib/ansible/plugins/action/vyos.py action-plugin-docs # base class for deprecated network platform modules using `connection: local`
lib/ansible/plugins/cache/base.py ansible-doc!skip # not a plugin, but a stub for backwards compatibility
lib/ansible/plugins/doc_fragments/asa.py future-import-boilerplate
lib/ansible/plugins/doc_fragments/asa.py metaclass-boilerplate
lib/ansible/plugins/doc_fragments/azure.py future-import-boilerplate
lib/ansible/plugins/doc_fragments/azure.py metaclass-boilerplate
lib/ansible/plugins/doc_fragments/azure_tags.py future-import-boilerplate

@ -1,76 +0,0 @@
# -*- coding: utf-8 -*-
# (c) 2019, Ansible by Red Hat, inc
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import json
from units.modules.utils import AnsibleExitJson, AnsibleFailJson, ModuleTestCase
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 TestAsaModule(ModuleTestCase):
def execute_module(self, failed=False, changed=False, commands=None, sort=True, defaults=False):
self.load_fixtures(commands)
if failed:
result = self.failed()
self.assertTrue(result['failed'], result)
else:
result = self.changed(changed)
self.assertEqual(result['changed'], changed, result)
if commands is not None:
if sort:
self.assertEqual(sorted(commands), sorted(result['commands']), result['commands'])
else:
self.assertEqual(commands, result['commands'], result['commands'])
return result
def failed(self):
with self.assertRaises(AnsibleFailJson) as exc:
self.module.main()
result = exc.exception.args[0]
self.assertTrue(result['failed'], result)
return result
def changed(self, changed=False):
with self.assertRaises(AnsibleExitJson) as exc:
self.module.main()
result = exc.exception.args[0]
self.assertEqual(result['changed'], changed, result)
return result
def load_fixtures(self, commands=None):
pass

@ -1,5 +0,0 @@
object-group network test_nets
description ansible_test object-group description
network-object host 8.8.8.8
network-object 192.168.0.0 255.255.0.0
group-object awx_lon

@ -1,107 +0,0 @@
# -*- coding: utf-8 -*-
# (c) 2019, Ansible by Red Hat, inc
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from units.compat.mock import patch
from ansible.modules.network.asa import asa_og
from units.modules.utils import set_module_args
from .asa_module import TestAsaModule, load_fixture
class TestAsaOgModule(TestAsaModule):
module = asa_og
def setUp(self):
super(TestAsaOgModule, self).setUp()
self.mock_get_config = patch('ansible.modules.network.asa.asa_og.get_config')
self.get_config = self.mock_get_config.start()
self.mock_load_config = patch('ansible.modules.network.asa.asa_og.load_config')
self.load_config = self.mock_load_config.start()
self.mock_get_connection = patch('ansible.module_utils.network.asa.asa.get_connection')
self.get_connection = self.mock_get_connection.start()
def tearDown(self):
super(TestAsaOgModule, self).tearDown()
self.mock_get_config.stop()
self.mock_load_config.stop()
def load_fixtures(self, commands=None):
self.get_config.return_value = load_fixture('asa_og_config.cfg').strip()
self.load_config.return_value = dict(diff=None, session='session')
def test_asa_og_idempotent(self):
set_module_args(dict(
name='test_nets',
group_type='network-object',
host_ip=['8.8.8.8'],
ip_mask=['192.168.0.0 255.255.0.0'],
group_object=['awx_lon'],
description='ansible_test object-group description',
state='present'
))
commands = []
self.execute_module(changed=False, commands=commands)
def test_asa_og_add(self):
set_module_args(dict(
name='test_nets',
group_type='network-object',
host_ip=['8.8.8.8', '8.8.4.4'],
ip_mask=['192.168.0.0 255.255.0.0', '10.0.0.0 255.255.255.0'],
group_object=['awx_lon', 'awx_ams'],
description='ansible_test object-group description',
state='present'
))
commands = [
'object-group network test_nets',
'network-object host 8.8.4.4',
'network-object 10.0.0.0 255.255.255.0',
'group-object awx_ams'
]
self.execute_module(changed=True, commands=commands)
def test_asa_og_replace(self):
set_module_args(dict(
name='test_nets',
group_type='network-object',
host_ip=['8.8.4.4'],
ip_mask=['10.0.0.0 255.255.255.0'],
group_object=['awx_ams'],
description='ansible_test custom description',
state='replace'
))
commands = [
'object-group network test_nets',
'description ansible_test custom description',
'no network-object host 8.8.8.8',
'network-object host 8.8.4.4',
'no network-object 192.168.0.0 255.255.0.0',
'network-object 10.0.0.0 255.255.255.0',
'no group-object awx_lon',
'group-object awx_ams'
]
self.execute_module(changed=True, commands=commands)
def test_asa_og_remove(self):
set_module_args(dict(
name='test_nets',
group_type='network-object',
host_ip=['8.8.8.8'],
group_object=['awx_lon'],
state='absent'
))
commands = [
'object-group network test_nets',
'no network-object host 8.8.8.8',
'no group-object awx_lon'
]
self.execute_module(changed=True, commands=commands)
Loading…
Cancel
Save