ACI/MSO: Use get() dict lookups (#63074)

This improves the reliability of the modules somewhat.
This commit is contained in:
Dag Wieers 2019-11-06 18:24:11 +01:00 committed by GitHub
parent 1f5d2f9159
commit 26e0e4be01
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
102 changed files with 1138 additions and 1140 deletions

View file

@ -121,13 +121,13 @@ class ACIModule(object):
self.module.warn('Enable debug output because ANSIBLE_DEBUG was set.') self.module.warn('Enable debug output because ANSIBLE_DEBUG was set.')
self.params['output_level'] = 'debug' self.params['output_level'] = 'debug'
if self.params['private_key']: if self.params.get('private_key'):
# Perform signature-based authentication, no need to log on separately # Perform signature-based authentication, no need to log on separately
if not HAS_OPENSSL: if not HAS_OPENSSL:
self.module.fail_json(msg='Cannot use signature-based authentication because pyopenssl is not available') self.module.fail_json(msg='Cannot use signature-based authentication because pyopenssl is not available')
elif self.params['password'] is not None: elif self.params.get('password') is not None:
self.module.warn("When doing ACI signatured-based authentication, providing parameter 'password' is not required") self.module.warn("When doing ACI signatured-based authentication, providing parameter 'password' is not required")
elif self.params['password']: elif self.params.get('password'):
# Perform password-based authentication, log on using password # Perform password-based authentication, log on using password
self.login() self.login()
else: else:
@ -166,27 +166,27 @@ class ACIModule(object):
# Set method for further use # Set method for further use
state_map = dict(absent='delete', present='post', query='get') state_map = dict(absent='delete', present='post', query='get')
self.params['method'] = state_map[self.params['state']] self.params['method'] = state_map.get(self.params.get('state'))
def login(self): def login(self):
''' Log in to APIC ''' ''' Log in to APIC '''
# Perform login request # Perform login request
if 'port' in self.params and self.params['port'] is not None: if self.params.get('port') is not None:
url = '%(protocol)s://%(host)s:%(port)s/api/aaaLogin.json' % self.params url = '%(protocol)s://%(host)s:%(port)s/api/aaaLogin.json' % self.params
else: else:
url = '%(protocol)s://%(host)s/api/aaaLogin.json' % self.params url = '%(protocol)s://%(host)s/api/aaaLogin.json' % self.params
payload = {'aaaUser': {'attributes': {'name': self.params['username'], 'pwd': self.params['password']}}} payload = {'aaaUser': {'attributes': {'name': self.params.get('username'), 'pwd': self.params.get('password')}}}
resp, auth = fetch_url(self.module, url, resp, auth = fetch_url(self.module, url,
data=json.dumps(payload), data=json.dumps(payload),
method='POST', method='POST',
timeout=self.params['timeout'], timeout=self.params.get('timeout'),
use_proxy=self.params['use_proxy']) use_proxy=self.params.get('use_proxy'))
# Handle APIC response # Handle APIC response
if auth['status'] != 200: if auth.get('status') != 200:
self.response = auth['msg'] self.response = auth.get('msg')
self.status = auth['status'] self.status = auth.get('status')
try: try:
# APIC error # APIC error
self.response_json(auth['body']) self.response_json(auth['body'])
@ -196,13 +196,13 @@ class ACIModule(object):
self.fail_json(msg='Connection failed for %(url)s. %(msg)s' % auth) self.fail_json(msg='Connection failed for %(url)s. %(msg)s' % auth)
# Retain cookie for later use # Retain cookie for later use
self.headers['Cookie'] = resp.headers['Set-Cookie'] self.headers['Cookie'] = resp.headers.get('Set-Cookie')
def cert_auth(self, path=None, payload='', method=None): def cert_auth(self, path=None, payload='', method=None):
''' Perform APIC signature-based authentication, not the expected SSL client certificate authentication. ''' ''' Perform APIC signature-based authentication, not the expected SSL client certificate authentication. '''
if method is None: if method is None:
method = self.params['method'].upper() method = self.params.get('method').upper()
# NOTE: ACI documentation incorrectly uses complete URL # NOTE: ACI documentation incorrectly uses complete URL
if path is None: if path is None:
@ -213,43 +213,43 @@ class ACIModule(object):
payload = '' payload = ''
# Check if we got a private key. This allows the use of vaulting the private key. # Check if we got a private key. This allows the use of vaulting the private key.
if self.params['private_key'].startswith('-----BEGIN PRIVATE KEY-----'): if self.params.get('private_key').startswith('-----BEGIN PRIVATE KEY-----'):
try: try:
sig_key = load_privatekey(FILETYPE_PEM, self.params['private_key']) sig_key = load_privatekey(FILETYPE_PEM, self.params.get('private_key'))
except Exception: except Exception:
self.module.fail_json(msg="Cannot load provided 'private_key' parameter.") self.module.fail_json(msg="Cannot load provided 'private_key' parameter.")
# Use the username as the certificate_name value # Use the username as the certificate_name value
if self.params['certificate_name'] is None: if self.params.get('certificate_name') is None:
self.params['certificate_name'] = self.params['username'] self.params['certificate_name'] = self.params.get('username')
elif self.params['private_key'].startswith('-----BEGIN CERTIFICATE-----'): elif self.params.get('private_key').startswith('-----BEGIN CERTIFICATE-----'):
self.module.fail_json(msg="Provided 'private_key' parameter value appears to be a certificate. Please correct.") self.module.fail_json(msg="Provided 'private_key' parameter value appears to be a certificate.")
else: else:
# If we got a private key file, read from this file. # If we got a private key file, read from this file.
# NOTE: Avoid exposing any other credential as a filename in output... # NOTE: Avoid exposing any other credential as a filename in output...
if not os.path.exists(self.params['private_key']): if not os.path.exists(self.params.get('private_key')):
self.module.fail_json(msg="The provided private key file does not appear to exist. Is it a filename?") self.module.fail_json(msg="The provided private key file does not appear to exist. Is it a filename?")
try: try:
with open(self.params['private_key'], 'r') as fh: with open(self.params.get('private_key'), 'r') as fh:
private_key_content = fh.read() private_key_content = fh.read()
except Exception: except Exception:
self.module.fail_json(msg="Cannot open private key file '%s'." % self.params['private_key']) self.module.fail_json(msg="Cannot open private key file '%(private_key)s'." % self.params)
if private_key_content.startswith('-----BEGIN PRIVATE KEY-----'): if private_key_content.startswith('-----BEGIN PRIVATE KEY-----'):
try: try:
sig_key = load_privatekey(FILETYPE_PEM, private_key_content) sig_key = load_privatekey(FILETYPE_PEM, private_key_content)
except Exception: except Exception:
self.module.fail_json(msg="Cannot load private key file '%s'." % self.params['private_key']) self.module.fail_json(msg="Cannot load private key file '%(private_key)s'." % self.params)
# Use the private key basename (without extension) as certificate_name # Use the private key basename (without extension) as certificate_name
if self.params['certificate_name'] is None: if self.params.get('certificate_name') is None:
self.params['certificate_name'] = os.path.basename(os.path.splitext(self.params['private_key'])[0]) self.params['certificate_name'] = os.path.basename(os.path.splitext(self.params.get('private_key'))[0])
elif private_key_content.startswith('-----BEGIN CERTIFICATE-----'): elif private_key_content.startswith('-----BEGIN CERTIFICATE-----'):
self.module.fail_json(msg="Provided private key file %s appears to be a certificate. Please correct." % self.params['private_key']) self.module.fail_json(msg="Provided private key file '%(private_key)s' appears to be a certificate." % self.params)
else: else:
self.module.fail_json(msg="Provided private key file '%s' does not appear to be a private key. Please correct." % self.params['private_key']) self.module.fail_json(msg="Provided private key file '%(private_key)s' does not appear to be a private key." % self.params)
# NOTE: ACI documentation incorrectly adds a space between method and path # NOTE: ACI documentation incorrectly adds a space between method and path
sig_request = method + path + payload sig_request = method + path + payload
sig_signature = base64.b64encode(sign(sig_key, sig_request, 'sha256')) sig_signature = base64.b64encode(sign(sig_key, sig_request, 'sha256'))
sig_dn = 'uni/userext/user-%s/usercert-%s' % (self.params['username'], self.params['certificate_name']) sig_dn = 'uni/userext/user-%(username)s/usercert-%(certificate_name)s' % self.params
self.headers['Cookie'] = 'APIC-Certificate-Algorithm=v1.0; ' +\ self.headers['Cookie'] = 'APIC-Certificate-Algorithm=v1.0; ' +\
'APIC-Certificate-DN=%s; ' % sig_dn +\ 'APIC-Certificate-DN=%s; ' % sig_dn +\
'APIC-Certificate-Fingerprint=fingerprint; ' +\ 'APIC-Certificate-Fingerprint=fingerprint; ' +\
@ -266,11 +266,10 @@ class ACIModule(object):
return return
# Extract JSON API output # Extract JSON API output
try: self.imdata = jsondata.get('imdata')
self.imdata = jsondata['imdata'] if self.imdata is None:
except KeyError:
self.imdata = dict() self.imdata = dict()
self.totalCount = int(jsondata['totalCount']) self.totalCount = int(jsondata.get('totalCount'))
# Handle possible APIC error information # Handle possible APIC error information
self.response_error() self.response_error()
@ -289,11 +288,10 @@ class ACIModule(object):
return return
# Reformat as ACI does for JSON API output # Reformat as ACI does for JSON API output
try: self.imdata = xmldata.get('imdata', {}).get('children')
self.imdata = xmldata['imdata']['children'] if self.imdata is None:
except KeyError:
self.imdata = dict() self.imdata = dict()
self.totalCount = int(xmldata['imdata']['attributes']['totalCount']) self.totalCount = int(xmldata.get('imdata', {}).get('attributes', {}).get('totalCount'))
# Handle possible APIC error information # Handle possible APIC error information
self.response_error() self.response_error()
@ -304,8 +302,8 @@ class ACIModule(object):
# Handle possible APIC error information # Handle possible APIC error information
if self.totalCount != '0': if self.totalCount != '0':
try: try:
self.error = self.imdata[0]['error']['attributes'] self.error = self.imdata[0].get('error').get('attributes')
except (KeyError, IndexError): except (AttributeError, IndexError, KeyError):
pass pass
def request(self, path, payload=None): def request(self, path, payload=None):
@ -315,28 +313,28 @@ class ACIModule(object):
self.define_method() self.define_method()
self.path = path self.path = path
if 'port' in self.params and self.params['port'] is not None: if self.params.get('port') is not None:
self.url = '%(protocol)s://%(host)s:%(port)s/' % self.params + path.lstrip('/') self.url = '%(protocol)s://%(host)s:%(port)s/' % self.params + path.lstrip('/')
else: else:
self.url = '%(protocol)s://%(host)s/' % self.params + path.lstrip('/') self.url = '%(protocol)s://%(host)s/' % self.params + path.lstrip('/')
# Sign and encode request as to APIC's wishes # Sign and encode request as to APIC's wishes
if self.params['private_key']: if self.params.get('private_key'):
self.cert_auth(path=path, payload=payload) self.cert_auth(path=path, payload=payload)
# Perform request # Perform request
resp, info = fetch_url(self.module, self.url, resp, info = fetch_url(self.module, self.url,
data=payload, data=payload,
headers=self.headers, headers=self.headers,
method=self.params['method'].upper(), method=self.params.get('method').upper(),
timeout=self.params['timeout'], timeout=self.params.get('timeout'),
use_proxy=self.params['use_proxy']) use_proxy=self.params.get('use_proxy'))
self.response = info['msg'] self.response = info.get('msg')
self.status = info['status'] self.status = info.get('status')
# Handle APIC response # Handle APIC response
if info['status'] != 200: if info.get('status') != 200:
try: try:
# APIC error # APIC error
self.response_json(info['body']) self.response_json(info['body'])
@ -352,13 +350,13 @@ class ACIModule(object):
self.path = path self.path = path
if 'port' in self.params and self.params['port'] is not None: if self.params.get('port') is not None:
self.url = '%(protocol)s://%(host)s:%(port)s/' % self.params + path.lstrip('/') self.url = '%(protocol)s://%(host)s:%(port)s/' % self.params + path.lstrip('/')
else: else:
self.url = '%(protocol)s://%(host)s/' % self.params + path.lstrip('/') self.url = '%(protocol)s://%(host)s/' % self.params + path.lstrip('/')
# Sign and encode request as to APIC's wishes # Sign and encode request as to APIC's wishes
if self.params['private_key']: if self.params.get('private_key'):
self.cert_auth(path=path, method='GET') self.cert_auth(path=path, method='GET')
# Perform request # Perform request
@ -366,13 +364,13 @@ class ACIModule(object):
data=None, data=None,
headers=self.headers, headers=self.headers,
method='GET', method='GET',
timeout=self.params['timeout'], timeout=self.params.get('timeout'),
use_proxy=self.params['use_proxy']) use_proxy=self.params.get('use_proxy'))
# Handle APIC response # Handle APIC response
if query['status'] != 200: if query.get('status') != 200:
self.response = query['msg'] self.response = query.get('msg')
self.status = query['status'] self.status = query.get('status')
try: try:
# APIC error # APIC error
self.response_json(query['body']) self.response_json(query['body'])
@ -383,7 +381,7 @@ class ACIModule(object):
query = json.loads(resp.read()) query = json.loads(resp.read())
return json.dumps(query['imdata'], sort_keys=True, indent=2) + '\n' return json.dumps(query.get('imdata'), sort_keys=True, indent=2) + '\n'
def request_diff(self, path, payload=None): def request_diff(self, path, payload=None):
''' Perform a request, including a proper diff output ''' ''' Perform a request, including a proper diff output '''
@ -393,7 +391,7 @@ class ACIModule(object):
# TODO: Check if we can use the request output for the 'after' diff # TODO: Check if we can use the request output for the 'after' diff
self.result['diff']['after'] = self.query(path) self.result['diff']['after'] = self.query(path)
if self.result['diff']['before'] != self.result['diff']['after']: if self.result.get('diff', {}).get('before') != self.result.get('diff', {}).get('after'):
self.result['changed'] = True self.result['changed'] = True
# TODO: This could be designed to update existing keys # TODO: This could be designed to update existing keys
@ -417,16 +415,16 @@ class ACIModule(object):
return 'and(' + ','.join(['eq({0}.{1},"{2}")'.format(obj_class, k, v) for (k, v) in accepted_params.items()]) + ')' return 'and(' + ','.join(['eq({0}.{1},"{2}")'.format(obj_class, k, v) for (k, v) in accepted_params.items()]) + ')'
def _deep_url_path_builder(self, obj): def _deep_url_path_builder(self, obj):
target_class = obj['target_class'] target_class = obj.get('target_class')
target_filter = obj['target_filter'] target_filter = obj.get('target_filter')
subtree_class = obj['subtree_class'] subtree_class = obj.get('subtree_class')
subtree_filter = obj['subtree_filter'] subtree_filter = obj.get('subtree_filter')
object_rn = obj['object_rn'] object_rn = obj.get('object_rn')
mo = obj['module_object'] mo = obj.get('module_object')
add_subtree_filter = obj['add_subtree_filter'] add_subtree_filter = obj.get('add_subtree_filter')
add_target_filter = obj['add_target_filter'] add_target_filter = obj.get('add_target_filter')
if self.module.params['state'] in ('absent', 'present') and mo is not None: if self.module.params.get('state') in ('absent', 'present') and mo is not None:
self.path = 'api/mo/uni/{0}.json'.format(object_rn) self.path = 'api/mo/uni/{0}.json'.format(object_rn)
self.update_qs({'rsp-prop-include': 'config-only'}) self.update_qs({'rsp-prop-include': 'config-only'})
@ -446,7 +444,7 @@ class ACIModule(object):
self.update_qs( self.update_qs(
{'rsp-subtree-filter': self.build_filter(subtree_class, subtree_filter)}) {'rsp-subtree-filter': self.build_filter(subtree_class, subtree_filter)})
if 'port' in self.params and self.params['port'] is not None: if self.params.get('port') is not None:
self.url = '{protocol}://{host}:{port}/{path}'.format( self.url = '{protocol}://{host}:{port}/{path}'.format(
path=self.path, **self.module.params) path=self.path, **self.module.params)
@ -461,7 +459,7 @@ class ACIModule(object):
def _deep_url_parent_object(self, parent_objects, parent_class): def _deep_url_parent_object(self, parent_objects, parent_class):
for parent_object in parent_objects: for parent_object in parent_objects:
if parent_object['aci_class'] is parent_class: if parent_object.get('aci_class') is parent_class:
return parent_object return parent_object
return None return None
@ -494,11 +492,11 @@ class ACIModule(object):
else: else:
self.child_classes = set(child_classes) self.child_classes = set(child_classes)
target_parent_class = target_object['parent_class'] target_parent_class = target_object.get('parent_class')
target_class = target_object['aci_class'] target_class = target_object.get('aci_class')
target_rn = target_object['aci_rn'] target_rn = target_object.get('aci_rn')
target_filter = target_object['target_filter'] target_filter = target_object.get('target_filter')
target_module_object = target_object['module_object'] target_module_object = target_object.get('module_object')
url_path_object = dict( url_path_object = dict(
target_class=target_class, target_class=target_class,
@ -527,11 +525,11 @@ class ACIModule(object):
parent_objects=parent_objects, parent_class=current_parent_class) parent_objects=parent_objects, parent_class=current_parent_class)
if parent_object is not None: if parent_object is not None:
parent_parent_class = parent_object['parent_class'] parent_parent_class = parent_object.get('parent_class')
parent_class = parent_object['aci_class'] parent_class = parent_object.get('aci_class')
parent_rn = parent_object['aci_rn'] parent_rn = parent_object.get('aci_rn')
parent_filter = parent_object['target_filter'] parent_filter = parent_object.get('target_filter')
parent_module_object = parent_object['module_object'] parent_module_object = parent_object.get('module_object')
if is_first_parent: if is_first_parent:
is_single_parent = True is_single_parent = True
@ -544,8 +542,7 @@ class ACIModule(object):
if parent_module_object is not None: if parent_module_object is not None:
if rn_builder is not None: if rn_builder is not None:
rn_builder = '{0}/{1}'.format(parent_rn, rn_builder = '{0}/{1}'.format(parent_rn, rn_builder)
rn_builder)
else: else:
rn_builder = parent_rn rn_builder = parent_rn
@ -631,7 +628,7 @@ class ACIModule(object):
else: else:
self._construct_url_1(root_class) self._construct_url_1(root_class)
if 'port' in self.params and self.params['port'] is not None: if self.params.get('port') is not None:
self.url = '{protocol}://{host}:{port}/{path}'.format(path=self.path, **self.module.params) self.url = '{protocol}://{host}:{port}/{path}'.format(path=self.path, **self.module.params)
else: else:
self.url = '{protocol}://{host}/{path}'.format(path=self.path, **self.module.params) self.url = '{protocol}://{host}/{path}'.format(path=self.path, **self.module.params)
@ -644,12 +641,12 @@ class ACIModule(object):
""" """
This method is used by construct_url when the object is the top-level class. This method is used by construct_url when the object is the top-level class.
""" """
obj_class = obj['aci_class'] obj_class = obj.get('aci_class')
obj_rn = obj['aci_rn'] obj_rn = obj.get('aci_rn')
obj_filter = obj['target_filter'] obj_filter = obj.get('target_filter')
mo = obj['module_object'] mo = obj.get('module_object')
if self.module.params['state'] in ('absent', 'present'): if self.module.params.get('state') in ('absent', 'present'):
# State is absent or present # State is absent or present
self.path = 'api/mo/uni/{0}.json'.format(obj_rn) self.path = 'api/mo/uni/{0}.json'.format(obj_rn)
self.update_qs({'rsp-prop-include': 'config-only'}) self.update_qs({'rsp-prop-include': 'config-only'})
@ -665,16 +662,16 @@ class ACIModule(object):
""" """
This method is used by construct_url when the object is the second-level class. This method is used by construct_url when the object is the second-level class.
""" """
parent_class = parent['aci_class'] parent_class = parent.get('aci_class')
parent_rn = parent['aci_rn'] parent_rn = parent.get('aci_rn')
parent_filter = parent['target_filter'] parent_filter = parent.get('target_filter')
parent_obj = parent['module_object'] parent_obj = parent.get('module_object')
obj_class = obj['aci_class'] obj_class = obj.get('aci_class')
obj_rn = obj['aci_rn'] obj_rn = obj.get('aci_rn')
obj_filter = obj['target_filter'] obj_filter = obj.get('target_filter')
mo = obj['module_object'] mo = obj.get('module_object')
if self.module.params['state'] in ('absent', 'present'): if self.module.params.get('state') in ('absent', 'present'):
# State is absent or present # State is absent or present
self.path = 'api/mo/uni/{0}/{1}.json'.format(parent_rn, obj_rn) self.path = 'api/mo/uni/{0}/{1}.json'.format(parent_rn, obj_rn)
self.update_qs({'rsp-prop-include': 'config-only'}) self.update_qs({'rsp-prop-include': 'config-only'})
@ -698,20 +695,20 @@ class ACIModule(object):
""" """
This method is used by construct_url when the object is the third-level class. This method is used by construct_url when the object is the third-level class.
""" """
root_class = root['aci_class'] root_class = root.get('aci_class')
root_rn = root['aci_rn'] root_rn = root.get('aci_rn')
root_filter = root['target_filter'] root_filter = root.get('target_filter')
root_obj = root['module_object'] root_obj = root.get('module_object')
parent_class = parent['aci_class'] parent_class = parent.get('aci_class')
parent_rn = parent['aci_rn'] parent_rn = parent.get('aci_rn')
parent_filter = parent['target_filter'] parent_filter = parent.get('target_filter')
parent_obj = parent['module_object'] parent_obj = parent.get('module_object')
obj_class = obj['aci_class'] obj_class = obj.get('aci_class')
obj_rn = obj['aci_rn'] obj_rn = obj.get('aci_rn')
obj_filter = obj['target_filter'] obj_filter = obj.get('target_filter')
mo = obj['module_object'] mo = obj.get('module_object')
if self.module.params['state'] in ('absent', 'present'): if self.module.params.get('state') in ('absent', 'present'):
# State is absent or present # State is absent or present
self.path = 'api/mo/uni/{0}/{1}/{2}.json'.format(root_rn, parent_rn, obj_rn) self.path = 'api/mo/uni/{0}/{1}/{2}.json'.format(root_rn, parent_rn, obj_rn)
self.update_qs({'rsp-prop-include': 'config-only'}) self.update_qs({'rsp-prop-include': 'config-only'})
@ -764,27 +761,27 @@ class ACIModule(object):
""" """
This method is used by construct_url when the object is the fourth-level class. This method is used by construct_url when the object is the fourth-level class.
""" """
root_class = root['aci_class'] root_class = root.get('aci_class')
root_rn = root['aci_rn'] root_rn = root.get('aci_rn')
root_filter = root['target_filter'] root_filter = root.get('target_filter')
root_obj = root['module_object'] root_obj = root.get('module_object')
sec_class = sec['aci_class'] sec_class = sec.get('aci_class')
sec_rn = sec['aci_rn'] sec_rn = sec.get('aci_rn')
sec_filter = sec['target_filter'] sec_filter = sec.get('target_filter')
sec_obj = sec['module_object'] sec_obj = sec.get('module_object')
parent_class = parent['aci_class'] parent_class = parent.get('aci_class')
parent_rn = parent['aci_rn'] parent_rn = parent.get('aci_rn')
parent_filter = parent['target_filter'] parent_filter = parent.get('target_filter')
parent_obj = parent['module_object'] parent_obj = parent.get('module_object')
obj_class = obj['aci_class'] obj_class = obj.get('aci_class')
obj_rn = obj['aci_rn'] obj_rn = obj.get('aci_rn')
obj_filter = obj['target_filter'] obj_filter = obj.get('target_filter')
mo = obj['module_object'] mo = obj.get('module_object')
if self.child_classes is None: if self.child_classes is None:
self.child_classes = [obj_class] self.child_classes = [obj_class]
if self.module.params['state'] in ('absent', 'present'): if self.module.params.get('state') in ('absent', 'present'):
# State is absent or present # State is absent or present
self.path = 'api/mo/uni/{0}/{1}/{2}/{3}.json'.format(root_rn, sec_rn, parent_rn, obj_rn) self.path = 'api/mo/uni/{0}/{1}/{2}/{3}.json'.format(root_rn, sec_rn, parent_rn, obj_rn)
self.update_qs({'rsp-prop-include': 'config-only'}) self.update_qs({'rsp-prop-include': 'config-only'})
@ -834,15 +831,15 @@ class ACIModule(object):
resp, info = fetch_url(self.module, self.url, resp, info = fetch_url(self.module, self.url,
headers=self.headers, headers=self.headers,
method='DELETE', method='DELETE',
timeout=self.params['timeout'], timeout=self.params.get('timeout'),
use_proxy=self.params['use_proxy']) use_proxy=self.params.get('use_proxy'))
self.response = info['msg'] self.response = info.get('msg')
self.status = info['status'] self.status = info.get('status')
self.method = 'DELETE' self.method = 'DELETE'
# Handle APIC response # Handle APIC response
if info['status'] == 200: if info.get('status') == 200:
self.result['changed'] = True self.result['changed'] = True
self.response_json(resp.read()) self.response_json(resp.read())
else: else:
@ -880,7 +877,7 @@ class ACIModule(object):
# add name back to config only if the configs do not match # add name back to config only if the configs do not match
if config: if config:
# TODO: If URLs are built with the object's name, then we should be able to leave off adding the name back # TODO: If URLs are built with the object's name, then we should be able to leave off adding the name back
# config["name"] = proposed_config["name"] # config['name'] = proposed_config.get('name')
config = {aci_class: {'attributes': config}} config = {aci_class: {'attributes': config}}
# check for updates to child configs and update new config dictionary # check for updates to child configs and update new config dictionary
@ -964,20 +961,20 @@ class ACIModule(object):
uri = self.url + self.filter_string uri = self.url + self.filter_string
# Sign and encode request as to APIC's wishes # Sign and encode request as to APIC's wishes
if self.params['private_key']: if self.params.get('private_key'):
self.cert_auth(path=self.path + self.filter_string, method='GET') self.cert_auth(path=self.path + self.filter_string, method='GET')
resp, info = fetch_url(self.module, uri, resp, info = fetch_url(self.module, uri,
headers=self.headers, headers=self.headers,
method='GET', method='GET',
timeout=self.params['timeout'], timeout=self.params.get('timeout'),
use_proxy=self.params['use_proxy']) use_proxy=self.params.get('use_proxy'))
self.response = info['msg'] self.response = info.get('msg')
self.status = info['status'] self.status = info.get('status')
self.method = 'GET' self.method = 'GET'
# Handle APIC response # Handle APIC response
if info['status'] == 200: if info.get('status') == 200:
self.existing = json.loads(resp.read())['imdata'] self.existing = json.loads(resp.read())['imdata']
else: else:
try: try:
@ -1065,22 +1062,22 @@ class ACIModule(object):
return return
elif not self.module.check_mode: elif not self.module.check_mode:
# Sign and encode request as to APIC's wishes # Sign and encode request as to APIC's wishes
if self.params['private_key']: if self.params.get('private_key'):
self.cert_auth(method='POST', payload=json.dumps(self.config)) self.cert_auth(method='POST', payload=json.dumps(self.config))
resp, info = fetch_url(self.module, self.url, resp, info = fetch_url(self.module, self.url,
data=json.dumps(self.config), data=json.dumps(self.config),
headers=self.headers, headers=self.headers,
method='POST', method='POST',
timeout=self.params['timeout'], timeout=self.params.get('timeout'),
use_proxy=self.params['use_proxy']) use_proxy=self.params.get('use_proxy'))
self.response = info['msg'] self.response = info.get('msg')
self.status = info['status'] self.status = info.get('status')
self.method = 'POST' self.method = 'POST'
# Handle APIC response # Handle APIC response
if info['status'] == 200: if info.get('status') == 200:
self.result['changed'] = True self.result['changed'] = True
self.response_json(resp.read()) self.response_json(resp.read())
else: else:
@ -1098,12 +1095,12 @@ class ACIModule(object):
def exit_json(self, **kwargs): def exit_json(self, **kwargs):
if 'state' in self.params: if 'state' in self.params:
if self.params['state'] in ('absent', 'present'): if self.params.get('state') in ('absent', 'present'):
if self.params['output_level'] in ('debug', 'info'): if self.params.get('output_level') in ('debug', 'info'):
self.result['previous'] = self.existing self.result['previous'] = self.existing
# Return the gory details when we need it # Return the gory details when we need it
if self.params['output_level'] == 'debug': if self.params.get('output_level') == 'debug':
if 'state' in self.params: if 'state' in self.params:
self.result['filter_string'] = self.filter_string self.result['filter_string'] = self.filter_string
self.result['method'] = self.method self.result['method'] = self.method
@ -1114,7 +1111,7 @@ class ACIModule(object):
if 'state' in self.params: if 'state' in self.params:
self.original = self.existing self.original = self.existing
if self.params['state'] in ('absent', 'present'): if self.params.get('state') in ('absent', 'present'):
self.get_existing() self.get_existing()
# if self.module._diff and self.original != self.existing: # if self.module._diff and self.original != self.existing:
@ -1124,7 +1121,7 @@ class ACIModule(object):
# ) # )
self.result['current'] = self.existing self.result['current'] = self.existing
if self.params['output_level'] in ('debug', 'info'): if self.params.get('output_level') in ('debug', 'info'):
self.result['sent'] = self.config self.result['sent'] = self.config
self.result['proposed'] = self.proposed self.result['proposed'] = self.proposed
@ -1134,21 +1131,21 @@ class ACIModule(object):
def fail_json(self, msg, **kwargs): def fail_json(self, msg, **kwargs):
# Return error information, if we have it # Return error information, if we have it
if self.error['code'] is not None and self.error['text'] is not None: if self.error.get('code') is not None and self.error.get('text') is not None:
self.result['error'] = self.error self.result['error'] = self.error
if 'state' in self.params: if 'state' in self.params:
if self.params['state'] in ('absent', 'present'): if self.params.get('state') in ('absent', 'present'):
if self.params['output_level'] in ('debug', 'info'): if self.params.get('output_level') in ('debug', 'info'):
self.result['previous'] = self.existing self.result['previous'] = self.existing
# Return the gory details when we need it # Return the gory details when we need it
if self.params['output_level'] == 'debug': if self.params.get('output_level') == 'debug':
if self.imdata is not None: if self.imdata is not None:
self.result['imdata'] = self.imdata self.result['imdata'] = self.imdata
self.result['totalCount'] = self.totalCount self.result['totalCount'] = self.totalCount
if self.params['output_level'] == 'debug': if self.params.get('output_level') == 'debug':
if self.url is not None: if self.url is not None:
if 'state' in self.params: if 'state' in self.params:
self.result['filter_string'] = self.filter_string self.result['filter_string'] = self.filter_string
@ -1159,7 +1156,7 @@ class ACIModule(object):
self.result['url'] = self.url self.result['url'] = self.url
if 'state' in self.params: if 'state' in self.params:
if self.params['output_level'] in ('debug', 'info'): if self.params.get('output_level') in ('debug', 'info'):
self.result['sent'] = self.config self.result['sent'] = self.config
self.result['proposed'] = self.proposed self.result['proposed'] = self.proposed

View file

@ -146,7 +146,7 @@ class MSOModule(object):
self.params['protocol'] = 'https' if self.params.get('use_ssl', True) else 'http' self.params['protocol'] = 'https' if self.params.get('use_ssl', True) else 'http'
# Set base_uri # Set base_uri
if 'port' in self.params and self.params['port'] is not None: if self.params.get('port') is not None:
self.baseuri = '{protocol}://{host}:{port}/api/v1/'.format(**self.params) self.baseuri = '{protocol}://{host}:{port}/api/v1/'.format(**self.params)
else: else:
self.baseuri = '{protocol}://{host}/api/v1/'.format(**self.params) self.baseuri = '{protocol}://{host}/api/v1/'.format(**self.params)
@ -155,7 +155,7 @@ class MSOModule(object):
self.module.warn('Enable debug output because ANSIBLE_DEBUG was set.') self.module.warn('Enable debug output because ANSIBLE_DEBUG was set.')
self.params['output_level'] = 'debug' self.params['output_level'] = 'debug'
if self.params['password']: if self.params.get('password'):
# Perform password-based authentication, log on using password # Perform password-based authentication, log on using password
self.login() self.login()
else: else:
@ -166,19 +166,19 @@ class MSOModule(object):
# Perform login request # Perform login request
self.url = urljoin(self.baseuri, 'auth/login') self.url = urljoin(self.baseuri, 'auth/login')
payload = {'username': self.params['username'], 'password': self.params['password']} payload = {'username': self.params.get('username'), 'password': self.params.get('password')}
resp, auth = fetch_url(self.module, resp, auth = fetch_url(self.module,
self.url, self.url,
data=json.dumps(payload), data=json.dumps(payload),
method='POST', method='POST',
headers=self.headers, headers=self.headers,
timeout=self.params['timeout'], timeout=self.params.get('timeout'),
use_proxy=self.params['use_proxy']) use_proxy=self.params.get('use_proxy'))
# Handle MSO response # Handle MSO response
if auth['status'] != 201: if auth.get('status') != 201:
self.response = auth['msg'] self.response = auth.get('msg')
self.status = auth['status'] self.status = auth.get('status')
self.fail_json(msg='Authentication failed: {msg}'.format(**auth)) self.fail_json(msg='Authentication failed: {msg}'.format(**auth))
payload = json.loads(resp.read()) payload = json.loads(resp.read())
@ -206,20 +206,20 @@ class MSOModule(object):
headers=self.headers, headers=self.headers,
data=json.dumps(data), data=json.dumps(data),
method=self.method, method=self.method,
timeout=self.params['timeout'], timeout=self.params.get('timeout'),
use_proxy=self.params['use_proxy'], use_proxy=self.params.get('use_proxy'),
) )
self.response = info['msg'] self.response = info.get('msg')
self.status = info['status'] self.status = info.get('status')
# self.result['info'] = info # self.result['info'] = info
# Get change status from HTTP headers # Get change status from HTTP headers
if 'modified' in info: if 'modified' in info:
self.has_modified = True self.has_modified = True
if info['modified'] == 'false': if info.get('modified') == 'false':
self.result['changed'] = False self.result['changed'] = False
elif info['modified'] == 'true': elif info.get('modified') == 'true':
self.result['changed'] = True self.result['changed'] = True
# 200: OK, 201: Created, 202: Accepted, 204: No Content # 200: OK, 201: Created, 202: Accepted, 204: No Content
@ -294,7 +294,7 @@ class MSOModule(object):
self.module.fail_json(msg="Schema '%s' is not a valid schema name." % schema) self.module.fail_json(msg="Schema '%s' is not a valid schema name." % schema)
if 'id' not in s: if 'id' not in s:
self.module.fail_json(msg="Schema lookup failed for schema '%s': %s" % (schema, s)) self.module.fail_json(msg="Schema lookup failed for schema '%s': %s" % (schema, s))
return s['id'] return s.get('id')
def lookup_domain(self, domain): def lookup_domain(self, domain):
''' Look up a domain and return its id ''' ''' Look up a domain and return its id '''
@ -306,7 +306,7 @@ class MSOModule(object):
self.module.fail_json(msg="Domain '%s' is not a valid domain name." % domain) self.module.fail_json(msg="Domain '%s' is not a valid domain name." % domain)
if 'id' not in d: if 'id' not in d:
self.module.fail_json(msg="Domain lookup failed for domain '%s': %s" % (domain, d)) self.module.fail_json(msg="Domain lookup failed for domain '%s': %s" % (domain, d))
return d['id'] return d.get('id')
def lookup_roles(self, roles): def lookup_roles(self, roles):
''' Look up roles and return their ids ''' ''' Look up roles and return their ids '''
@ -320,7 +320,7 @@ class MSOModule(object):
self.module.fail_json(msg="Role '%s' is not a valid role name." % role) self.module.fail_json(msg="Role '%s' is not a valid role name." % role)
if 'id' not in r: if 'id' not in r:
self.module.fail_json(msg="Role lookup failed for role '%s': %s" % (role, r)) self.module.fail_json(msg="Role lookup failed for role '%s': %s" % (role, r))
ids.append(dict(roleId=r['id'])) ids.append(dict(roleId=r.get('id')))
return ids return ids
def lookup_site(self, site): def lookup_site(self, site):
@ -333,7 +333,7 @@ class MSOModule(object):
self.module.fail_json(msg="Site '%s' is not a valid site name." % site) self.module.fail_json(msg="Site '%s' is not a valid site name." % site)
if 'id' not in s: if 'id' not in s:
self.module.fail_json(msg="Site lookup failed for site '%s': %s" % (site, s)) self.module.fail_json(msg="Site lookup failed for site '%s': %s" % (site, s))
return s['id'] return s.get('id')
def lookup_sites(self, sites): def lookup_sites(self, sites):
''' Look up sites and return their ids ''' ''' Look up sites and return their ids '''
@ -347,7 +347,7 @@ class MSOModule(object):
self.module.fail_json(msg="Site '%s' is not a valid site name." % site) self.module.fail_json(msg="Site '%s' is not a valid site name." % site)
if 'id' not in s: if 'id' not in s:
self.module.fail_json(msg="Site lookup failed for site '%s': %s" % (site, s)) self.module.fail_json(msg="Site lookup failed for site '%s': %s" % (site, s))
ids.append(dict(siteId=s['id'], securityDomains=[])) ids.append(dict(siteId=s.get('id'), securityDomains=[]))
return ids return ids
def lookup_tenant(self, tenant): def lookup_tenant(self, tenant):
@ -360,7 +360,7 @@ class MSOModule(object):
self.module.fail_json(msg="Tenant '%s' is not valid tenant name." % tenant) self.module.fail_json(msg="Tenant '%s' is not valid tenant name." % tenant)
if 'id' not in t: if 'id' not in t:
self.module.fail_json(msg="Tenant lookup failed for tenant '%s': %s" % (tenant, t)) self.module.fail_json(msg="Tenant lookup failed for tenant '%s': %s" % (tenant, t))
return t['id'] return t.get('id')
def lookup_users(self, users): def lookup_users(self, users):
''' Look up users and return their ids ''' ''' Look up users and return their ids '''
@ -374,7 +374,7 @@ class MSOModule(object):
self.module.fail_json(msg="User '%s' is not a valid user name." % user) self.module.fail_json(msg="User '%s' is not a valid user name." % user)
if 'id' not in u: if 'id' not in u:
self.module.fail_json(msg="User lookup failed for user '%s': %s" % (user, u)) self.module.fail_json(msg="User lookup failed for user '%s': %s" % (user, u))
ids.append(dict(userId=u['id'])) ids.append(dict(userId=u.get('id')))
return ids return ids
def create_label(self, label, label_type): def create_label(self, label, label_type):
@ -393,7 +393,7 @@ class MSOModule(object):
l = self.create_label(label, label_type) l = self.create_label(label, label_type)
if 'id' not in l: if 'id' not in l:
self.module.fail_json(msg="Label lookup failed for label '%s': %s" % (label, l)) self.module.fail_json(msg="Label lookup failed for label '%s': %s" % (label, l))
ids.append(l['id']) ids.append(l.get('id'))
return ids return ids
def anp_ref(self, **data): def anp_ref(self, **data):
@ -412,7 +412,7 @@ class MSOModule(object):
''' Create contractRef string ''' ''' Create contractRef string '''
# Support the contract argspec # Support the contract argspec
if 'name' in data: if 'name' in data:
data['contract'] = data['name'] data['contract'] = data.get('name')
return '/schemas/{schema_id}/templates/{template}/contracts/{contract}'.format(**data) return '/schemas/{schema_id}/templates/{template}/contracts/{contract}'.format(**data)
def filter_ref(self, **data): def filter_ref(self, **data):
@ -430,18 +430,18 @@ class MSOModule(object):
return None return None
if data.get('schema') is not None: if data.get('schema') is not None:
schema_obj = self.get_obj('schemas', displayName=data['schema']) schema_obj = self.get_obj('schemas', displayName=data.get('schema'))
if not schema_obj: if not schema_obj:
self.fail_json(msg="Referenced schema '{schema}' in {reftype}ref does not exist".format(reftype=reftype, **data)) self.fail_json(msg="Referenced schema '{schema}' in {reftype}ref does not exist".format(reftype=reftype, **data))
schema_id = schema_obj['id'] schema_id = schema_obj.get('id')
if data.get('template') is not None: if data.get('template') is not None:
template = data['template'] template = data.get('template')
refname = '%sName' % reftype refname = '%sName' % reftype
return { return {
refname: data['name'], refname: data.get('name'),
'schemaId': schema_id, 'schemaId': schema_id,
'templateName': template, 'templateName': template,
} }
@ -454,8 +454,8 @@ class MSOModule(object):
subnets = [] subnets = []
for subnet in data: for subnet in data:
subnets.append(dict( subnets.append(dict(
ip=subnet['ip'], ip=subnet.get('ip'),
description=subnet.get('description', subnet['ip']), description=subnet.get('description', subnet.get('ip')),
scope=subnet.get('scope', 'private'), scope=subnet.get('scope', 'private'),
shared=subnet.get('shared', False), shared=subnet.get('shared', False),
noDefaultGateway=subnet.get('no_default_gateway', False), noDefaultGateway=subnet.get('no_default_gateway', False),
@ -512,27 +512,27 @@ class MSOModule(object):
def exit_json(self, **kwargs): def exit_json(self, **kwargs):
''' Custom written method to exit from module. ''' ''' Custom written method to exit from module. '''
if self.params['state'] in ('absent', 'present'): if self.params.get('state') in ('absent', 'present'):
if self.params['output_level'] in ('debug', 'info'): if self.params.get('output_level') in ('debug', 'info'):
self.result['previous'] = self.previous self.result['previous'] = self.previous
# FIXME: Modified header only works for PATCH # FIXME: Modified header only works for PATCH
if not self.has_modified and self.previous != self.existing: if not self.has_modified and self.previous != self.existing:
self.result['changed'] = True self.result['changed'] = True
# Return the gory details when we need it # Return the gory details when we need it
if self.params['output_level'] == 'debug': if self.params.get('output_level') == 'debug':
self.result['method'] = self.method self.result['method'] = self.method
self.result['response'] = self.response self.result['response'] = self.response
self.result['status'] = self.status self.result['status'] = self.status
self.result['url'] = self.url self.result['url'] = self.url
if self.params['state'] in ('absent', 'present'): if self.params.get('state') in ('absent', 'present'):
self.result['sent'] = self.sent self.result['sent'] = self.sent
self.result['proposed'] = self.proposed self.result['proposed'] = self.proposed
self.result['current'] = self.existing self.result['current'] = self.existing
if self.module._diff and self.result['changed'] is True: if self.module._diff and self.result.get('changed') is True:
self.result['diff'] = dict( self.result['diff'] = dict(
before=self.previous, before=self.previous,
after=self.existing, after=self.existing,
@ -544,22 +544,22 @@ class MSOModule(object):
def fail_json(self, msg, **kwargs): def fail_json(self, msg, **kwargs):
''' Custom written method to return info on failure. ''' ''' Custom written method to return info on failure. '''
if self.params['state'] in ('absent', 'present'): if self.params.get('state') in ('absent', 'present'):
if self.params['output_level'] in ('debug', 'info'): if self.params.get('output_level') in ('debug', 'info'):
self.result['previous'] = self.previous self.result['previous'] = self.previous
# FIXME: Modified header only works for PATCH # FIXME: Modified header only works for PATCH
if not self.has_modified and self.previous != self.existing: if not self.has_modified and self.previous != self.existing:
self.result['changed'] = True self.result['changed'] = True
# Return the gory details when we need it # Return the gory details when we need it
if self.params['output_level'] == 'debug': if self.params.get('output_level') == 'debug':
if self.url is not None: if self.url is not None:
self.result['method'] = self.method self.result['method'] = self.method
self.result['response'] = self.response self.result['response'] = self.response
self.result['status'] = self.status self.result['status'] = self.status
self.result['url'] = self.url self.result['url'] = self.url
if self.params['state'] in ('absent', 'present'): if self.params.get('state') in ('absent', 'present'):
self.result['sent'] = self.sent self.result['sent'] = self.sent
self.result['proposed'] = self.proposed self.result['proposed'] = self.proposed

View file

@ -294,26 +294,26 @@ def main():
if not HAS_DATEUTIL: if not HAS_DATEUTIL:
module.fail_json(msg='dateutil required for this module') module.fail_json(msg='dateutil required for this module')
aaa_password = module.params['aaa_password'] aaa_password = module.params.get('aaa_password')
aaa_password_lifetime = module.params['aaa_password_lifetime'] aaa_password_lifetime = module.params.get('aaa_password_lifetime')
aaa_password_update_required = aci.boolean(module.params['aaa_password_update_required']) aaa_password_update_required = aci.boolean(module.params.get('aaa_password_update_required'))
aaa_user = module.params['aaa_user'] aaa_user = module.params.get('aaa_user')
clear_password_history = aci.boolean(module.params['clear_password_history'], 'yes', 'no') clear_password_history = aci.boolean(module.params.get('clear_password_history'), 'yes', 'no')
description = module.params['description'] description = module.params.get('description')
email = module.params['email'] email = module.params.get('email')
enabled = aci.boolean(module.params['enabled'], 'active', 'inactive') enabled = aci.boolean(module.params.get('enabled'), 'active', 'inactive')
expires = aci.boolean(module.params['expires']) expires = aci.boolean(module.params.get('expires'))
first_name = module.params['first_name'] first_name = module.params.get('first_name')
last_name = module.params['last_name'] last_name = module.params.get('last_name')
phone = module.params['phone'] phone = module.params.get('phone')
state = module.params['state'] state = module.params.get('state')
expiration = module.params['expiration'] expiration = module.params.get('expiration')
if expiration is not None and expiration != 'never': if expiration is not None and expiration != 'never':
try: try:
expiration = aci.iso8601_format(dateutil.parser.parse(expiration).replace(tzinfo=tzutc())) expiration = aci.iso8601_format(dateutil.parser.parse(expiration).replace(tzinfo=tzutc()))
except Exception as e: except Exception as e:
module.fail_json(msg="Failed to parse date format '%s', %s" % (module.params['expiration'], e)) module.fail_json(msg="Failed to parse date format '%s', %s" % (module.params.get('expiration'), e))
aci.construct_url( aci.construct_url(
root_class=dict( root_class=dict(

View file

@ -243,17 +243,17 @@ def main():
], ],
) )
aaa_user = module.params['aaa_user'] aaa_user = module.params.get('aaa_user')
aaa_user_type = module.params['aaa_user_type'] aaa_user_type = module.params.get('aaa_user_type')
certificate = module.params['certificate'] certificate = module.params.get('certificate')
certificate_name = module.params['certificate_name'] certificate_name = module.params.get('certificate_name')
state = module.params['state'] state = module.params.get('state')
aci = ACIModule(module) aci = ACIModule(module)
aci.construct_url( aci.construct_url(
root_class=dict( root_class=dict(
aci_class=ACI_MAPPING[aaa_user_type]['aci_class'], aci_class=ACI_MAPPING.get(aaa_user_type).get('aci_class'),
aci_rn=ACI_MAPPING[aaa_user_type]['aci_mo'] + aaa_user, aci_rn=ACI_MAPPING.get(aaa_user_type).get('aci_mo') + aaa_user,
module_object=aaa_user, module_object=aaa_user,
target_filter={'name': aaa_user}, target_filter={'name': aaa_user},
), ),

View file

@ -283,15 +283,15 @@ def main():
], ],
) )
leaf_interface_profile = module.params['leaf_interface_profile'] leaf_interface_profile = module.params.get('leaf_interface_profile')
access_port_selector = module.params['access_port_selector'] access_port_selector = module.params.get('access_port_selector')
leaf_port_blk = module.params['leaf_port_blk'] leaf_port_blk = module.params.get('leaf_port_blk')
leaf_port_blk_description = module.params['leaf_port_blk_description'] leaf_port_blk_description = module.params.get('leaf_port_blk_description')
from_port = module.params['from_port'] from_port = module.params.get('from_port')
to_port = module.params['to_port'] to_port = module.params.get('to_port')
from_card = module.params['from_card'] from_card = module.params.get('from_card')
to_card = module.params['to_card'] to_card = module.params.get('to_card')
state = module.params['state'] state = module.params.get('state')
aci = ACIModule(module) aci = ACIModule(module)
aci.construct_url( aci.construct_url(

View file

@ -314,18 +314,18 @@ def main():
], ],
) )
leaf_interface_profile = module.params['leaf_interface_profile'] leaf_interface_profile = module.params.get('leaf_interface_profile')
access_port_selector = module.params['access_port_selector'] access_port_selector = module.params.get('access_port_selector')
description = module.params['description'] description = module.params.get('description')
leaf_port_blk = module.params['leaf_port_blk'] leaf_port_blk = module.params.get('leaf_port_blk')
leaf_port_blk_description = module.params['leaf_port_blk_description'] leaf_port_blk_description = module.params.get('leaf_port_blk_description')
from_port = module.params['from_port'] from_port = module.params.get('from_port')
to_port = module.params['to_port'] to_port = module.params.get('to_port')
from_card = module.params['from_card'] from_card = module.params.get('from_card')
to_card = module.params['to_card'] to_card = module.params.get('to_card')
policy_group = module.params['policy_group'] policy_group = module.params.get('policy_group')
interface_type = module.params['interface_type'] interface_type = module.params.get('interface_type')
state = module.params['state'] state = module.params.get('state')
# Build child_configs dynamically # Build child_configs dynamically
child_configs = [dict( child_configs = [dict(

View file

@ -303,17 +303,17 @@ def main():
], ],
) )
leaf_interface_profile = module.params['leaf_interface_profile'] leaf_interface_profile = module.params.get('leaf_interface_profile')
access_port_selector = module.params['access_port_selector'] access_port_selector = module.params.get('access_port_selector')
leaf_port_blk = module.params['leaf_port_blk'] leaf_port_blk = module.params.get('leaf_port_blk')
leaf_port_blk_description = module.params['leaf_port_blk_description'] leaf_port_blk_description = module.params.get('leaf_port_blk_description')
from_port = module.params['from_port'] from_port = module.params.get('from_port')
to_port = module.params['to_port'] to_port = module.params.get('to_port')
from_sub_port = module.params['from_sub_port'] from_sub_port = module.params.get('from_sub_port')
to_sub_port = module.params['to_sub_port'] to_sub_port = module.params.get('to_sub_port')
from_card = module.params['from_card'] from_card = module.params.get('from_card')
to_card = module.params['to_card'] to_card = module.params.get('to_card')
state = module.params['state'] state = module.params.get('state')
aci = ACIModule(module) aci = ACIModule(module)
aci.construct_url( aci.construct_url(

View file

@ -222,10 +222,10 @@ def main():
], ],
) )
aep = module.params['aep'] aep = module.params.get('aep')
description = module.params['description'] description = module.params.get('description')
infra_vlan = module.params['infra_vlan'] infra_vlan = module.params.get('infra_vlan')
state = module.params['state'] state = module.params.get('state')
if infra_vlan: if infra_vlan:
child_configs = [dict(infraProvAcc=dict(attributes=dict(name='provacc')))] child_configs = [dict(infraProvAcc=dict(attributes=dict(name='provacc')))]

View file

@ -250,11 +250,11 @@ def main():
], ],
) )
aep = module.params['aep'] aep = module.params.get('aep')
domain = module.params['domain'] domain = module.params.get('domain')
domain_type = module.params['domain_type'] domain_type = module.params.get('domain_type')
vm_provider = module.params['vm_provider'] vm_provider = module.params.get('vm_provider')
state = module.params['state'] state = module.params.get('state')
# Report when vm_provider is set when type is not virtual # Report when vm_provider is set when type is not virtual
if domain_type != 'vmm' and vm_provider is not None: if domain_type != 'vmm' and vm_provider is not None:

View file

@ -226,10 +226,10 @@ def main():
], ],
) )
ap = module.params['ap'] ap = module.params.get('ap')
description = module.params['description'] description = module.params.get('description')
state = module.params['state'] state = module.params.get('state')
tenant = module.params['tenant'] tenant = module.params.get('tenant')
aci = ACIModule(module) aci = ACIModule(module)
aci.construct_url( aci.construct_url(

View file

@ -367,33 +367,33 @@ def main():
aci = ACIModule(module) aci = ACIModule(module)
arp_flooding = aci.boolean(module.params['arp_flooding']) arp_flooding = aci.boolean(module.params.get('arp_flooding'))
bd = module.params['bd'] bd = module.params.get('bd')
bd_type = module.params['bd_type'] bd_type = module.params.get('bd_type')
if bd_type == 'ethernet': if bd_type == 'ethernet':
# ethernet type is represented as regular, but that is not clear to the users # ethernet type is represented as regular, but that is not clear to the users
bd_type = 'regular' bd_type = 'regular'
description = module.params['description'] description = module.params.get('description')
enable_multicast = aci.boolean(module.params['enable_multicast']) enable_multicast = aci.boolean(module.params.get('enable_multicast'))
enable_routing = aci.boolean(module.params['enable_routing']) enable_routing = aci.boolean(module.params.get('enable_routing'))
endpoint_clear = aci.boolean(module.params['endpoint_clear']) endpoint_clear = aci.boolean(module.params.get('endpoint_clear'))
endpoint_move_detect = module.params['endpoint_move_detect'] endpoint_move_detect = module.params.get('endpoint_move_detect')
if endpoint_move_detect == 'default': if endpoint_move_detect == 'default':
# the ACI default setting is an empty string, but that is not a good input value # the ACI default setting is an empty string, but that is not a good input value
endpoint_move_detect = '' endpoint_move_detect = ''
endpoint_retention_action = module.params['endpoint_retention_action'] endpoint_retention_action = module.params.get('endpoint_retention_action')
endpoint_retention_policy = module.params['endpoint_retention_policy'] endpoint_retention_policy = module.params.get('endpoint_retention_policy')
igmp_snoop_policy = module.params['igmp_snoop_policy'] igmp_snoop_policy = module.params.get('igmp_snoop_policy')
ip_learning = aci.boolean(module.params['ip_learning']) ip_learning = aci.boolean(module.params.get('ip_learning'))
ipv6_nd_policy = module.params['ipv6_nd_policy'] ipv6_nd_policy = module.params.get('ipv6_nd_policy')
l2_unknown_unicast = module.params['l2_unknown_unicast'] l2_unknown_unicast = module.params.get('l2_unknown_unicast')
l3_unknown_multicast = module.params['l3_unknown_multicast'] l3_unknown_multicast = module.params.get('l3_unknown_multicast')
limit_ip_learn = aci.boolean(module.params['limit_ip_learn']) limit_ip_learn = aci.boolean(module.params.get('limit_ip_learn'))
mac_address = module.params['mac_address'] mac_address = module.params.get('mac_address')
multi_dest = module.params['multi_dest'] multi_dest = module.params.get('multi_dest')
state = module.params['state'] state = module.params.get('state')
tenant = module.params['tenant'] tenant = module.params.get('tenant')
vrf = module.params['vrf'] vrf = module.params.get('vrf')
aci.construct_url( aci.construct_url(
root_class=dict( root_class=dict(

View file

@ -375,30 +375,30 @@ def main():
aci = ACIModule(module) aci = ACIModule(module)
description = module.params['description'] description = module.params.get('description')
enable_vip = aci.boolean(module.params['enable_vip']) enable_vip = aci.boolean(module.params.get('enable_vip'))
tenant = module.params['tenant'] tenant = module.params.get('tenant')
bd = module.params['bd'] bd = module.params.get('bd')
gateway = module.params['gateway'] gateway = module.params.get('gateway')
mask = module.params['mask'] mask = module.params.get('mask')
if mask is not None and mask not in range(0, 129): if mask is not None and mask not in range(0, 129):
# TODO: split checks between IPv4 and IPv6 Addresses # TODO: split checks between IPv4 and IPv6 Addresses
module.fail_json(msg='Valid Subnet Masks are 0 to 32 for IPv4 Addresses and 0 to 128 for IPv6 addresses') module.fail_json(msg='Valid Subnet Masks are 0 to 32 for IPv4 Addresses and 0 to 128 for IPv6 addresses')
if gateway is not None: if gateway is not None:
gateway = '{0}/{1}'.format(gateway, str(mask)) gateway = '{0}/{1}'.format(gateway, str(mask))
subnet_name = module.params['subnet_name'] subnet_name = module.params.get('subnet_name')
nd_prefix_policy = module.params['nd_prefix_policy'] nd_prefix_policy = module.params.get('nd_prefix_policy')
preferred = aci.boolean(module.params['preferred']) preferred = aci.boolean(module.params.get('preferred'))
route_profile = module.params['route_profile'] route_profile = module.params.get('route_profile')
route_profile_l3_out = module.params['route_profile_l3_out'] route_profile_l3_out = module.params.get('route_profile_l3_out')
scope = module.params['scope'] scope = module.params.get('scope')
if scope is not None: if scope is not None:
if 'private' in scope and 'public' in scope: if 'private' in scope and 'public' in scope:
module.fail_json(msg="Parameter 'scope' cannot be both 'private' and 'public', got: %s" % scope) module.fail_json(msg="Parameter 'scope' cannot be both 'private' and 'public', got: %s" % scope)
else: else:
scope = ','.join(sorted(scope)) scope = ','.join(sorted(scope))
state = module.params['state'] state = module.params.get('state')
subnet_control = module.params['subnet_control'] subnet_control = module.params.get('subnet_control')
if subnet_control: if subnet_control:
subnet_control = SUBNET_CONTROL_MAPPING[subnet_control] subnet_control = SUBNET_CONTROL_MAPPING[subnet_control]

View file

@ -190,10 +190,10 @@ def main():
], ],
) )
bd = module.params['bd'] bd = module.params.get('bd')
l3out = module.params['l3out'] l3out = module.params.get('l3out')
state = module.params['state'] state = module.params.get('state')
tenant = module.params['tenant'] tenant = module.params.get('tenant')
aci = ACIModule(module) aci = ACIModule(module)
aci.construct_url( aci.construct_url(

View file

@ -226,14 +226,14 @@ def main():
aci = ACIModule(module) aci = ACIModule(module)
description = module.params['description'] description = module.params.get('description')
export_policy = module.params['export_policy'] export_policy = module.params.get('export_policy')
fail_on_decrypt = aci.boolean(module.params['fail_on_decrypt']) fail_on_decrypt = aci.boolean(module.params.get('fail_on_decrypt'))
import_mode = module.params['import_mode'] import_mode = module.params.get('import_mode')
import_policy = module.params['import_policy'] import_policy = module.params.get('import_policy')
import_type = module.params['import_type'] import_type = module.params.get('import_type')
snapshot = module.params['snapshot'] snapshot = module.params.get('snapshot')
state = module.params['state'] state = module.params.get('state')
if state == 'rollback': if state == 'rollback':
if snapshot.startswith('run-'): if snapshot.startswith('run-'):
@ -291,13 +291,14 @@ def get_preview(aci):
This function is used to generate a preview between two snapshots and add the parsed results to the aci module return data. This function is used to generate a preview between two snapshots and add the parsed results to the aci module return data.
''' '''
uri = aci.url + aci.filter_string uri = aci.url + aci.filter_string
resp, info = fetch_url(aci.module, uri, headers=aci.headers, method='GET', timeout=aci.module.params['timeout'], use_proxy=aci.module.params['use_proxy']) resp, info = fetch_url(aci.module, uri, headers=aci.headers, method='GET', timeout=aci.module.params.get('timeout'),
use_proxy=aci.module.params.get('use_proxy'))
aci.method = 'GET' aci.method = 'GET'
aci.response = info['msg'] aci.response = info.get('msg')
aci.status = info['status'] aci.status = info.get('status')
# Handle APIC response # Handle APIC response
if info['status'] == 200: if info.get('status') == 200:
xml_to_json(aci, resp.read()) xml_to_json(aci, resp.read())
else: else:
aci.result['raw'] = resp.read() aci.result['raw'] = resp.read()

View file

@ -246,20 +246,20 @@ def main():
aci = ACIModule(module) aci = ACIModule(module)
description = module.params['description'] description = module.params.get('description')
export_policy = module.params['export_policy'] export_policy = module.params.get('export_policy')
file_format = module.params['format'] file_format = module.params.get('format')
include_secure = aci.boolean(module.params['include_secure']) include_secure = aci.boolean(module.params.get('include_secure'))
max_count = module.params['max_count'] max_count = module.params.get('max_count')
if max_count is not None: if max_count is not None:
if max_count in range(1, 11): if max_count in range(1, 11):
max_count = str(max_count) max_count = str(max_count)
else: else:
module.fail_json(msg="Parameter 'max_count' must be a number between 1 and 10") module.fail_json(msg="Parameter 'max_count' must be a number between 1 and 10")
snapshot = module.params['snapshot'] snapshot = module.params.get('snapshot')
if snapshot is not None and not snapshot.startswith('run-'): if snapshot is not None and not snapshot.startswith('run-'):
snapshot = 'run-' + snapshot snapshot = 'run-' + snapshot
state = module.params['state'] state = module.params.get('state')
if state == 'present': if state == 'present':
aci.construct_url( aci.construct_url(

View file

@ -254,13 +254,13 @@ def main():
], ],
) )
contract = module.params['contract'] contract = module.params.get('contract')
description = module.params['description'] description = module.params.get('description')
scope = module.params['scope'] scope = module.params.get('scope')
priority = module.params['priority'] priority = module.params.get('priority')
dscp = module.params['dscp'] dscp = module.params.get('dscp')
state = module.params['state'] state = module.params.get('state')
tenant = module.params['tenant'] tenant = module.params.get('tenant')
aci = ACIModule(module) aci = ACIModule(module)
aci.construct_url( aci.construct_url(

View file

@ -284,20 +284,20 @@ def main():
aci = ACIModule(module) aci = ACIModule(module)
subject = module.params['subject'] subject = module.params.get('subject')
priority = module.params['priority'] priority = module.params.get('priority')
reverse_filter = aci.boolean(module.params['reverse_filter']) reverse_filter = aci.boolean(module.params.get('reverse_filter'))
contract = module.params['contract'] contract = module.params.get('contract')
dscp = module.params['dscp'] dscp = module.params.get('dscp')
description = module.params['description'] description = module.params.get('description')
consumer_match = module.params['consumer_match'] consumer_match = module.params.get('consumer_match')
if consumer_match is not None: if consumer_match is not None:
consumer_match = MATCH_MAPPING[consumer_match] consumer_match = MATCH_MAPPING.get(consumer_match)
provider_match = module.params['provider_match'] provider_match = module.params.get('provider_match')
if provider_match is not None: if provider_match is not None:
provider_match = MATCH_MAPPING[provider_match] provider_match = MATCH_MAPPING.get(provider_match)
state = module.params['state'] state = module.params.get('state')
tenant = module.params['tenant'] tenant = module.params.get('tenant')
aci.construct_url( aci.construct_url(
root_class=dict( root_class=dict(

View file

@ -249,12 +249,12 @@ def main():
], ],
) )
contract = module.params['contract'] contract = module.params.get('contract')
filter_name = module.params['filter'] filter_name = module.params.get('filter')
log = module.params['log'] log = module.params.get('log')
subject = module.params['subject'] subject = module.params.get('subject')
tenant = module.params['tenant'] tenant = module.params.get('tenant')
state = module.params['state'] state = module.params.get('state')
# Add subject_filter key to modul.params for building the URL # Add subject_filter key to modul.params for building the URL
module.params['subject_filter'] = filter_name module.params['subject_filter'] = filter_name

View file

@ -298,16 +298,16 @@ def main():
], ],
) )
dscp = module.params['dscp'] dscp = module.params.get('dscp')
domain = module.params['domain'] domain = module.params.get('domain')
domain_type = module.params['domain_type'] domain_type = module.params.get('domain_type')
encap_mode = module.params['encap_mode'] encap_mode = module.params.get('encap_mode')
multicast_address = module.params['multicast_address'] multicast_address = module.params.get('multicast_address')
vm_provider = module.params['vm_provider'] vm_provider = module.params.get('vm_provider')
vswitch = module.params['vswitch'] vswitch = module.params.get('vswitch')
if vswitch is not None: if vswitch is not None:
vswitch = VSWITCH_MAPPING[vswitch] vswitch = VSWITCH_MAPPING.get(vswitch)
state = module.params['state'] state = module.params.get('state')
if domain_type != 'vmm': if domain_type != 'vmm':
if vm_provider is not None: if vm_provider is not None:
@ -341,8 +341,8 @@ def main():
domain_rn = 'phys-{0}'.format(domain) domain_rn = 'phys-{0}'.format(domain)
elif domain_type == 'vmm': elif domain_type == 'vmm':
domain_class = 'vmmDomP' domain_class = 'vmmDomP'
domain_mo = 'uni/vmmp-{0}/dom-{1}'.format(VM_PROVIDER_MAPPING[vm_provider], domain) domain_mo = 'uni/vmmp-{0}/dom-{1}'.format(VM_PROVIDER_MAPPING.get(vm_provider), domain)
domain_rn = 'vmmp-{0}/dom-{1}'.format(VM_PROVIDER_MAPPING[vm_provider], domain) domain_rn = 'vmmp-{0}/dom-{1}'.format(VM_PROVIDER_MAPPING.get(vm_provider), domain)
# Ensure that querying all objects works when only domain_type is provided # Ensure that querying all objects works when only domain_type is provided
if domain is None: if domain is None:

View file

@ -284,13 +284,13 @@ def main():
], ],
) )
domain = module.params['domain'] domain = module.params.get('domain')
domain_type = module.params['domain_type'] domain_type = module.params.get('domain_type')
pool = module.params['pool'] pool = module.params.get('pool')
pool_allocation_mode = module.params['pool_allocation_mode'] pool_allocation_mode = module.params.get('pool_allocation_mode')
pool_type = module.params['pool_type'] pool_type = module.params.get('pool_type')
vm_provider = module.params['vm_provider'] vm_provider = module.params.get('vm_provider')
state = module.params['state'] state = module.params.get('state')
# Report when vm_provider is set when type is not virtual # Report when vm_provider is set when type is not virtual
if domain_type != 'vmm' and vm_provider is not None: if domain_type != 'vmm' and vm_provider is not None:

View file

@ -284,12 +284,12 @@ def main():
], ],
) )
domain = module.params['domain'] domain = module.params.get('domain')
domain_type = module.params['domain_type'] domain_type = module.params.get('domain_type')
pool = module.params['pool'] pool = module.params.get('pool')
pool_allocation_mode = module.params['pool_allocation_mode'] pool_allocation_mode = module.params.get('pool_allocation_mode')
vm_provider = module.params['vm_provider'] vm_provider = module.params.get('vm_provider')
state = module.params['state'] state = module.params.get('state')
# Report when vm_provider is set when type is not virtual # Report when vm_provider is set when type is not virtual
if domain_type != 'vmm' and vm_provider is not None: if domain_type != 'vmm' and vm_provider is not None:

View file

@ -248,11 +248,11 @@ def main():
], ],
) )
description = module.params['description'] description = module.params.get('description')
pool = module.params['pool'] pool = module.params.get('pool')
pool_type = module.params['pool_type'] pool_type = module.params.get('pool_type')
pool_allocation_mode = module.params['pool_allocation_mode'] pool_allocation_mode = module.params.get('pool_allocation_mode')
state = module.params['state'] state = module.params.get('state')
aci_class = ACI_POOL_MAPPING[pool_type]['aci_class'] aci_class = ACI_POOL_MAPPING[pool_type]['aci_class']
aci_mo = ACI_POOL_MAPPING[pool_type]['aci_mo'] aci_mo = ACI_POOL_MAPPING[pool_type]['aci_mo']

View file

@ -321,15 +321,15 @@ def main():
], ],
) )
allocation_mode = module.params['allocation_mode'] allocation_mode = module.params.get('allocation_mode')
description = module.params['description'] description = module.params.get('description')
pool = module.params['pool'] pool = module.params.get('pool')
pool_allocation_mode = module.params['pool_allocation_mode'] pool_allocation_mode = module.params.get('pool_allocation_mode')
pool_type = module.params['pool_type'] pool_type = module.params.get('pool_type')
range_end = module.params['range_end'] range_end = module.params.get('range_end')
range_name = module.params['range_name'] range_name = module.params.get('range_name')
range_start = module.params['range_start'] range_start = module.params.get('range_start')
state = module.params['state'] state = module.params.get('state')
if range_end is not None: if range_end is not None:
encap_end = '{0}-{1}'.format(pool_type, range_end) encap_end = '{0}-{1}'.format(pool_type, range_end)

View file

@ -316,16 +316,16 @@ def main():
aci = ACIModule(module) aci = ACIModule(module)
epg = module.params['epg'] epg = module.params.get('epg')
bd = module.params['bd'] bd = module.params.get('bd')
description = module.params['description'] description = module.params.get('description')
priority = module.params['priority'] priority = module.params.get('priority')
intra_epg_isolation = module.params['intra_epg_isolation'] intra_epg_isolation = module.params.get('intra_epg_isolation')
fwd_control = module.params['fwd_control'] fwd_control = module.params.get('fwd_control')
preferred_group = aci.boolean(module.params['preferred_group'], 'include', 'exclude') preferred_group = aci.boolean(module.params.get('preferred_group'), 'include', 'exclude')
state = module.params['state'] state = module.params.get('state')
tenant = module.params['tenant'] tenant = module.params.get('tenant')
ap = module.params['ap'] ap = module.params.get('ap')
aci.construct_url( aci.construct_url(
root_class=dict( root_class=dict(

View file

@ -194,10 +194,10 @@ def main():
], ],
) )
monitoring_policy = module.params['monitoring_policy'] monitoring_policy = module.params.get('monitoring_policy')
description = module.params['description'] description = module.params.get('description')
state = module.params['state'] state = module.params.get('state')
tenant = module.params['tenant'] tenant = module.params.get('tenant')
aci = ACIModule(module) aci = ACIModule(module)
aci.construct_url( aci.construct_url(

View file

@ -279,16 +279,16 @@ def main():
], ],
) )
ap = module.params['ap'] ap = module.params.get('ap')
contract = module.params['contract'] contract = module.params.get('contract')
contract_type = module.params['contract_type'] contract_type = module.params.get('contract_type')
epg = module.params['epg'] epg = module.params.get('epg')
priority = module.params['priority'] priority = module.params.get('priority')
provider_match = module.params['provider_match'] provider_match = module.params.get('provider_match')
if provider_match is not None: if provider_match is not None:
provider_match = PROVIDER_MATCH_MAPPING[provider_match] provider_match = PROVIDER_MATCH_MAPPING[provider_match]
state = module.params['state'] state = module.params.get('state')
tenant = module.params['tenant'] tenant = module.params.get('tenant')
aci_class = ACI_CLASS_MAPPING[contract_type]["class"] aci_class = ACI_CLASS_MAPPING[contract_type]["class"]
aci_rn = ACI_CLASS_MAPPING[contract_type]["rn"] aci_rn = ACI_CLASS_MAPPING[contract_type]["rn"]

View file

@ -326,31 +326,31 @@ def main():
aci = ACIModule(module) aci = ACIModule(module)
allow_useg = module.params['allow_useg'] allow_useg = module.params.get('allow_useg')
ap = module.params['ap'] ap = module.params.get('ap')
deploy_immediacy = module.params['deploy_immediacy'] deploy_immediacy = module.params.get('deploy_immediacy')
domain = module.params['domain'] domain = module.params.get('domain')
domain_type = module.params['domain_type'] domain_type = module.params.get('domain_type')
vm_provider = module.params['vm_provider'] vm_provider = module.params.get('vm_provider')
encap = module.params['encap'] encap = module.params.get('encap')
if encap is not None: if encap is not None:
if encap in range(1, 4097): if encap in range(1, 4097):
encap = 'vlan-{0}'.format(encap) encap = 'vlan-{0}'.format(encap)
else: else:
module.fail_json(msg='Valid VLAN assignments are from 1 to 4096') module.fail_json(msg='Valid VLAN assignments are from 1 to 4096')
encap_mode = module.params['encap_mode'] encap_mode = module.params.get('encap_mode')
switching_mode = module.params['switching_mode'] switching_mode = module.params.get('switching_mode')
epg = module.params['epg'] epg = module.params.get('epg')
netflow = aci.boolean(module.params['netflow'], 'enabled', 'disabled') netflow = aci.boolean(module.params.get('netflow'), 'enabled', 'disabled')
primary_encap = module.params['primary_encap'] primary_encap = module.params.get('primary_encap')
if primary_encap is not None: if primary_encap is not None:
if primary_encap in range(1, 4097): if primary_encap in range(1, 4097):
primary_encap = 'vlan-{0}'.format(primary_encap) primary_encap = 'vlan-{0}'.format(primary_encap)
else: else:
module.fail_json(msg='Valid VLAN assignments are from 1 to 4096') module.fail_json(msg='Valid VLAN assignments are from 1 to 4096')
resolution_immediacy = module.params['resolution_immediacy'] resolution_immediacy = module.params.get('resolution_immediacy')
state = module.params['state'] state = module.params.get('state')
tenant = module.params['tenant'] tenant = module.params.get('tenant')
if domain_type in ['l2dom', 'phys'] and vm_provider is not None: if domain_type in ['l2dom', 'phys'] and vm_provider is not None:
module.fail_json(msg="Domain type '%s' cannot have a 'vm_provider'" % domain_type) module.fail_json(msg="Domain type '%s' cannot have a 'vm_provider'" % domain_type)

View file

@ -229,13 +229,13 @@ def main():
], ],
) )
pod_id = module.params['pod_id'] pod_id = module.params.get('pod_id')
serial = module.params['serial'] serial = module.params.get('serial')
node_id = module.params['node_id'] node_id = module.params.get('node_id')
switch = module.params['switch'] switch = module.params.get('switch')
description = module.params['description'] description = module.params.get('description')
role = module.params['role'] role = module.params.get('role')
state = module.params['state'] state = module.params.get('state')
aci = ACIModule(module) aci = ACIModule(module)
aci.construct_url( aci.construct_url(

View file

@ -267,17 +267,17 @@ def main():
], ],
) )
state = module.params['state'] state = module.params.get('state')
name = module.params['name'] name = module.params.get('name')
windowname = module.params['windowname'] windowname = module.params.get('windowname')
recurring = module.params['recurring'] recurring = module.params.get('recurring')
date = module.params['date'] date = module.params.get('date')
hour = module.params['hour'] hour = module.params.get('hour')
minute = module.params['minute'] minute = module.params.get('minute')
maxTime = module.params['maxTime'] maxTime = module.params.get('maxTime')
concurCap = module.params['concurCap'] concurCap = module.params.get('concurCap')
day = module.params['day'] day = module.params.get('day')
description = module.params['description'] description = module.params.get('description')
if recurring: if recurring:
child_configs = [dict(trigRecurrWindowP=dict(attributes=dict(name=windowname, hour=hour, minute=minute, child_configs = [dict(trigRecurrWindowP=dict(attributes=dict(name=windowname, hour=hour, minute=minute,

View file

@ -227,10 +227,10 @@ def main():
], ],
) )
filter_name = module.params['filter'] filter_name = module.params.get('filter')
description = module.params['description'] description = module.params.get('description')
state = module.params['state'] state = module.params.get('state')
tenant = module.params['tenant'] tenant = module.params.get('tenant')
aci = ACIModule(module) aci = ACIModule(module)
aci.construct_url( aci.construct_url(

View file

@ -279,32 +279,32 @@ def main():
aci = ACIModule(module) aci = ACIModule(module)
arp_flag = module.params['arp_flag'] arp_flag = module.params.get('arp_flag')
if arp_flag is not None: if arp_flag is not None:
arp_flag = ARP_FLAG_MAPPING[arp_flag] arp_flag = ARP_FLAG_MAPPING.get(arp_flag)
description = module.params['description'] description = module.params.get('description')
dst_port = module.params['dst_port'] dst_port = module.params.get('dst_port')
if dst_port in FILTER_PORT_MAPPING.keys(): if FILTER_PORT_MAPPING.get(dst_port) is not None:
dst_port = FILTER_PORT_MAPPING[dst_port] dst_port = FILTER_PORT_MAPPING.get(dst_port)
dst_end = module.params['dst_port_end'] dst_end = module.params.get('dst_port_end')
if dst_end in FILTER_PORT_MAPPING.keys(): if FILTER_PORT_MAPPING.get(dst_end) is not None:
dst_end = FILTER_PORT_MAPPING[dst_end] dst_end = FILTER_PORT_MAPPING.get(dst_end)
dst_start = module.params['dst_port_start'] dst_start = module.params.get('dst_port_start')
if dst_start in FILTER_PORT_MAPPING.keys(): if FILTER_PORT_MAPPING.get(dst_start) is not None:
dst_start = FILTER_PORT_MAPPING[dst_start] dst_start = FILTER_PORT_MAPPING.get(dst_start)
entry = module.params['entry'] entry = module.params.get('entry')
ether_type = module.params['ether_type'] ether_type = module.params.get('ether_type')
filter_name = module.params['filter'] filter_name = module.params.get('filter')
icmp_msg_type = module.params['icmp_msg_type'] icmp_msg_type = module.params.get('icmp_msg_type')
if icmp_msg_type is not None: if icmp_msg_type is not None:
icmp_msg_type = ICMP_MAPPING[icmp_msg_type] icmp_msg_type = ICMP_MAPPING.get(icmp_msg_type)
icmp6_msg_type = module.params['icmp6_msg_type'] icmp6_msg_type = module.params.get('icmp6_msg_type')
if icmp6_msg_type is not None: if icmp6_msg_type is not None:
icmp6_msg_type = ICMP6_MAPPING[icmp6_msg_type] icmp6_msg_type = ICMP6_MAPPING.get(icmp6_msg_type)
ip_protocol = module.params['ip_protocol'] ip_protocol = module.params.get('ip_protocol')
state = module.params['state'] state = module.params.get('state')
stateful = aci.boolean(module.params['stateful']) stateful = aci.boolean(module.params.get('stateful'))
tenant = module.params['tenant'] tenant = module.params.get('tenant')
# validate that dst_port is not passed with dst_start or dst_end # validate that dst_port is not passed with dst_start or dst_end
if dst_port is not None and (dst_end is not None or dst_start is not None): if dst_port is not None and (dst_end is not None or dst_start is not None):

View file

@ -184,9 +184,9 @@ def main():
], ],
) )
state = module.params['state'] state = module.params.get('state')
group = module.params['group'] group = module.params.get('group')
firmwarepol = module.params['firmwarepol'] firmwarepol = module.params.get('firmwarepol')
aci = ACIModule(module) aci = ACIModule(module)
aci.construct_url( aci.construct_url(

View file

@ -197,9 +197,9 @@ def main():
], ],
) )
state = module.params['state'] state = module.params.get('state')
group = module.params['group'] group = module.params.get('group')
node = module.params['node'] node = module.params.get('node')
aci = ACIModule(module) aci = ACIModule(module)
aci.construct_url( aci.construct_url(

View file

@ -200,11 +200,11 @@ def main():
], ],
) )
state = module.params['state'] state = module.params.get('state')
name = module.params['name'] name = module.params.get('name')
version = module.params['version'] version = module.params.get('version')
if module.params['ignoreCompat']: if module.params.get('ignoreCompat'):
ignore = 'yes' ignore = 'yes'
else: else:
ignore = 'no' ignore = 'no'

View file

@ -236,13 +236,13 @@ def main():
], ],
) )
polling_interval = module.params['polling_interval'] polling_interval = module.params.get('polling_interval')
url_protocol = module.params['url_protocol'] url_protocol = module.params.get('url_protocol')
state = module.params['state'] state = module.params.get('state')
source = module.params['source'] source = module.params.get('source')
url = module.params['url'] url = module.params.get('url')
url_password = module.params['url_password'] url_password = module.params.get('url_password')
url_username = module.params['url_username'] url_username = module.params.get('url_username')
aci = ACIModule(module) aci = ACIModule(module)
aci.construct_url( aci.construct_url(

View file

@ -209,10 +209,10 @@ def main():
aci = ACIModule(module) aci = ACIModule(module)
cdp_policy = module.params['cdp_policy'] cdp_policy = module.params.get('cdp_policy')
description = module.params['description'] description = module.params.get('description')
admin_state = aci.boolean(module.params['admin_state'], 'enabled', 'disabled') admin_state = aci.boolean(module.params.get('admin_state'), 'enabled', 'disabled')
state = module.params['state'] state = module.params.get('state')
aci.construct_url( aci.construct_url(
root_class=dict( root_class=dict(

View file

@ -190,10 +190,10 @@ def main():
], ],
) )
fc_policy = module.params['fc_policy'] fc_policy = module.params.get('fc_policy')
port_mode = module.params['port_mode'] port_mode = module.params.get('port_mode')
description = module.params['description'] description = module.params.get('description')
state = module.params['state'] state = module.params.get('state')
aci = ACIModule(module) aci = ACIModule(module)
aci.construct_url( aci.construct_url(

View file

@ -211,14 +211,14 @@ def main():
aci = ACIModule(module) aci = ACIModule(module)
l2_policy = module.params['l2_policy'] l2_policy = module.params.get('l2_policy')
vlan_scope = module.params['vlan_scope'] vlan_scope = module.params.get('vlan_scope')
qinq = module.params['qinq'] qinq = module.params.get('qinq')
if qinq is not None: if qinq is not None:
qinq = QINQ_MAPPING[qinq] qinq = QINQ_MAPPING.get(qinq)
vepa = aci.boolean(module.params['vepa'], 'enabled', 'disabled') vepa = aci.boolean(module.params.get('vepa'), 'enabled', 'disabled')
description = module.params['description'] description = module.params.get('description')
state = module.params['state'] state = module.params.get('state')
aci.construct_url( aci.construct_url(
root_class=dict( root_class=dict(

View file

@ -353,26 +353,26 @@ def main():
], ],
) )
policy_group = module.params['policy_group'] policy_group = module.params.get('policy_group')
description = module.params['description'] description = module.params.get('description')
lag_type = module.params['lag_type'] lag_type = module.params.get('lag_type')
link_level_policy = module.params['link_level_policy'] link_level_policy = module.params.get('link_level_policy')
cdp_policy = module.params['cdp_policy'] cdp_policy = module.params.get('cdp_policy')
mcp_policy = module.params['mcp_policy'] mcp_policy = module.params.get('mcp_policy')
lldp_policy = module.params['lldp_policy'] lldp_policy = module.params.get('lldp_policy')
stp_interface_policy = module.params['stp_interface_policy'] stp_interface_policy = module.params.get('stp_interface_policy')
egress_data_plane_policing_policy = module.params['egress_data_plane_policing_policy'] egress_data_plane_policing_policy = module.params.get('egress_data_plane_policing_policy')
ingress_data_plane_policing_policy = module.params['ingress_data_plane_policing_policy'] ingress_data_plane_policing_policy = module.params.get('ingress_data_plane_policing_policy')
priority_flow_control_policy = module.params['priority_flow_control_policy'] priority_flow_control_policy = module.params.get('priority_flow_control_policy')
fibre_channel_interface_policy = module.params['fibre_channel_interface_policy'] fibre_channel_interface_policy = module.params.get('fibre_channel_interface_policy')
slow_drain_policy = module.params['slow_drain_policy'] slow_drain_policy = module.params.get('slow_drain_policy')
port_channel_policy = module.params['port_channel_policy'] port_channel_policy = module.params.get('port_channel_policy')
monitoring_policy = module.params['monitoring_policy'] monitoring_policy = module.params.get('monitoring_policy')
storm_control_interface_policy = module.params['storm_control_interface_policy'] storm_control_interface_policy = module.params.get('storm_control_interface_policy')
l2_interface_policy = module.params['l2_interface_policy'] l2_interface_policy = module.params.get('l2_interface_policy')
port_security_policy = module.params['port_security_policy'] port_security_policy = module.params.get('port_security_policy')
aep = module.params['aep'] aep = module.params.get('aep')
state = module.params['state'] state = module.params.get('state')
if lag_type == 'leaf': if lag_type == 'leaf':
aci_class_name = 'infraAccPortGrp' aci_class_name = 'infraAccPortGrp'

View file

@ -211,9 +211,9 @@ def main():
], ],
) )
leaf_interface_profile = module.params['leaf_interface_profile'] leaf_interface_profile = module.params.get('leaf_interface_profile')
description = module.params['description'] description = module.params.get('description')
state = module.params['state'] state = module.params.get('state')
aci = ACIModule(module) aci = ACIModule(module)
aci.construct_url( aci.construct_url(

View file

@ -198,11 +198,11 @@ def main():
aci = ACIModule(module) aci = ACIModule(module)
lldp_policy = module.params['lldp_policy'] lldp_policy = module.params.get('lldp_policy')
description = module.params['description'] description = module.params.get('description')
receive_state = aci.boolean(module.params['receive_state'], 'enabled', 'disabled') receive_state = aci.boolean(module.params.get('receive_state'), 'enabled', 'disabled')
transmit_state = aci.boolean(module.params['transmit_state'], 'enabled', 'disabled') transmit_state = aci.boolean(module.params.get('transmit_state'), 'enabled', 'disabled')
state = module.params['state'] state = module.params.get('state')
aci.construct_url( aci.construct_url(
root_class=dict( root_class=dict(

View file

@ -191,10 +191,10 @@ def main():
aci = ACIModule(module) aci = ACIModule(module)
mcp = module.params['mcp'] mcp = module.params.get('mcp')
description = module.params['description'] description = module.params.get('description')
admin_state = aci.boolean(module.params['admin_state'], 'enabled', 'disabled') admin_state = aci.boolean(module.params.get('admin_state'), 'enabled', 'disabled')
state = module.params['state'] state = module.params.get('state')
aci.construct_url( aci.construct_url(
root_class=dict( root_class=dict(

View file

@ -318,42 +318,42 @@ def main():
aci = ACIModule(module) aci = ACIModule(module)
tenant = module.params['tenant'] tenant = module.params.get('tenant')
ospf = module.params['ospf'] ospf = module.params.get('ospf')
description = module.params['description'] description = module.params.get('description')
if module.params['controls'] is None: if module.params.get('controls') is None:
controls = None controls = None
else: else:
controls = ','.join(module.params['controls']) controls = ','.join(module.params.get('controls'))
cost = module.params['cost'] cost = module.params.get('cost')
if cost is not None and cost not in range(1, 451): if cost is not None and cost not in range(1, 451):
module.fail_json(msg="Parameter 'cost' is only valid in range between 1 and 450.") module.fail_json(msg="Parameter 'cost' is only valid in range between 1 and 450.")
dead_interval = module.params['dead_interval'] dead_interval = module.params.get('dead_interval')
if dead_interval is not None and dead_interval not in range(1, 65536): if dead_interval is not None and dead_interval not in range(1, 65536):
module.fail_json(msg="Parameter 'dead_interval' is only valid in range between 1 and 65536.") module.fail_json(msg="Parameter 'dead_interval' is only valid in range between 1 and 65536.")
hello_interval = module.params['hello_interval'] hello_interval = module.params.get('hello_interval')
if hello_interval is not None and hello_interval not in range(1, 65536): if hello_interval is not None and hello_interval not in range(1, 65536):
module.fail_json(msg="Parameter 'hello_interval' is only valid in range between 1 and 65536.") module.fail_json(msg="Parameter 'hello_interval' is only valid in range between 1 and 65536.")
network_type = module.params['network_type'] network_type = module.params.get('network_type')
prefix_suppression = aci.boolean(module.params['prefix_suppression'], 'enabled', 'disabled') prefix_suppression = aci.boolean(module.params.get('prefix_suppression'), 'enabled', 'disabled')
priority = module.params['priority'] priority = module.params.get('priority')
if priority is not None and priority not in range(0, 256): if priority is not None and priority not in range(0, 256):
module.fail_json(msg="Parameter 'priority' is only valid in range between 1 and 255.") module.fail_json(msg="Parameter 'priority' is only valid in range between 1 and 255.")
retransmit_interval = module.params['retransmit_interval'] retransmit_interval = module.params.get('retransmit_interval')
if retransmit_interval is not None and retransmit_interval not in range(1, 65536): if retransmit_interval is not None and retransmit_interval not in range(1, 65536):
module.fail_json(msg="Parameter 'retransmit_interval' is only valid in range between 1 and 65536.") module.fail_json(msg="Parameter 'retransmit_interval' is only valid in range between 1 and 65536.")
transmit_delay = module.params['transmit_delay'] transmit_delay = module.params.get('transmit_delay')
if transmit_delay is not None and transmit_delay not in range(1, 451): if transmit_delay is not None and transmit_delay not in range(1, 451):
module.fail_json(msg="Parameter 'transmit_delay' is only valid in range between 1 and 450.") module.fail_json(msg="Parameter 'transmit_delay' is only valid in range between 1 and 450.")
state = module.params['state'] state = module.params.get('state')
aci.construct_url( aci.construct_url(
root_class=dict( root_class=dict(

View file

@ -246,28 +246,28 @@ def main():
], ],
) )
port_channel = module.params['port_channel'] port_channel = module.params.get('port_channel')
description = module.params['description'] description = module.params.get('description')
min_links = module.params['min_links'] min_links = module.params.get('min_links')
if min_links is not None and min_links not in range(1, 17): if min_links is not None and min_links not in range(1, 17):
module.fail_json(msg='The "min_links" must be a value between 1 and 16') module.fail_json(msg='The "min_links" must be a value between 1 and 16')
max_links = module.params['max_links'] max_links = module.params.get('max_links')
if max_links is not None and max_links not in range(1, 17): if max_links is not None and max_links not in range(1, 17):
module.fail_json(msg='The "max_links" must be a value between 1 and 16') module.fail_json(msg='The "max_links" must be a value between 1 and 16')
mode = module.params['mode'] mode = module.params.get('mode')
state = module.params['state'] state = module.params.get('state')
# Build ctrl value for request # Build ctrl value for request
ctrl = [] ctrl = []
if module.params['fast_select'] is True: if module.params.get('fast_select') is True:
ctrl.append('fast-sel-hot-stdby') ctrl.append('fast-sel-hot-stdby')
if module.params['graceful_convergence'] is True: if module.params.get('graceful_convergence') is True:
ctrl.append('graceful-conv') ctrl.append('graceful-conv')
if module.params['load_defer'] is True: if module.params.get('load_defer') is True:
ctrl.append('load-defer') ctrl.append('load-defer')
if module.params['suspend_individual'] is True: if module.params.get('suspend_individual') is True:
ctrl.append('susp-individual') ctrl.append('susp-individual')
if module.params['symmetric_hash'] is True: if module.params.get('symmetric_hash') is True:
ctrl.append('symmetric-hash') ctrl.append('symmetric-hash')
if not ctrl: if not ctrl:
ctrl = None ctrl = None

View file

@ -199,15 +199,15 @@ def main():
], ],
) )
port_security = module.params['port_security'] port_security = module.params.get('port_security')
description = module.params['description'] description = module.params.get('description')
max_end_points = module.params['max_end_points'] max_end_points = module.params.get('max_end_points')
port_security_timeout = module.params['port_security_timeout'] port_security_timeout = module.params.get('port_security_timeout')
if max_end_points is not None and max_end_points not in range(12001): if max_end_points is not None and max_end_points not in range(12001):
module.fail_json(msg='The "max_end_points" must be between 0 and 12000') module.fail_json(msg='The "max_end_points" must be between 0 and 12000')
if port_security_timeout is not None and port_security_timeout not in range(60, 3601): if port_security_timeout is not None and port_security_timeout not in range(60, 3601):
module.fail_json(msg='The "port_security_timeout" must be between 60 and 3600') module.fail_json(msg='The "port_security_timeout" must be between 60 and 3600')
state = module.params['state'] state = module.params.get('state')
aci = ACIModule(module) aci = ACIModule(module)
aci.construct_url( aci.construct_url(

View file

@ -207,10 +207,10 @@ def main():
], ],
) )
leaf_profile = module.params['leaf_profile'] leaf_profile = module.params.get('leaf_profile')
# WARNING: interface_selector accepts non existing interface_profile names and they appear on APIC gui with a state of "missing-target" # WARNING: interface_selector accepts non existing interface_profile names and they appear on APIC gui with a state of "missing-target"
interface_selector = module.params['interface_selector'] interface_selector = module.params.get('interface_selector')
state = module.params['state'] state = module.params.get('state')
# Defining the interface profile tDn for clarity # Defining the interface profile tDn for clarity
interface_selector_tDn = 'uni/infra/accportprof-{0}'.format(interface_selector) interface_selector_tDn = 'uni/infra/accportprof-{0}'.format(interface_selector)

View file

@ -269,16 +269,16 @@ def main():
aci = ACIModule(module) aci = ACIModule(module)
l3out = module.params['l3out'] l3out = module.params.get('l3out')
domain = module.params['domain'] domain = module.params.get('domain')
dscp = module.params['dscp'] dscp = module.params.get('dscp')
description = module.params['description'] description = module.params.get('description')
enforceRtctrl = module.params['route_control'] enforceRtctrl = module.params.get('route_control')
vrf = module.params['vrf'] vrf = module.params.get('vrf')
l3protocol = module.params['l3protocol'] l3protocol = module.params.get('l3protocol')
asn = module.params['asn'] asn = module.params.get('asn')
state = module.params['state'] state = module.params.get('state')
tenant = module.params['tenant'] tenant = module.params.get('tenant')
if l3protocol: if l3protocol:
if 'eigrp' in l3protocol and asn is None: if 'eigrp' in l3protocol and asn is None:

View file

@ -248,13 +248,13 @@ def main():
aci = ACIModule(module) aci = ACIModule(module)
tenant = module.params['tenant'] tenant = module.params.get('tenant')
l3out = module.params['l3out'] l3out = module.params.get('l3out')
extepg = module.params['extepg'] extepg = module.params.get('extepg')
description = module.params['description'] description = module.params.get('description')
preferred_group = aci.boolean(module.params['preferred_group'], 'include', 'exclude') preferred_group = aci.boolean(module.params.get('preferred_group'), 'include', 'exclude')
dscp = module.params['dscp'] dscp = module.params.get('dscp')
state = module.params['state'] state = module.params.get('state')
aci.construct_url( aci.construct_url(
root_class=dict( root_class=dict(

View file

@ -259,14 +259,14 @@ def main():
aci = ACIModule(module) aci = ACIModule(module)
tenant = module.params['tenant'] tenant = module.params.get('tenant')
l3out = module.params['l3out'] l3out = module.params.get('l3out')
extepg = module.params['extepg'] extepg = module.params.get('extepg')
network = module.params['network'] network = module.params.get('network')
description = module.params['description'] description = module.params.get('description')
subnet_name = module.params['subnet_name'] subnet_name = module.params.get('subnet_name')
scope = ','.join(sorted(module.params['scope'])) scope = ','.join(sorted(module.params.get('scope')))
state = module.params['state'] state = module.params.get('state')
aci.construct_url( aci.construct_url(
root_class=dict( root_class=dict(

View file

@ -202,11 +202,11 @@ def main():
], ],
) )
rtp = module.params['rtp'] rtp = module.params.get('rtp')
description = module.params['description'] description = module.params.get('description')
tag = module.params['tag'] tag = module.params.get('tag')
state = module.params['state'] state = module.params.get('state')
tenant = module.params['tenant'] tenant = module.params.get('tenant')
aci = ACIModule(module) aci = ACIModule(module)
aci.construct_url( aci.construct_url(

View file

@ -182,9 +182,9 @@ def main():
], ],
) )
state = module.params['state'] state = module.params.get('state')
group = module.params['group'] group = module.params.get('group')
policy = module.params['policy'] policy = module.params.get('policy')
aci = ACIModule(module) aci = ACIModule(module)
aci.construct_url( aci.construct_url(

View file

@ -192,9 +192,9 @@ def main():
], ],
) )
state = module.params['state'] state = module.params.get('state')
group = module.params['group'] group = module.params.get('group')
node = module.params['node'] node = module.params.get('node')
aci = ACIModule(module) aci = ACIModule(module)
aci.construct_url( aci.construct_url(

View file

@ -214,13 +214,13 @@ def main():
aci = ACIModule(module) aci = ACIModule(module)
state = module.params['state'] state = module.params.get('state')
name = module.params['name'] name = module.params.get('name')
runmode = module.params['runmode'] runmode = module.params.get('runmode')
scheduler = module.params['scheduler'] scheduler = module.params.get('scheduler')
adminst = module.params['adminst'] adminst = module.params.get('adminst')
graceful = aci.boolean(module.params['graceful']) graceful = aci.boolean(module.params.get('graceful'))
ignoreCompat = aci.boolean(module.params['ignoreCompat']) ignoreCompat = aci.boolean(module.params.get('ignoreCompat'))
aci.construct_url( aci.construct_url(
root_class=dict( root_class=dict(

View file

@ -335,9 +335,9 @@ def main():
mutually_exclusive=[['content', 'src']], mutually_exclusive=[['content', 'src']],
) )
content = module.params['content'] content = module.params.get('content')
path = module.params['path'] path = module.params.get('path')
src = module.params['src'] src = module.params.get('src')
# Report missing file # Report missing file
file_exists = False file_exists = False
@ -394,36 +394,36 @@ def main():
module.fail_json(msg='Failed to parse provided XML payload: %s' % to_text(e), payload=payload) module.fail_json(msg='Failed to parse provided XML payload: %s' % to_text(e), payload=payload)
# Perform actual request using auth cookie (Same as aci.request(), but also supports XML) # Perform actual request using auth cookie (Same as aci.request(), but also supports XML)
if 'port' in aci.params and aci.params['port'] is not None: if 'port' in aci.params and aci.params.get('port') is not None:
aci.url = '%(protocol)s://%(host)s:%(port)s/' % aci.params + path.lstrip('/') aci.url = '%(protocol)s://%(host)s:%(port)s/' % aci.params + path.lstrip('/')
else: else:
aci.url = '%(protocol)s://%(host)s/' % aci.params + path.lstrip('/') aci.url = '%(protocol)s://%(host)s/' % aci.params + path.lstrip('/')
if aci.params['method'] != 'get': if aci.params.get('method') != 'get':
path += '?rsp-subtree=modified' path += '?rsp-subtree=modified'
aci.url = update_qsl(aci.url, {'rsp-subtree': 'modified'}) aci.url = update_qsl(aci.url, {'rsp-subtree': 'modified'})
# Sign and encode request as to APIC's wishes # Sign and encode request as to APIC's wishes
if aci.params['private_key'] is not None: if aci.params.get('private_key') is not None:
aci.cert_auth(path=path, payload=payload) aci.cert_auth(path=path, payload=payload)
aci.method = aci.params['method'].upper() aci.method = aci.params.get('method').upper()
# Perform request # Perform request
resp, info = fetch_url(module, aci.url, resp, info = fetch_url(module, aci.url,
data=payload, data=payload,
headers=aci.headers, headers=aci.headers,
method=aci.method, method=aci.method,
timeout=aci.params['timeout'], timeout=aci.params.get('timeout'),
use_proxy=aci.params['use_proxy']) use_proxy=aci.params.get('use_proxy'))
aci.response = info['msg'] aci.response = info.get('msg')
aci.status = info['status'] aci.status = info.get('status')
# Report failure # Report failure
if info['status'] != 200: if info.get('status') != 200:
try: try:
# APIC error # APIC error
aci.response_type(info['body'], rest_type) aci.response_type(info.get('body'), rest_type)
aci.fail_json(msg='APIC Error %(code)s: %(text)s' % aci.error) aci.fail_json(msg='APIC Error %(code)s: %(text)s' % aci.error)
except KeyError: except KeyError:
# Connection error # Connection error

View file

@ -332,21 +332,21 @@ def main():
], ],
) )
tenant = module.params['tenant'] tenant = module.params.get('tenant')
ap = module.params['ap'] ap = module.params.get('ap')
epg = module.params['epg'] epg = module.params.get('epg')
description = module.params['description'] description = module.params.get('description')
encap_id = module.params['encap_id'] encap_id = module.params.get('encap_id')
primary_encap_id = module.params['primary_encap_id'] primary_encap_id = module.params.get('primary_encap_id')
deploy_immediacy = module.params['deploy_immediacy'] deploy_immediacy = module.params.get('deploy_immediacy')
interface_mode = module.params['interface_mode'] interface_mode = module.params.get('interface_mode')
interface_type = module.params['interface_type'] interface_type = module.params.get('interface_type')
pod_id = module.params['pod_id'] pod_id = module.params.get('pod_id')
leafs = module.params['leafs'] leafs = module.params.get('leafs')
if leafs is not None: if leafs is not None:
# Process leafs, and support dash-delimited leafs # Process leafs, and support dash-delimited leafs
leafs = [] leafs = []
for leaf in module.params['leafs']: for leaf in module.params.get('leafs'):
# Users are likely to use integers for leaf IDs, which would raise an exception when using the join method # Users are likely to use integers for leaf IDs, which would raise an exception when using the join method
leafs.extend(str(leaf).split('-')) leafs.extend(str(leaf).split('-'))
if len(leafs) == 1: if len(leafs) == 1:
@ -360,9 +360,9 @@ def main():
leafs = "-".join(leafs) leafs = "-".join(leafs)
else: else:
module.fail_json(msg='The "leafs" parameter must not have more than 2 entries') module.fail_json(msg='The "leafs" parameter must not have more than 2 entries')
interface = module.params['interface'] interface = module.params.get('interface')
extpaths = module.params['extpaths'] extpaths = module.params.get('extpaths')
state = module.params['state'] state = module.params.get('state')
if encap_id is not None: if encap_id is not None:
if encap_id not in range(1, 4097): if encap_id not in range(1, 4097):

View file

@ -261,15 +261,15 @@ def main():
] ]
) )
description = module.params['description'] description = module.params.get('description')
leaf_profile = module.params['leaf_profile'] leaf_profile = module.params.get('leaf_profile')
leaf = module.params['leaf'] leaf = module.params.get('leaf')
leaf_node_blk = module.params['leaf_node_blk'] leaf_node_blk = module.params.get('leaf_node_blk')
leaf_node_blk_description = module.params['leaf_node_blk_description'] leaf_node_blk_description = module.params.get('leaf_node_blk_description')
from_ = module.params['from'] from_ = module.params.get('from')
to_ = module.params['to'] to_ = module.params.get('to')
policy_group = module.params['policy_group'] policy_group = module.params.get('policy_group')
state = module.params['state'] state = module.params.get('state')
# Build child_configs dynamically # Build child_configs dynamically
child_configs = [ child_configs = [

View file

@ -203,9 +203,9 @@ def main():
], ],
) )
leaf_profile = module.params['leaf_profile'] leaf_profile = module.params.get('leaf_profile')
description = module.params['description'] description = module.params.get('description')
state = module.params['state'] state = module.params.get('state')
aci = ACIModule(module) aci = ACIModule(module)
aci.construct_url( aci.construct_url(

View file

@ -234,12 +234,12 @@ def main():
], ],
) )
protection_group = module.params['protection_group'] protection_group = module.params.get('protection_group')
protection_group_id = module.params['protection_group_id'] protection_group_id = module.params.get('protection_group_id')
vpc_domain_policy = module.params['vpc_domain_policy'] vpc_domain_policy = module.params.get('vpc_domain_policy')
switch_1_id = module.params['switch_1_id'] switch_1_id = module.params.get('switch_1_id')
switch_2_id = module.params['switch_2_id'] switch_2_id = module.params.get('switch_2_id')
state = module.params['state'] state = module.params.get('state')
aci = ACIModule(module) aci = ACIModule(module)
aci.construct_url( aci.construct_url(

View file

@ -232,11 +232,11 @@ def main():
], ],
) )
taboo_contract = module.params['taboo_contract'] taboo_contract = module.params.get('taboo_contract')
description = module.params['description'] description = module.params.get('description')
scope = module.params['scope'] scope = module.params.get('scope')
state = module.params['state'] state = module.params.get('state')
tenant = module.params['tenant'] tenant = module.params.get('tenant')
aci = ACIModule(module) aci = ACIModule(module)
aci.construct_url( aci.construct_url(

View file

@ -216,9 +216,9 @@ def main():
], ],
) )
description = module.params['description'] description = module.params.get('description')
state = module.params['state'] state = module.params.get('state')
tenant = module.params['tenant'] tenant = module.params.get('tenant')
aci = ACIModule(module) aci = ACIModule(module)
aci.construct_url( aci.construct_url(

View file

@ -192,10 +192,10 @@ def main():
], ],
) )
action_rule = module.params['action_rule'] action_rule = module.params.get('action_rule')
description = module.params['description'] description = module.params.get('description')
state = module.params['state'] state = module.params.get('state')
tenant = module.params['tenant'] tenant = module.params.get('tenant')
aci = ACIModule(module) aci = ACIModule(module)
aci.construct_url( aci.construct_url(

View file

@ -275,36 +275,36 @@ def main():
], ],
) )
epr_policy = module.params['epr_policy'] epr_policy = module.params.get('epr_policy')
bounce_age = module.params['bounce_age'] bounce_age = module.params.get('bounce_age')
if bounce_age is not None and bounce_age != 0 and bounce_age not in range(150, 65536): if bounce_age is not None and bounce_age != 0 and bounce_age not in range(150, 65536):
module.fail_json(msg="The bounce_age must be a value of 0 or between 150 and 65535") module.fail_json(msg="The bounce_age must be a value of 0 or between 150 and 65535")
if bounce_age == 0: if bounce_age == 0:
bounce_age = 'infinite' bounce_age = 'infinite'
bounce_trigger = module.params['bounce_trigger'] bounce_trigger = module.params.get('bounce_trigger')
if bounce_trigger is not None: if bounce_trigger is not None:
bounce_trigger = BOUNCE_TRIG_MAPPING[bounce_trigger] bounce_trigger = BOUNCE_TRIG_MAPPING[bounce_trigger]
description = module.params['description'] description = module.params.get('description')
hold_interval = module.params['hold_interval'] hold_interval = module.params.get('hold_interval')
if hold_interval is not None and hold_interval not in range(5, 65536): if hold_interval is not None and hold_interval not in range(5, 65536):
module.fail_json(msg="The hold_interval must be a value between 5 and 65535") module.fail_json(msg="The hold_interval must be a value between 5 and 65535")
local_ep_interval = module.params['local_ep_interval'] local_ep_interval = module.params.get('local_ep_interval')
if local_ep_interval is not None and local_ep_interval != 0 and local_ep_interval not in range(120, 65536): if local_ep_interval is not None and local_ep_interval != 0 and local_ep_interval not in range(120, 65536):
module.fail_json(msg="The local_ep_interval must be a value of 0 or between 120 and 65535") module.fail_json(msg="The local_ep_interval must be a value of 0 or between 120 and 65535")
if local_ep_interval == 0: if local_ep_interval == 0:
local_ep_interval = "infinite" local_ep_interval = "infinite"
move_frequency = module.params['move_frequency'] move_frequency = module.params.get('move_frequency')
if move_frequency is not None and move_frequency not in range(65536): if move_frequency is not None and move_frequency not in range(65536):
module.fail_json(msg="The move_frequency must be a value between 0 and 65535") module.fail_json(msg="The move_frequency must be a value between 0 and 65535")
if move_frequency == 0: if move_frequency == 0:
move_frequency = "none" move_frequency = "none"
remote_ep_interval = module.params['remote_ep_interval'] remote_ep_interval = module.params.get('remote_ep_interval')
if remote_ep_interval is not None and remote_ep_interval not in range(120, 65536): if remote_ep_interval is not None and remote_ep_interval not in range(120, 65536):
module.fail_json(msg="The remote_ep_interval must be a value of 0 or between 120 and 65535") module.fail_json(msg="The remote_ep_interval must be a value of 0 or between 120 and 65535")
if remote_ep_interval == 0: if remote_ep_interval == 0:
remote_ep_interval = "infinite" remote_ep_interval = "infinite"
state = module.params['state'] state = module.params.get('state')
tenant = module.params['tenant'] tenant = module.params.get('tenant')
aci = ACIModule(module) aci = ACIModule(module)
aci.construct_url( aci.construct_url(

View file

@ -194,10 +194,10 @@ def main():
], ],
) )
dst_group = module.params['dst_group'] dst_group = module.params.get('dst_group')
description = module.params['description'] description = module.params.get('description')
state = module.params['state'] state = module.params.get('state')
tenant = module.params['tenant'] tenant = module.params.get('tenant')
aci = ACIModule(module) aci = ACIModule(module)
aci.construct_url( aci.construct_url(

View file

@ -206,12 +206,12 @@ def main():
aci = ACIModule(module) aci = ACIModule(module)
admin_state = aci.boolean(module.params['admin_state'], 'enabled', 'disabled') admin_state = aci.boolean(module.params.get('admin_state'), 'enabled', 'disabled')
description = module.params['description'] description = module.params.get('description')
dst_group = module.params['dst_group'] dst_group = module.params.get('dst_group')
src_group = module.params['src_group'] src_group = module.params.get('src_group')
state = module.params['state'] state = module.params.get('state')
tenant = module.params['tenant'] tenant = module.params.get('tenant')
aci.construct_url( aci.construct_url(
root_class=dict( root_class=dict(

View file

@ -198,11 +198,11 @@ def main():
], ],
) )
description = module.params['description'] description = module.params.get('description')
dst_group = module.params['dst_group'] dst_group = module.params.get('dst_group')
src_group = module.params['src_group'] src_group = module.params.get('src_group')
state = module.params['state'] state = module.params.get('state')
tenant = module.params['tenant'] tenant = module.params.get('tenant')
aci = ACIModule(module) aci = ACIModule(module)
aci.construct_url( aci.construct_url(

View file

@ -225,10 +225,10 @@ def main():
], ],
) )
description = module.params['description'] description = module.params.get('description')
pool = module.params['pool'] pool = module.params.get('pool')
pool_allocation_mode = module.params['pool_allocation_mode'] pool_allocation_mode = module.params.get('pool_allocation_mode')
state = module.params['state'] state = module.params.get('state')
pool_name = pool pool_name = pool

View file

@ -264,14 +264,14 @@ def main():
], ],
) )
allocation_mode = module.params['allocation_mode'] allocation_mode = module.params.get('allocation_mode')
description = module.params['description'] description = module.params.get('description')
pool = module.params['pool'] pool = module.params.get('pool')
pool_allocation_mode = module.params['pool_allocation_mode'] pool_allocation_mode = module.params.get('pool_allocation_mode')
block_end = module.params['block_end'] block_end = module.params.get('block_end')
block_name = module.params['block_name'] block_name = module.params.get('block_name')
block_start = module.params['block_start'] block_start = module.params.get('block_start')
state = module.params['state'] state = module.params.get('state')
if block_end is not None: if block_end is not None:
encap_end = 'vlan-{0}'.format(block_end) encap_end = 'vlan-{0}'.format(block_end)

View file

@ -238,7 +238,7 @@ def main():
argument_spec = aci_argument_spec() argument_spec = aci_argument_spec()
argument_spec.update( argument_spec.update(
name=dict(type='str', aliases=['credential_name', 'credential_profile']), name=dict(type='str', aliases=['credential_name', 'credential_profile']),
credential_password=dict(type='str'), credential_password=dict(type='str', no_log=True),
credential_username=dict(type='str'), credential_username=dict(type='str'),
description=dict(type='str', aliases=['descr']), description=dict(type='str', aliases=['descr']),
domain=dict(type='str', aliases=['domain_name', 'domain_profile']), domain=dict(type='str', aliases=['domain_name', 'domain_profile']),
@ -255,17 +255,17 @@ def main():
], ],
) )
name = module.params['name'] name = module.params.get('name')
credential_password = module.params['credential_password'] credential_password = module.params.get('credential_password')
credential_username = module.params['credential_username'] credential_username = module.params.get('credential_username')
description = module.params['description'] description = module.params.get('description')
domain = module.params['domain'] domain = module.params.get('domain')
state = module.params['state'] state = module.params.get('state')
vm_provider = module.params['vm_provider'] vm_provider = module.params.get('vm_provider')
credential_class = 'vmmUsrAccP' credential_class = 'vmmUsrAccP'
usracc_mo = 'uni/vmmp-{0}/dom-{1}/usracc-{2}'.format(VM_PROVIDER_MAPPING[vm_provider], domain, name) usracc_mo = 'uni/vmmp-{0}/dom-{1}/usracc-{2}'.format(VM_PROVIDER_MAPPING.get(vm_provider), domain, name)
usracc_rn = 'vmmp-{0}/dom-{1}/usracc-{2}'.format(VM_PROVIDER_MAPPING[vm_provider], domain, name) usracc_rn = 'vmmp-{0}/dom-{1}/usracc-{2}'.format(VM_PROVIDER_MAPPING.get(vm_provider), domain, name)
# Ensure that querying all objects works when only domain is provided # Ensure that querying all objects works when only domain is provided
if name is None: if name is None:

View file

@ -238,12 +238,12 @@ def main():
], ],
) )
description = module.params['description'] description = module.params.get('description')
policy_control_direction = module.params['policy_control_direction'] policy_control_direction = module.params.get('policy_control_direction')
policy_control_preference = module.params['policy_control_preference'] policy_control_preference = module.params.get('policy_control_preference')
state = module.params['state'] state = module.params.get('state')
tenant = module.params['tenant'] tenant = module.params.get('tenant')
vrf = module.params['vrf'] vrf = module.params.get('vrf')
aci = ACIModule(module) aci = ACIModule(module)
aci.construct_url( aci.construct_url(

View file

@ -107,9 +107,9 @@ def main():
], ],
) )
label = module.params['label'] label = module.params.get('label')
label_type = module.params['type'] label_type = module.params.get('type')
state = module.params['state'] state = module.params.get('state')
mso = MSOModule(module) mso = MSOModule(module)
@ -120,7 +120,7 @@ def main():
if label: if label:
mso.existing = mso.get_obj(path, displayName=label) mso.existing = mso.get_obj(path, displayName=label)
if mso.existing: if mso.existing:
label_id = mso.existing['id'] label_id = mso.existing.get('id')
# If we found an existing object, continue with it # If we found an existing object, continue with it
path = 'labels/{id}'.format(id=label_id) path = 'labels/{id}'.format(id=label_id)
else: else:

View file

@ -161,10 +161,10 @@ def main():
], ],
) )
role = module.params['role'] role = module.params.get('role')
description = module.params['description'] description = module.params.get('description')
permissions = module.params['permissions'] permissions = module.params.get('permissions')
state = module.params['state'] state = module.params.get('state')
mso = MSOModule(module) mso = MSOModule(module)
@ -175,7 +175,7 @@ def main():
if role: if role:
mso.existing = mso.get_obj(path, name=role) mso.existing = mso.get_obj(path, name=role)
if mso.existing: if mso.existing:
role_id = mso.existing['id'] role_id = mso.existing.get('id')
# If we found an existing object, continue with it # If we found an existing object, continue with it
path = 'roles/{id}'.format(id=role_id) path = 'roles/{id}'.format(id=role_id)
else: else:

View file

@ -131,10 +131,10 @@ def main():
], ],
) )
schema = module.params['schema'] schema = module.params.get('schema')
templates = module.params['templates'] templates = module.params.get('templates')
sites = module.params['sites'] sites = module.params.get('sites')
state = module.params['state'] state = module.params.get('state')
mso = MSOModule(module) mso = MSOModule(module)
@ -145,7 +145,7 @@ def main():
if schema: if schema:
mso.existing = mso.get_obj(path, displayName=schema) mso.existing = mso.get_obj(path, displayName=schema)
if mso.existing: if mso.existing:
schema_id = mso.existing['id'] schema_id = mso.existing.get('id')
path = 'schemas/{id}'.format(id=schema_id) path = 'schemas/{id}'.format(id=schema_id)
else: else:
mso.existing = mso.query_objs(path) mso.existing = mso.query_objs(path)

View file

@ -122,10 +122,10 @@ def main():
], ],
) )
schema = module.params['schema'] schema = module.params.get('schema')
site = module.params['site'] site = module.params.get('site')
template = module.params['template'] template = module.params.get('template')
state = module.params['state'] state = module.params.get('state')
mso = MSOModule(module) mso = MSOModule(module)
@ -142,13 +142,13 @@ def main():
mso.existing = {} mso.existing = {}
if 'sites' in schema_obj: if 'sites' in schema_obj:
sites = [(s['siteId'], s['templateName']) for s in schema_obj['sites']] sites = [(s.get('siteId'), s.get('templateName')) for s in schema_obj.get('sites')]
if template: if template:
if (site_id, template) in sites: if (site_id, template) in sites:
site_idx = sites.index((site_id, template)) site_idx = sites.index((site_id, template))
mso.existing = schema_obj['sites'][site_idx] mso.existing = schema_obj.get('sites')[site_idx]
else: else:
mso.existing = schema_obj['sites'] mso.existing = schema_obj.get('sites')
if state == 'query': if state == 'query':
if not mso.existing: if not mso.existing:

View file

@ -131,11 +131,11 @@ def main():
], ],
) )
schema = module.params['schema'] schema = module.params.get('schema')
site = module.params['site'] site = module.params.get('site')
template = module.params['template'] template = module.params.get('template')
anp = module.params['anp'] anp = module.params.get('anp')
state = module.params['state'] state = module.params.get('state')
mso = MSOModule(module) mso = MSOModule(module)
@ -145,13 +145,13 @@ def main():
mso.fail_json(msg="Provided schema '{0}' does not exist".format(schema)) mso.fail_json(msg="Provided schema '{0}' does not exist".format(schema))
schema_path = 'schemas/{id}'.format(**schema_obj) schema_path = 'schemas/{id}'.format(**schema_obj)
schema_id = schema_obj['id'] schema_id = schema_obj.get('id')
# Get site # Get site
site_id = mso.lookup_site(site) site_id = mso.lookup_site(site)
# Get site_idx # Get site_idx
sites = [(s['siteId'], s['templateName']) for s in schema_obj['sites']] sites = [(s.get('siteId'), s.get('templateName')) for s in schema_obj.get('sites')]
if (site_id, template) not in sites: if (site_id, template) not in sites:
mso.fail_json(msg="Provided site/template '{0}-{1}' does not exist. Existing sites/templates: {2}".format(site, template, ', '.join(sites))) mso.fail_json(msg="Provided site/template '{0}-{1}' does not exist. Existing sites/templates: {2}".format(site, template, ', '.join(sites)))
@ -162,16 +162,16 @@ def main():
# Get ANP # Get ANP
anp_ref = mso.anp_ref(schema_id=schema_id, template=template, anp=anp) anp_ref = mso.anp_ref(schema_id=schema_id, template=template, anp=anp)
anps = [a['anpRef'] for a in schema_obj['sites'][site_idx]['anps']] anps = [a.get('anpRef') for a in schema_obj.get('sites')[site_idx]['anps']]
if anp is not None and anp_ref in anps: if anp is not None and anp_ref in anps:
anp_idx = anps.index(anp_ref) anp_idx = anps.index(anp_ref)
anp_path = '/sites/{0}/anps/{1}'.format(site_template, anp) anp_path = '/sites/{0}/anps/{1}'.format(site_template, anp)
mso.existing = schema_obj['sites'][site_idx]['anps'][anp_idx] mso.existing = schema_obj.get('sites')[site_idx]['anps'][anp_idx]
if state == 'query': if state == 'query':
if anp is None: if anp is None:
mso.existing = schema_obj['sites'][site_idx]['anps'] mso.existing = schema_obj.get('sites')[site_idx]['anps']
elif not mso.existing: elif not mso.existing:
mso.fail_json(msg="ANP '{anp}' not found".format(anp=anp)) mso.fail_json(msg="ANP '{anp}' not found".format(anp=anp))
mso.exit_json() mso.exit_json()

View file

@ -141,12 +141,12 @@ def main():
], ],
) )
schema = module.params['schema'] schema = module.params.get('schema')
site = module.params['site'] site = module.params.get('site')
template = module.params['template'] template = module.params.get('template')
anp = module.params['anp'] anp = module.params.get('anp')
epg = module.params['epg'] epg = module.params.get('epg')
state = module.params['state'] state = module.params.get('state')
mso = MSOModule(module) mso = MSOModule(module)
@ -156,11 +156,11 @@ def main():
mso.fail_json(msg="Provided schema '{0}' does not exist".format(schema)) mso.fail_json(msg="Provided schema '{0}' does not exist".format(schema))
schema_path = 'schemas/{id}'.format(**schema_obj) schema_path = 'schemas/{id}'.format(**schema_obj)
schema_id = schema_obj['id'] schema_id = schema_obj.get('id')
# Get site # Get site
site_id = mso.lookup_site(site) site_id = mso.lookup_site(site)
sites = [(s['siteId'], s['templateName']) for s in schema_obj['sites']] sites = [(s.get('siteId'), s.get('templateName')) for s in schema_obj.get('sites')]
if (site_id, template) not in sites: if (site_id, template) not in sites:
mso.fail_json(msg="Provided site/template '{0}-{1}' does not exist. Existing sites/templates: {2}".format(site, template, ', '.join(sites))) mso.fail_json(msg="Provided site/template '{0}-{1}' does not exist. Existing sites/templates: {2}".format(site, template, ', '.join(sites)))
@ -171,22 +171,22 @@ def main():
# Get ANP # Get ANP
anp_ref = mso.anp_ref(schema_id=schema_id, template=template, anp=anp) anp_ref = mso.anp_ref(schema_id=schema_id, template=template, anp=anp)
anps = [a['anpRef'] for a in schema_obj['sites'][site_idx]['anps']] anps = [a.get('anpRef') for a in schema_obj.get('sites')[site_idx]['anps']]
if anp_ref not in anps: if anp_ref not in anps:
mso.fail_json(msg="Provided anp '{0}' does not exist. Existing anps: {1}".format(anp, ', '.join(anps))) mso.fail_json(msg="Provided anp '{0}' does not exist. Existing anps: {1}".format(anp, ', '.join(anps)))
anp_idx = anps.index(anp_ref) anp_idx = anps.index(anp_ref)
# Get EPG # Get EPG
epg_ref = mso.epg_ref(schema_id=schema_id, template=template, anp=anp, epg=epg) epg_ref = mso.epg_ref(schema_id=schema_id, template=template, anp=anp, epg=epg)
epgs = [e['epgRef'] for e in schema_obj['sites'][site_idx]['anps'][anp_idx]['epgs']] epgs = [e.get('epgRef') for e in schema_obj.get('sites')[site_idx]['anps'][anp_idx]['epgs']]
if epg is not None and epg_ref in epgs: if epg is not None and epg_ref in epgs:
epg_idx = epgs.index(epg_ref) epg_idx = epgs.index(epg_ref)
epg_path = '/sites/{0}/anps/{1}/epgs/{2}'.format(site_template, anp, epg) epg_path = '/sites/{0}/anps/{1}/epgs/{2}'.format(site_template, anp, epg)
mso.existing = schema_obj['sites'][site_idx]['anps'][anp_idx]['epgs'][epg_idx] mso.existing = schema_obj.get('sites')[site_idx]['anps'][anp_idx]['epgs'][epg_idx]
if state == 'query': if state == 'query':
if epg is None: if epg is None:
mso.existing = schema_obj['sites'][site_idx]['anps'][anp_idx]['epgs'] mso.existing = schema_obj.get('sites')[site_idx]['anps'][anp_idx]['epgs']
elif not mso.existing: elif not mso.existing:
mso.fail_json(msg="EPG '{epg}' not found".format(epg=epg)) mso.fail_json(msg="EPG '{epg}' not found".format(epg=epg))
mso.exit_json() mso.exit_json()

View file

@ -232,26 +232,26 @@ def main():
], ],
) )
schema = module.params['schema'] schema = module.params.get('schema')
site = module.params['site'] site = module.params.get('site')
template = module.params['template'] template = module.params.get('template')
anp = module.params['anp'] anp = module.params.get('anp')
epg = module.params['epg'] epg = module.params.get('epg')
domain_association_type = module.params['domain_association_type'] domain_association_type = module.params.get('domain_association_type')
domain_profile = module.params['domain_profile'] domain_profile = module.params.get('domain_profile')
deployment_immediacy = module.params['deployment_immediacy'] deployment_immediacy = module.params.get('deployment_immediacy')
resolution_immediacy = module.params['resolution_immediacy'] resolution_immediacy = module.params.get('resolution_immediacy')
state = module.params['state'] state = module.params.get('state')
micro_seg_vlan_type = module.params['micro_seg_vlan_type'] micro_seg_vlan_type = module.params.get('micro_seg_vlan_type')
micro_seg_vlan = module.params['micro_seg_vlan'] micro_seg_vlan = module.params.get('micro_seg_vlan')
port_encap_vlan_type = module.params['port_encap_vlan_type'] port_encap_vlan_type = module.params.get('port_encap_vlan_type')
port_encap_vlan = module.params['port_encap_vlan'] port_encap_vlan = module.params.get('port_encap_vlan')
vlan_encap_mode = module.params['vlan_encap_mode'] vlan_encap_mode = module.params.get('vlan_encap_mode')
allow_micro_segmentation = module.params['allow_micro_segmentation'] allow_micro_segmentation = module.params.get('allow_micro_segmentation')
switch_type = module.params['switch_type'] switch_type = module.params.get('switch_type')
switching_mode = module.params['switching_mode'] switching_mode = module.params.get('switching_mode')
enhanced_lagpolicy_name = module.params['enhanced_lagpolicy_name'] enhanced_lagpolicy_name = module.params.get('enhanced_lagpolicy_name')
enhanced_lagpolicy_dn = module.params['enhanced_lagpolicy_dn'] enhanced_lagpolicy_dn = module.params.get('enhanced_lagpolicy_dn')
mso = MSOModule(module) mso = MSOModule(module)
@ -261,13 +261,13 @@ def main():
mso.fail_json(msg="Provided schema '{0}' does not exist".format(schema)) mso.fail_json(msg="Provided schema '{0}' does not exist".format(schema))
schema_path = 'schemas/{id}'.format(**schema_obj) schema_path = 'schemas/{id}'.format(**schema_obj)
schema_id = schema_obj['id'] schema_id = schema_obj.get('id')
# Get site # Get site
site_id = mso.lookup_site(site) site_id = mso.lookup_site(site)
# Get site_idx # Get site_idx
sites = [(s['siteId'], s['templateName']) for s in schema_obj['sites']] sites = [(s.get('siteId'), s.get('templateName')) for s in schema_obj.get('sites')]
if (site_id, template) not in sites: if (site_id, template) not in sites:
mso.fail_json(msg="Provided site/template '{0}-{1}' does not exist. Existing sites/templates: {2}".format(site, template, ', '.join(sites))) mso.fail_json(msg="Provided site/template '{0}-{1}' does not exist. Existing sites/templates: {2}".format(site, template, ', '.join(sites)))
@ -278,7 +278,7 @@ def main():
# Get ANP # Get ANP
anp_ref = mso.anp_ref(schema_id=schema_id, template=template, anp=anp) anp_ref = mso.anp_ref(schema_id=schema_id, template=template, anp=anp)
anps = [a['anpRef'] for a in schema_obj['sites'][site_idx]['anps']] anps = [a.get('anpRef') for a in schema_obj.get('sites')[site_idx]['anps']]
if anp_ref not in anps: if anp_ref not in anps:
mso.fail_json(msg="Provided anp '{0}' does not exist. Existing anps: {1}".format(anp, ', '.join(anps))) mso.fail_json(msg="Provided anp '{0}' does not exist. Existing anps: {1}".format(anp, ', '.join(anps)))
anp_idx = anps.index(anp_ref) anp_idx = anps.index(anp_ref)
@ -286,9 +286,9 @@ def main():
# Get EPG # Get EPG
epg_ref = mso.epg_ref(schema_id=schema_id, template=template, anp=anp, epg=epg) epg_ref = mso.epg_ref(schema_id=schema_id, template=template, anp=anp, epg=epg)
print(epg_ref) print(epg_ref)
epgs = [e['epgRef'] for e in schema_obj['sites'][site_idx]['anps'][anp_idx]['epgs']] epgs = [e.get('epgRef') for e in schema_obj.get('sites')[site_idx]['anps'][anp_idx]['epgs']]
if epg_ref not in epgs: if epg_ref not in epgs:
mso.fail_json(msg="Provided epg '{0}' does not exist. Existing epgs: {1} epgref {2}".format(epg, str(schema_obj['sites'][site_idx]), epg_ref)) mso.fail_json(msg="Provided epg '{0}' does not exist. Existing epgs: {1} epgref {2}".format(epg, str(schema_obj.get('sites')[site_idx]), epg_ref))
epg_idx = epgs.index(epg_ref) epg_idx = epgs.index(epg_ref)
if domain_association_type == 'vmmDomain': if domain_association_type == 'vmmDomain':
@ -305,15 +305,15 @@ def main():
domain_dn = '' domain_dn = ''
# Get Domains # Get Domains
domains = [dom['dn'] for dom in schema_obj['sites'][site_idx]['anps'][anp_idx]['epgs'][epg_idx]['domainAssociations']] domains = [dom.get('dn') for dom in schema_obj.get('sites')[site_idx]['anps'][anp_idx]['epgs'][epg_idx]['domainAssociations']]
if domain_dn in domains: if domain_dn in domains:
domain_idx = domains.index(domain_dn) domain_idx = domains.index(domain_dn)
domain_path = '/sites/{0}/anps/{1}/epgs/{2}/domainAssociations/{3}'.format(site_template, anp, epg, domain_idx) domain_path = '/sites/{0}/anps/{1}/epgs/{2}/domainAssociations/{3}'.format(site_template, anp, epg, domain_idx)
mso.existing = schema_obj['sites'][site_idx]['anps'][anp_idx]['epgs'][epg_idx]['domainAssociations'][domain_idx] mso.existing = schema_obj.get('sites')[site_idx]['anps'][anp_idx]['epgs'][epg_idx]['domainAssociations'][domain_idx]
if state == 'query': if state == 'query':
if domain_association_type is None or domain_profile is None: if domain_association_type is None or domain_profile is None:
mso.existing = schema_obj['sites'][site_idx]['anps'][anp_idx]['epgs'][epg_idx]['domainAssociations'] mso.existing = schema_obj.get('sites')[site_idx]['anps'][anp_idx]['epgs'][epg_idx]['domainAssociations']
elif not mso.existing: elif not mso.existing:
mso.fail_json(msg="Domain association '{domain_association_type}/{domain_profile}' not found".format( mso.fail_json(msg="Domain association '{domain_association_type}/{domain_profile}' not found".format(
domain_association_type=domain_association_type, domain_association_type=domain_association_type,

View file

@ -163,15 +163,15 @@ def main():
], ],
) )
schema = module.params['schema'] schema = module.params.get('schema')
site = module.params['site'] site = module.params.get('site')
template = module.params['template'] template = module.params.get('template')
anp = module.params['anp'] anp = module.params.get('anp')
epg = module.params['epg'] epg = module.params.get('epg')
pod = module.params['pod'] pod = module.params.get('pod')
leaf = module.params['leaf'] leaf = module.params.get('leaf')
vlan = module.params['vlan'] vlan = module.params.get('vlan')
state = module.params['state'] state = module.params.get('state')
leafpath = 'topology/{0}/node-{1}'.format(pod, leaf) leafpath = 'topology/{0}/node-{1}'.format(pod, leaf)
@ -183,13 +183,13 @@ def main():
mso.fail_json(msg="Provided schema '{0}' does not exist".format(schema)) mso.fail_json(msg="Provided schema '{0}' does not exist".format(schema))
schema_path = 'schemas/{id}'.format(**schema_obj) schema_path = 'schemas/{id}'.format(**schema_obj)
schema_id = schema_obj['id'] schema_id = schema_obj.get('id')
# Get site # Get site
site_id = mso.lookup_site(site) site_id = mso.lookup_site(site)
# Get site_idx # Get site_idx
sites = [(s['siteId'], s['templateName']) for s in schema_obj['sites']] sites = [(s.get('siteId'), s.get('templateName')) for s in schema_obj.get('sites')]
if (site_id, template) not in sites: if (site_id, template) not in sites:
mso.fail_json(msg="Provided site/template '{0}-{1}' does not exist. Existing sites/templates: {2}".format(site, template, ', '.join(sites))) mso.fail_json(msg="Provided site/template '{0}-{1}' does not exist. Existing sites/templates: {2}".format(site, template, ', '.join(sites)))
@ -200,29 +200,29 @@ def main():
# Get ANP # Get ANP
anp_ref = mso.anp_ref(schema_id=schema_id, template=template, anp=anp) anp_ref = mso.anp_ref(schema_id=schema_id, template=template, anp=anp)
anps = [a['anpRef'] for a in schema_obj['sites'][site_idx]['anps']] anps = [a.get('anpRef') for a in schema_obj.get('sites')[site_idx]['anps']]
if anp_ref not in anps: if anp_ref not in anps:
mso.fail_json(msg="Provided anp '{0}' does not exist. Existing anps: {1}".format(anp, ', '.join(anps))) mso.fail_json(msg="Provided anp '{0}' does not exist. Existing anps: {1}".format(anp, ', '.join(anps)))
anp_idx = anps.index(anp_ref) anp_idx = anps.index(anp_ref)
# Get EPG # Get EPG
epg_ref = mso.epg_ref(schema_id=schema_id, template=template, anp=anp, epg=epg) epg_ref = mso.epg_ref(schema_id=schema_id, template=template, anp=anp, epg=epg)
epgs = [e['epgRef'] for e in schema_obj['sites'][site_idx]['anps'][anp_idx]['epgs']] epgs = [e.get('epgRef') for e in schema_obj.get('sites')[site_idx]['anps'][anp_idx]['epgs']]
if epg_ref not in epgs: if epg_ref not in epgs:
mso.fail_json(msg="Provided epg '{0}' does not exist. Existing epgs: {1}".format(epg, ', '.join(epgs))) mso.fail_json(msg="Provided epg '{0}' does not exist. Existing epgs: {1}".format(epg, ', '.join(epgs)))
epg_idx = epgs.index(epg_ref) epg_idx = epgs.index(epg_ref)
# Get Leaf # Get Leaf
leafs = [(l['path'], l['portEncapVlan']) for l in schema_obj['sites'][site_idx]['anps'][anp_idx]['epgs'][epg_idx]['staticLeafs']] leafs = [(l.get('path'), l.get('portEncapVlan')) for l in schema_obj.get('sites')[site_idx]['anps'][anp_idx]['epgs'][epg_idx]['staticLeafs']]
if (leafpath, vlan) in leafs: if (leafpath, vlan) in leafs:
leaf_idx = leafs.index((leafpath, vlan)) leaf_idx = leafs.index((leafpath, vlan))
# FIXME: Changes based on index are DANGEROUS # FIXME: Changes based on index are DANGEROUS
leaf_path = '/sites/{0}/anps/{1}/epgs/{2}/staticLeafs/{3}'.format(site_template, anp, epg, leaf_idx) leaf_path = '/sites/{0}/anps/{1}/epgs/{2}/staticLeafs/{3}'.format(site_template, anp, epg, leaf_idx)
mso.existing = schema_obj['sites'][site_idx]['anps'][anp_idx]['epgs'][epg_idx]['staticLeafs'][leaf_idx] mso.existing = schema_obj.get('sites')[site_idx]['anps'][anp_idx]['epgs'][epg_idx]['staticLeafs'][leaf_idx]
if state == 'query': if state == 'query':
if leaf is None or vlan is None: if leaf is None or vlan is None:
mso.existing = schema_obj['sites'][site_idx]['anps'][anp_idx]['epgs'][epg_idx]['staticLeafs'] mso.existing = schema_obj.get('sites')[site_idx]['anps'][anp_idx]['epgs'][epg_idx]['staticLeafs']
elif not mso.existing: elif not mso.existing:
mso.fail_json(msg="Static leaf '{leaf}/{vlan}' not found".format(leaf=leaf, vlan=vlan)) mso.fail_json(msg="Static leaf '{leaf}/{vlan}' not found".format(leaf=leaf, vlan=vlan))
mso.exit_json() mso.exit_json()

View file

@ -201,19 +201,19 @@ def main():
], ],
) )
schema = module.params['schema'] schema = module.params.get('schema')
site = module.params['site'] site = module.params.get('site')
template = module.params['template'] template = module.params.get('template')
anp = module.params['anp'] anp = module.params.get('anp')
epg = module.params['epg'] epg = module.params.get('epg')
path_type = module.params['type'] path_type = module.params.get('type')
pod = module.params['pod'] pod = module.params.get('pod')
leaf = module.params['leaf'] leaf = module.params.get('leaf')
path = module.params['path'] path = module.params.get('path')
vlan = module.params['vlan'] vlan = module.params.get('vlan')
deployment_immediacy = module.params['deployment_immediacy'] deployment_immediacy = module.params.get('deployment_immediacy')
mode = module.params['mode'] mode = module.params.get('mode')
state = module.params['state'] state = module.params.get('state')
if path_type == 'port': if path_type == 'port':
portpath = 'topology/{0}/paths-{1}/pathep-[{2}]'.format(pod, leaf, path) portpath = 'topology/{0}/paths-{1}/pathep-[{2}]'.format(pod, leaf, path)
@ -228,13 +228,13 @@ def main():
mso.fail_json(msg="Provided schema '{0}' does not exist".format(schema)) mso.fail_json(msg="Provided schema '{0}' does not exist".format(schema))
schema_path = 'schemas/{id}'.format(**schema_obj) schema_path = 'schemas/{id}'.format(**schema_obj)
schema_id = schema_obj['id'] schema_id = schema_obj.get('id')
# Get site # Get site
site_id = mso.lookup_site(site) site_id = mso.lookup_site(site)
# Get site_idx # Get site_idx
sites = [(s['siteId'], s['templateName']) for s in schema_obj['sites']] sites = [(s.get('siteId'), s.get('templateName')) for s in schema_obj.get('sites')]
if (site_id, template) not in sites: if (site_id, template) not in sites:
mso.fail_json(msg="Provided site/template '{0}-{1}' does not exist. Existing sites/templates: {2}".format(site, template, ', '.join(sites))) mso.fail_json(msg="Provided site/template '{0}-{1}' does not exist. Existing sites/templates: {2}".format(site, template, ', '.join(sites)))
@ -245,29 +245,29 @@ def main():
# Get ANP # Get ANP
anp_ref = mso.anp_ref(schema_id=schema_id, template=template, anp=anp) anp_ref = mso.anp_ref(schema_id=schema_id, template=template, anp=anp)
anps = [a['anpRef'] for a in schema_obj['sites'][site_idx]['anps']] anps = [a.get('anpRef') for a in schema_obj.get('sites')[site_idx]['anps']]
if anp_ref not in anps: if anp_ref not in anps:
mso.fail_json(msg="Provided anp '{0}' does not exist. Existing anps: {1}".format(anp, ', '.join(anps))) mso.fail_json(msg="Provided anp '{0}' does not exist. Existing anps: {1}".format(anp, ', '.join(anps)))
anp_idx = anps.index(anp_ref) anp_idx = anps.index(anp_ref)
# Get EPG # Get EPG
epg_ref = mso.epg_ref(schema_id=schema_id, template=template, anp=anp, epg=epg) epg_ref = mso.epg_ref(schema_id=schema_id, template=template, anp=anp, epg=epg)
epgs = [e['epgRef'] for e in schema_obj['sites'][site_idx]['anps'][anp_idx]['epgs']] epgs = [e.get('epgRef') for e in schema_obj.get('sites')[site_idx]['anps'][anp_idx]['epgs']]
if epg_ref not in epgs: if epg_ref not in epgs:
mso.fail_json(msg="Provided epg '{0}' does not exist. Existing epgs: {1}".format(epg, ', '.join(epgs))) mso.fail_json(msg="Provided epg '{0}' does not exist. Existing epgs: {1}".format(epg, ', '.join(epgs)))
epg_idx = epgs.index(epg_ref) epg_idx = epgs.index(epg_ref)
# Get Leaf # Get Leaf
portpaths = [p['path'] for p in schema_obj['sites'][site_idx]['anps'][anp_idx]['epgs'][epg_idx]['staticPorts']] portpaths = [p.get('path') for p in schema_obj.get('sites')[site_idx]['anps'][anp_idx]['epgs'][epg_idx]['staticPorts']]
if portpath in portpaths: if portpath in portpaths:
portpath_idx = portpaths.index(portpath) portpath_idx = portpaths.index(portpath)
# FIXME: Changes based on index are DANGEROUS # FIXME: Changes based on index are DANGEROUS
port_path = '/sites/{0}/anps/{1}/epgs/{2}/staticPorts/{3}'.format(site_template, anp, epg, portpath_idx) port_path = '/sites/{0}/anps/{1}/epgs/{2}/staticPorts/{3}'.format(site_template, anp, epg, portpath_idx)
mso.existing = schema_obj['sites'][site_idx]['anps'][anp_idx]['epgs'][epg_idx]['staticPorts'][portpath_idx] mso.existing = schema_obj.get('sites')[site_idx]['anps'][anp_idx]['epgs'][epg_idx]['staticPorts'][portpath_idx]
if state == 'query': if state == 'query':
if leaf is None or vlan is None: if leaf is None or vlan is None:
mso.existing = schema_obj['sites'][site_idx]['anps'][anp_idx]['epgs'][epg_idx]['staticPorts'] mso.existing = schema_obj.get('sites')[site_idx]['anps'][anp_idx]['epgs'][epg_idx]['staticPorts']
elif not mso.existing: elif not mso.existing:
mso.fail_json(msg="Static port '{portpath}' not found".format(portpath=portpath)) mso.fail_json(msg="Static port '{portpath}' not found".format(portpath=portpath))
mso.exit_json() mso.exit_json()

View file

@ -170,17 +170,17 @@ def main():
], ],
) )
schema = module.params['schema'] schema = module.params.get('schema')
site = module.params['site'] site = module.params.get('site')
template = module.params['template'] template = module.params.get('template')
anp = module.params['anp'] anp = module.params.get('anp')
epg = module.params['epg'] epg = module.params.get('epg')
subnet = module.params['subnet'] subnet = module.params.get('subnet')
description = module.params['description'] description = module.params.get('description')
scope = module.params['scope'] scope = module.params.get('scope')
shared = module.params['shared'] shared = module.params.get('shared')
no_default_gateway = module.params['no_default_gateway'] no_default_gateway = module.params.get('no_default_gateway')
state = module.params['state'] state = module.params.get('state')
mso = MSOModule(module) mso = MSOModule(module)
@ -190,13 +190,13 @@ def main():
mso.fail_json(msg="Provided schema '{0}' does not exist".format(schema)) mso.fail_json(msg="Provided schema '{0}' does not exist".format(schema))
schema_path = 'schemas/{id}'.format(**schema_obj) schema_path = 'schemas/{id}'.format(**schema_obj)
schema_id = schema_obj['id'] schema_id = schema_obj.get('id')
# Get site # Get site
site_id = mso.lookup_site(site) site_id = mso.lookup_site(site)
# Get site_idx # Get site_idx
sites = [(s['siteId'], s['templateName']) for s in schema_obj['sites']] sites = [(s.get('siteId'), s.get('templateName')) for s in schema_obj.get('sites')]
if (site_id, template) not in sites: if (site_id, template) not in sites:
mso.fail_json(msg="Provided site/template '{0}-{1}' does not exist. Existing sites/templates: {2}".format(site, template, ', '.join(sites))) mso.fail_json(msg="Provided site/template '{0}-{1}' does not exist. Existing sites/templates: {2}".format(site, template, ', '.join(sites)))
@ -207,29 +207,29 @@ def main():
# Get ANP # Get ANP
anp_ref = mso.anp_ref(schema_id=schema_id, template=template, anp=anp) anp_ref = mso.anp_ref(schema_id=schema_id, template=template, anp=anp)
anps = [a['anpRef'] for a in schema_obj['sites'][site_idx]['anps']] anps = [a.get('anpRef') for a in schema_obj.get('sites')[site_idx]['anps']]
if anp_ref not in anps: if anp_ref not in anps:
mso.fail_json(msg="Provided anp '{0}' does not exist. Existing anps: {1}".format(anp, ', '.join(anps))) mso.fail_json(msg="Provided anp '{0}' does not exist. Existing anps: {1}".format(anp, ', '.join(anps)))
anp_idx = anps.index(anp_ref) anp_idx = anps.index(anp_ref)
# Get EPG # Get EPG
epg_ref = mso.epg_ref(schema_id=schema_id, template=template, anp=anp, epg=epg) epg_ref = mso.epg_ref(schema_id=schema_id, template=template, anp=anp, epg=epg)
epgs = [e['epgRef'] for e in schema_obj['sites'][site_idx]['anps'][anp_idx]['epgs']] epgs = [e.get('epgRef') for e in schema_obj.get('sites')[site_idx]['anps'][anp_idx]['epgs']]
if epg_ref not in epgs: if epg_ref not in epgs:
mso.fail_json(msg="Provided epg '{0}' does not exist. Existing epgs: {1}".format(epg, ', '.join(epgs))) mso.fail_json(msg="Provided epg '{0}' does not exist. Existing epgs: {1}".format(epg, ', '.join(epgs)))
epg_idx = epgs.index(epg_ref) epg_idx = epgs.index(epg_ref)
# Get Subnet # Get Subnet
subnets = [s['ip'] for s in schema_obj['sites'][site_idx]['anps'][anp_idx]['epgs'][epg_idx]['subnets']] subnets = [s.get('ip') for s in schema_obj.get('sites')[site_idx]['anps'][anp_idx]['epgs'][epg_idx]['subnets']]
if subnet in subnets: if subnet in subnets:
subnet_idx = subnets.index(subnet) subnet_idx = subnets.index(subnet)
# FIXME: Changes based on index are DANGEROUS # FIXME: Changes based on index are DANGEROUS
subnet_path = '/sites/{0}/anps/{1}/epgs/{2}/subnets/{3}'.format(site_template, anp, epg, subnet_idx) subnet_path = '/sites/{0}/anps/{1}/epgs/{2}/subnets/{3}'.format(site_template, anp, epg, subnet_idx)
mso.existing = schema_obj['sites'][site_idx]['anps'][anp_idx]['epgs'][epg_idx]['subnets'][subnet_idx] mso.existing = schema_obj.get('sites')[site_idx]['anps'][anp_idx]['epgs'][epg_idx]['subnets'][subnet_idx]
if state == 'query': if state == 'query':
if subnet is None: if subnet is None:
mso.existing = schema_obj['sites'][site_idx]['anps'][anp_idx]['epgs'][epg_idx]['subnets'] mso.existing = schema_obj.get('sites')[site_idx]['anps'][anp_idx]['epgs'][epg_idx]['subnets']
elif not mso.existing: elif not mso.existing:
mso.fail_json(msg="Subnet '{subnet}' not found".format(subnet=subnet)) mso.fail_json(msg="Subnet '{subnet}' not found".format(subnet=subnet))
mso.exit_json() mso.exit_json()

View file

@ -138,12 +138,12 @@ def main():
], ],
) )
schema = module.params['schema'] schema = module.params.get('schema')
site = module.params['site'] site = module.params.get('site')
template = module.params['template'] template = module.params.get('template')
bd = module.params['bd'] bd = module.params.get('bd')
host_route = module.params['host_route'] host_route = module.params.get('host_route')
state = module.params['state'] state = module.params.get('state')
mso = MSOModule(module) mso = MSOModule(module)
@ -153,13 +153,13 @@ def main():
mso.fail_json(msg="Provided schema '{0}' does not exist".format(schema)) mso.fail_json(msg="Provided schema '{0}' does not exist".format(schema))
schema_path = 'schemas/{id}'.format(**schema_obj) schema_path = 'schemas/{id}'.format(**schema_obj)
schema_id = schema_obj['id'] schema_id = schema_obj.get('id')
# Get site # Get site
site_id = mso.lookup_site(site) site_id = mso.lookup_site(site)
# Get site_idx # Get site_idx
sites = [(s['siteId'], s['templateName']) for s in schema_obj['sites']] sites = [(s.get('siteId'), s.get('templateName')) for s in schema_obj.get('sites')]
if (site_id, template) not in sites: if (site_id, template) not in sites:
mso.fail_json(msg="Provided site/template '{0}-{1}' does not exist. Existing sites/templates: {2}".format(site, template, ', '.join(sites))) mso.fail_json(msg="Provided site/template '{0}-{1}' does not exist. Existing sites/templates: {2}".format(site, template, ', '.join(sites)))
@ -170,15 +170,15 @@ def main():
# Get BD # Get BD
bd_ref = mso.bd_ref(schema_id=schema_id, template=template, bd=bd) bd_ref = mso.bd_ref(schema_id=schema_id, template=template, bd=bd)
bds = [v['bdRef'] for v in schema_obj['sites'][site_idx]['bds']] bds = [v.get('bdRef') for v in schema_obj.get('sites')[site_idx]['bds']]
if bd is not None and bd_ref in bds: if bd is not None and bd_ref in bds:
bd_idx = bds.index(bd_ref) bd_idx = bds.index(bd_ref)
bd_path = '/sites/{0}/bds/{1}'.format(site_template, bd) bd_path = '/sites/{0}/bds/{1}'.format(site_template, bd)
mso.existing = schema_obj['sites'][site_idx]['bds'][bd_idx] mso.existing = schema_obj.get('sites')[site_idx]['bds'][bd_idx]
if state == 'query': if state == 'query':
if bd is None: if bd is None:
mso.existing = schema_obj['sites'][site_idx]['bds'] mso.existing = schema_obj.get('sites')[site_idx]['bds']
elif not mso.existing: elif not mso.existing:
mso.fail_json(msg="BD '{bd}' not found".format(bd=bd)) mso.fail_json(msg="BD '{bd}' not found".format(bd=bd))
mso.exit_json() mso.exit_json()

View file

@ -144,12 +144,12 @@ def main():
], ],
) )
schema = module.params['schema'] schema = module.params.get('schema')
site = module.params['site'] site = module.params.get('site')
template = module.params['template'] template = module.params.get('template')
bd = module.params['bd'] bd = module.params.get('bd')
l3out = module.params['l3out'] l3out = module.params.get('l3out')
state = module.params['state'] state = module.params.get('state')
mso = MSOModule(module) mso = MSOModule(module)
@ -159,13 +159,13 @@ def main():
mso.fail_json(msg="Provided schema '{0}' does not exist".format(schema)) mso.fail_json(msg="Provided schema '{0}' does not exist".format(schema))
schema_path = 'schemas/{id}'.format(**schema_obj) schema_path = 'schemas/{id}'.format(**schema_obj)
schema_id = schema_obj['id'] schema_id = schema_obj.get('id')
# Get site # Get site
site_id = mso.lookup_site(site) site_id = mso.lookup_site(site)
# Get site_idx # Get site_idx
sites = [(s['siteId'], s['templateName']) for s in schema_obj['sites']] sites = [(s.get('siteId'), s.get('templateName')) for s in schema_obj.get('sites')]
if (site_id, template) not in sites: if (site_id, template) not in sites:
mso.fail_json(msg="Provided site/template '{0}-{1}' does not exist. Existing sites/templates: {2}".format(site, template, ', '.join(sites))) mso.fail_json(msg="Provided site/template '{0}-{1}' does not exist. Existing sites/templates: {2}".format(site, template, ', '.join(sites)))
@ -176,22 +176,22 @@ def main():
# Get BD # Get BD
bd_ref = mso.bd_ref(schema_id=schema_id, template=template, bd=bd) bd_ref = mso.bd_ref(schema_id=schema_id, template=template, bd=bd)
bds = [v['bdRef'] for v in schema_obj['sites'][site_idx]['bds']] bds = [v.get('bdRef') for v in schema_obj.get('sites')[site_idx]['bds']]
if bd_ref not in bds: if bd_ref not in bds:
mso.fail_json(msg="Provided BD '{0}' does not exist. Existing BDs: {1}".format(bd, ', '.join(bds))) mso.fail_json(msg="Provided BD '{0}' does not exist. Existing BDs: {1}".format(bd, ', '.join(bds)))
bd_idx = bds.index(bd_ref) bd_idx = bds.index(bd_ref)
# Get L3out # Get L3out
l3outs = schema_obj['sites'][site_idx]['bds'][bd_idx]['l3Outs'] l3outs = schema_obj.get('sites')[site_idx]['bds'][bd_idx]['l3Outs']
if l3out is not None and l3out in l3outs: if l3out is not None and l3out in l3outs:
l3out_idx = l3outs.index(l3out) l3out_idx = l3outs.index(l3out)
# FIXME: Changes based on index are DANGEROUS # FIXME: Changes based on index are DANGEROUS
l3out_path = '/sites/{0}/bds/{1}/l3Outs/{2}'.format(site_template, bd, l3out_idx) l3out_path = '/sites/{0}/bds/{1}/l3Outs/{2}'.format(site_template, bd, l3out_idx)
mso.existing = schema_obj['sites'][site_idx]['bds'][bd_idx]['l3Outs'][l3out_idx] mso.existing = schema_obj.get('sites')[site_idx]['bds'][bd_idx]['l3Outs'][l3out_idx]
if state == 'query': if state == 'query':
if l3out is None: if l3out is None:
mso.existing = schema_obj['sites'][site_idx]['bds'][bd_idx]['l3Outs'] mso.existing = schema_obj.get('sites')[site_idx]['bds'][bd_idx]['l3Outs']
elif not mso.existing: elif not mso.existing:
mso.fail_json(msg="L3out '{l3out}' not found".format(l3out=l3out)) mso.fail_json(msg="L3out '{l3out}' not found".format(l3out=l3out))
mso.exit_json() mso.exit_json()

View file

@ -163,16 +163,16 @@ def main():
], ],
) )
schema = module.params['schema'] schema = module.params.get('schema')
site = module.params['site'] site = module.params.get('site')
template = module.params['template'] template = module.params.get('template')
bd = module.params['bd'] bd = module.params.get('bd')
subnet = module.params['subnet'] subnet = module.params.get('subnet')
description = module.params['description'] description = module.params.get('description')
scope = module.params['scope'] scope = module.params.get('scope')
shared = module.params['shared'] shared = module.params.get('shared')
no_default_gateway = module.params['no_default_gateway'] no_default_gateway = module.params.get('no_default_gateway')
state = module.params['state'] state = module.params.get('state')
mso = MSOModule(module) mso = MSOModule(module)
@ -182,13 +182,13 @@ def main():
mso.fail_json(msg="Provided schema '{0}' does not exist".format(schema)) mso.fail_json(msg="Provided schema '{0}' does not exist".format(schema))
schema_path = 'schemas/{id}'.format(**schema_obj) schema_path = 'schemas/{id}'.format(**schema_obj)
schema_id = schema_obj['id'] schema_id = schema_obj.get('id')
# Get site # Get site
site_id = mso.lookup_site(site) site_id = mso.lookup_site(site)
# Get site_idx # Get site_idx
sites = [(s['siteId'], s['templateName']) for s in schema_obj['sites']] sites = [(s.get('siteId'), s.get('templateName')) for s in schema_obj.get('sites')]
if (site_id, template) not in sites: if (site_id, template) not in sites:
mso.fail_json(msg="Provided site/template '{0}-{1}' does not exist. Existing sites/templates: {2}".format(site, template, ', '.join(sites))) mso.fail_json(msg="Provided site/template '{0}-{1}' does not exist. Existing sites/templates: {2}".format(site, template, ', '.join(sites)))
@ -199,22 +199,22 @@ def main():
# Get BD # Get BD
bd_ref = mso.bd_ref(schema_id=schema_id, template=template, bd=bd) bd_ref = mso.bd_ref(schema_id=schema_id, template=template, bd=bd)
bds = [v['bdRef'] for v in schema_obj['sites'][site_idx]['bds']] bds = [v.get('bdRef') for v in schema_obj.get('sites')[site_idx]['bds']]
if bd_ref not in bds: if bd_ref not in bds:
mso.fail_json(msg="Provided BD '{0}' does not exist. Existing BDs: {1}".format(bd, ', '.join(bds))) mso.fail_json(msg="Provided BD '{0}' does not exist. Existing BDs: {1}".format(bd, ', '.join(bds)))
bd_idx = bds.index(bd_ref) bd_idx = bds.index(bd_ref)
# Get Subnet # Get Subnet
subnets = [s['ip'] for s in schema_obj['sites'][site_idx]['bds'][bd_idx]['subnets']] subnets = [s.get('ip') for s in schema_obj.get('sites')[site_idx]['bds'][bd_idx]['subnets']]
if subnet in subnets: if subnet in subnets:
subnet_idx = subnets.index(subnet) subnet_idx = subnets.index(subnet)
# FIXME: Changes based on index are DANGEROUS # FIXME: Changes based on index are DANGEROUS
subnet_path = '/sites/{0}/bds/{1}/subnets/{2}'.format(site_template, bd, subnet_idx) subnet_path = '/sites/{0}/bds/{1}/subnets/{2}'.format(site_template, bd, subnet_idx)
mso.existing = schema_obj['sites'][site_idx]['bds'][bd_idx]['subnets'][subnet_idx] mso.existing = schema_obj.get('sites')[site_idx]['bds'][bd_idx]['subnets'][subnet_idx]
if state == 'query': if state == 'query':
if subnet is None: if subnet is None:
mso.existing = schema_obj['sites'][site_idx]['bds'][bd_idx]['subnets'] mso.existing = schema_obj.get('sites')[site_idx]['bds'][bd_idx]['subnets']
elif not mso.existing: elif not mso.existing:
mso.fail_json(msg="Subnet IP '{subnet}' not found".format(subnet=subnet)) mso.fail_json(msg="Subnet IP '{subnet}' not found".format(subnet=subnet))
mso.exit_json() mso.exit_json()

View file

@ -131,11 +131,11 @@ def main():
], ],
) )
schema = module.params['schema'] schema = module.params.get('schema')
site = module.params['site'] site = module.params.get('site')
template = module.params['template'] template = module.params.get('template')
vrf = module.params['vrf'] vrf = module.params.get('vrf')
state = module.params['state'] state = module.params.get('state')
mso = MSOModule(module) mso = MSOModule(module)
@ -145,13 +145,13 @@ def main():
mso.fail_json(msg="Provided schema '{0}' does not exist".format(schema)) mso.fail_json(msg="Provided schema '{0}' does not exist".format(schema))
schema_path = 'schemas/{id}'.format(**schema_obj) schema_path = 'schemas/{id}'.format(**schema_obj)
schema_id = schema_obj['id'] schema_id = schema_obj.get('id')
# Get site # Get site
site_id = mso.lookup_site(site) site_id = mso.lookup_site(site)
# Get site_idx # Get site_idx
sites = [(s['siteId'], s['templateName']) for s in schema_obj['sites']] sites = [(s.get('siteId'), s.get('templateName')) for s in schema_obj.get('sites')]
if (site_id, template) not in sites: if (site_id, template) not in sites:
mso.fail_json(msg="Provided site/template '{0}-{1}' does not exist. Existing sites/templates: {2}".format(site, template, ', '.join(sites))) mso.fail_json(msg="Provided site/template '{0}-{1}' does not exist. Existing sites/templates: {2}".format(site, template, ', '.join(sites)))
@ -162,15 +162,15 @@ def main():
# Get VRF # Get VRF
vrf_ref = mso.vrf_ref(schema_id=schema_id, template=template, vrf=vrf) vrf_ref = mso.vrf_ref(schema_id=schema_id, template=template, vrf=vrf)
vrfs = [v['vrfRef'] for v in schema_obj['sites'][site_idx]['vrfs']] vrfs = [v.get('vrfRef') for v in schema_obj.get('sites')[site_idx]['vrfs']]
if vrf is not None and vrf_ref in vrfs: if vrf is not None and vrf_ref in vrfs:
vrf_idx = vrfs.index(vrf_ref) vrf_idx = vrfs.index(vrf_ref)
vrf_path = '/sites/{0}/vrfs/{1}'.format(site_template, vrf) vrf_path = '/sites/{0}/vrfs/{1}'.format(site_template, vrf)
mso.existing = schema_obj['sites'][site_idx]['vrfs'][vrf_idx] mso.existing = schema_obj.get('sites')[site_idx]['vrfs'][vrf_idx]
if state == 'query': if state == 'query':
if vrf is None: if vrf is None:
mso.existing = schema_obj['sites'][site_idx]['vrfs'] mso.existing = schema_obj.get('sites')[site_idx]['vrfs']
elif not mso.existing: elif not mso.existing:
mso.fail_json(msg="VRF '{vrf}' not found".format(vrf=vrf)) mso.fail_json(msg="VRF '{vrf}' not found".format(vrf=vrf))
mso.exit_json() mso.exit_json()

View file

@ -140,12 +140,12 @@ def main():
], ],
) )
schema = module.params['schema'] schema = module.params.get('schema')
site = module.params['site'] site = module.params.get('site')
template = module.params['template'] template = module.params.get('template')
vrf = module.params['vrf'] vrf = module.params.get('vrf')
region = module.params['region'] region = module.params.get('region')
state = module.params['state'] state = module.params.get('state')
mso = MSOModule(module) mso = MSOModule(module)
@ -155,13 +155,13 @@ def main():
mso.fail_json(msg="Provided schema '{0}' does not exist".format(schema)) mso.fail_json(msg="Provided schema '{0}' does not exist".format(schema))
schema_path = 'schemas/{id}'.format(**schema_obj) schema_path = 'schemas/{id}'.format(**schema_obj)
schema_id = schema_obj['id'] schema_id = schema_obj.get('id')
# Get site # Get site
site_id = mso.lookup_site(site) site_id = mso.lookup_site(site)
# Get site_idx # Get site_idx
sites = [(s['siteId'], s['templateName']) for s in schema_obj['sites']] sites = [(s.get('siteId'), s.get('templateName')) for s in schema_obj.get('sites')]
if (site_id, template) not in sites: if (site_id, template) not in sites:
mso.fail_json(msg="Provided site/template '{0}-{1}' does not exist. Existing sites/templates: {2}".format(site, template, ', '.join(sites))) mso.fail_json(msg="Provided site/template '{0}-{1}' does not exist. Existing sites/templates: {2}".format(site, template, ', '.join(sites)))
@ -172,21 +172,21 @@ def main():
# Get VRF # Get VRF
vrf_ref = mso.vrf_ref(schema_id=schema_id, template=template, vrf=vrf) vrf_ref = mso.vrf_ref(schema_id=schema_id, template=template, vrf=vrf)
vrfs = [v['vrfRef'] for v in schema_obj['sites'][site_idx]['vrfs']] vrfs = [v.get('vrfRef') for v in schema_obj.get('sites')[site_idx]['vrfs']]
if vrf_ref not in vrfs: if vrf_ref not in vrfs:
mso.fail_json(msg="Provided vrf '{0}' does not exist. Existing vrfs: {1}".format(vrf, ', '.join(vrfs))) mso.fail_json(msg="Provided vrf '{0}' does not exist. Existing vrfs: {1}".format(vrf, ', '.join(vrfs)))
vrf_idx = vrfs.index(vrf_ref) vrf_idx = vrfs.index(vrf_ref)
# Get Region # Get Region
regions = [r['name'] for r in schema_obj['sites'][site_idx]['vrfs'][vrf_idx]['regions']] regions = [r.get('name') for r in schema_obj.get('sites')[site_idx]['vrfs'][vrf_idx]['regions']]
if region is not None and region in regions: if region is not None and region in regions:
region_idx = regions.index(region) region_idx = regions.index(region)
region_path = '/sites/{0}/vrfs/{1}/regions/{2}'.format(site_template, vrf, region) region_path = '/sites/{0}/vrfs/{1}/regions/{2}'.format(site_template, vrf, region)
mso.existing = schema_obj['sites'][site_idx]['vrfs'][vrf_idx]['regions'][region_idx] mso.existing = schema_obj.get('sites')[site_idx]['vrfs'][vrf_idx]['regions'][region_idx]
if state == 'query': if state == 'query':
if region is None: if region is None:
mso.existing = schema_obj['sites'][site_idx]['vrfs'][vrf_idx]['regions'] mso.existing = schema_obj.get('sites')[site_idx]['vrfs'][vrf_idx]['regions']
elif not mso.existing: elif not mso.existing:
mso.fail_json(msg="Region '{region}' not found".format(region=region)) mso.fail_json(msg="Region '{region}' not found".format(region=region))
mso.exit_json() mso.exit_json()

View file

@ -159,14 +159,14 @@ def main():
], ],
) )
schema = module.params['schema'] schema = module.params.get('schema')
site = module.params['site'] site = module.params.get('site')
template = module.params['template'] template = module.params.get('template')
vrf = module.params['vrf'] vrf = module.params.get('vrf')
region = module.params['region'] region = module.params.get('region')
cidr = module.params['cidr'] cidr = module.params.get('cidr')
primary = module.params['primary'] primary = module.params.get('primary')
state = module.params['state'] state = module.params.get('state')
mso = MSOModule(module) mso = MSOModule(module)
@ -176,13 +176,13 @@ def main():
mso.fail_json(msg="Provided schema '{0}' does not exist".format(schema)) mso.fail_json(msg="Provided schema '{0}' does not exist".format(schema))
schema_path = 'schemas/{id}'.format(**schema_obj) schema_path = 'schemas/{id}'.format(**schema_obj)
schema_id = schema_obj['id'] schema_id = schema_obj.get('id')
# Get site # Get site
site_id = mso.lookup_site(site) site_id = mso.lookup_site(site)
# Get site_idx # Get site_idx
sites = [(s['siteId'], s['templateName']) for s in schema_obj['sites']] sites = [(s.get('siteId'), s.get('templateName')) for s in schema_obj.get('sites')]
if (site_id, template) not in sites: if (site_id, template) not in sites:
mso.fail_json(msg="Provided site/template '{0}-{1}' does not exist. Existing sites/templates: {2}".format(site, template, ', '.join(sites))) mso.fail_json(msg="Provided site/template '{0}-{1}' does not exist. Existing sites/templates: {2}".format(site, template, ', '.join(sites)))
@ -193,28 +193,28 @@ def main():
# Get VRF # Get VRF
vrf_ref = mso.vrf_ref(schema_id=schema_id, template=template, vrf=vrf) vrf_ref = mso.vrf_ref(schema_id=schema_id, template=template, vrf=vrf)
vrfs = [v['vrfRef'] for v in schema_obj['sites'][site_idx]['vrfs']] vrfs = [v.get('vrfRef') for v in schema_obj.get('sites')[site_idx]['vrfs']]
if vrf_ref not in vrfs: if vrf_ref not in vrfs:
mso.fail_json(msg="Provided vrf '{0}' does not exist. Existing vrfs: {1}".format(vrf, ', '.join(vrfs))) mso.fail_json(msg="Provided vrf '{0}' does not exist. Existing vrfs: {1}".format(vrf, ', '.join(vrfs)))
vrf_idx = vrfs.index(vrf_ref) vrf_idx = vrfs.index(vrf_ref)
# Get Region # Get Region
regions = [r['name'] for r in schema_obj['sites'][site_idx]['vrfs'][vrf_idx]['regions']] regions = [r.get('name') for r in schema_obj.get('sites')[site_idx]['vrfs'][vrf_idx]['regions']]
if region not in regions: if region not in regions:
mso.fail_json(msg="Provided region '{0}' does not exist. Existing regions: {1}".format(region, ', '.join(regions))) mso.fail_json(msg="Provided region '{0}' does not exist. Existing regions: {1}".format(region, ', '.join(regions)))
region_idx = regions.index(region) region_idx = regions.index(region)
# Get CIDR # Get CIDR
cidrs = [c['ip'] for c in schema_obj['sites'][site_idx]['vrfs'][vrf_idx]['regions'][region_idx]['cidrs']] cidrs = [c.get('ip') for c in schema_obj.get('sites')[site_idx]['vrfs'][vrf_idx]['regions'][region_idx]['cidrs']]
if cidr is not None and cidr in cidrs: if cidr is not None and cidr in cidrs:
cidr_idx = cidrs.index(cidr) cidr_idx = cidrs.index(cidr)
# FIXME: Changes based on index are DANGEROUS # FIXME: Changes based on index are DANGEROUS
cidr_path = '/sites/{0}/vrfs/{1}/regions/{2}/cidrs/{3}'.format(site_template, vrf, region, cidr_idx) cidr_path = '/sites/{0}/vrfs/{1}/regions/{2}/cidrs/{3}'.format(site_template, vrf, region, cidr_idx)
mso.existing = schema_obj['sites'][site_idx]['vrfs'][vrf_idx]['regions'][region_idx]['cidrs'][cidr_idx] mso.existing = schema_obj.get('sites')[site_idx]['vrfs'][vrf_idx]['regions'][region_idx]['cidrs'][cidr_idx]
if state == 'query': if state == 'query':
if cidr is None: if cidr is None:
mso.existing = schema_obj['sites'][site_idx]['vrfs'][vrf_idx]['regions'][region_idx]['cidrs'] mso.existing = schema_obj.get('sites')[site_idx]['vrfs'][vrf_idx]['regions'][region_idx]['cidrs']
elif not mso.existing: elif not mso.existing:
mso.fail_json(msg="CIDR IP '{cidr}' not found".format(cidr=cidr)) mso.fail_json(msg="CIDR IP '{cidr}' not found".format(cidr=cidr))
mso.exit_json() mso.exit_json()

View file

@ -169,15 +169,15 @@ def main():
], ],
) )
schema = module.params['schema'] schema = module.params.get('schema')
site = module.params['site'] site = module.params.get('site')
template = module.params['template'] template = module.params.get('template')
vrf = module.params['vrf'] vrf = module.params.get('vrf')
region = module.params['region'] region = module.params.get('region')
cidr = module.params['cidr'] cidr = module.params.get('cidr')
subnet = module.params['subnet'] subnet = module.params.get('subnet')
zone = module.params['zone'] zone = module.params.get('zone')
state = module.params['state'] state = module.params.get('state')
mso = MSOModule(module) mso = MSOModule(module)
@ -187,13 +187,13 @@ def main():
mso.fail_json(msg="Provided schema '{0}' does not exist".format(schema)) mso.fail_json(msg="Provided schema '{0}' does not exist".format(schema))
schema_path = 'schemas/{id}'.format(**schema_obj) schema_path = 'schemas/{id}'.format(**schema_obj)
schema_id = schema_obj['id'] schema_id = schema_obj.get('id')
# Get site # Get site
site_id = mso.lookup_site(site) site_id = mso.lookup_site(site)
# Get site_idx # Get site_idx
sites = [(s['siteId'], s['templateName']) for s in schema_obj['sites']] sites = [(s.get('siteId'), s.get('templateName')) for s in schema_obj.get('sites')]
if (site_id, template) not in sites: if (site_id, template) not in sites:
mso.fail_json(msg="Provided site/template '{0}-{1}' does not exist. Existing sites/templates: {2}".format(site, template, ', '.join(sites))) mso.fail_json(msg="Provided site/template '{0}-{1}' does not exist. Existing sites/templates: {2}".format(site, template, ', '.join(sites)))
@ -204,34 +204,34 @@ def main():
# Get VRF # Get VRF
vrf_ref = mso.vrf_ref(schema_id=schema_id, template=template, vrf=vrf) vrf_ref = mso.vrf_ref(schema_id=schema_id, template=template, vrf=vrf)
vrfs = [v['vrfRef'] for v in schema_obj['sites'][site_idx]['vrfs']] vrfs = [v.get('vrfRef') for v in schema_obj.get('sites')[site_idx]['vrfs']]
if vrf_ref not in vrfs: if vrf_ref not in vrfs:
mso.fail_json(msg="Provided vrf '{0}' does not exist. Existing vrfs: {1}".format(vrf, ', '.join(vrfs))) mso.fail_json(msg="Provided vrf '{0}' does not exist. Existing vrfs: {1}".format(vrf, ', '.join(vrfs)))
vrf_idx = vrfs.index(vrf_ref) vrf_idx = vrfs.index(vrf_ref)
# Get Region # Get Region
regions = [r['name'] for r in schema_obj['sites'][site_idx]['vrfs'][vrf_idx]['regions']] regions = [r.get('name') for r in schema_obj.get('sites')[site_idx]['vrfs'][vrf_idx]['regions']]
if region not in regions: if region not in regions:
mso.fail_json(msg="Provided region '{0}' does not exist. Existing regions: {1}".format(region, ', '.join(regions))) mso.fail_json(msg="Provided region '{0}' does not exist. Existing regions: {1}".format(region, ', '.join(regions)))
region_idx = regions.index(region) region_idx = regions.index(region)
# Get CIDR # Get CIDR
cidrs = [c['ip'] for c in schema_obj['sites'][site_idx]['vrfs'][vrf_idx]['regions'][region_idx]['cidrs']] cidrs = [c.get('ip') for c in schema_obj.get('sites')[site_idx]['vrfs'][vrf_idx]['regions'][region_idx]['cidrs']]
if cidr not in cidrs: if cidr not in cidrs:
mso.fail_json(msg="Provided CIDR IP '{0}' does not exist. Existing CIDR IPs: {1}".format(cidr, ', '.join(cidrs))) mso.fail_json(msg="Provided CIDR IP '{0}' does not exist. Existing CIDR IPs: {1}".format(cidr, ', '.join(cidrs)))
cidr_idx = cidrs.index(cidr) cidr_idx = cidrs.index(cidr)
# Get Subnet # Get Subnet
subnets = [s['ip'] for s in schema_obj['sites'][site_idx]['vrfs'][vrf_idx]['regions'][region_idx]['cidrs'][cidr_idx]['subnets']] subnets = [s.get('ip') for s in schema_obj.get('sites')[site_idx]['vrfs'][vrf_idx]['regions'][region_idx]['cidrs'][cidr_idx]['subnets']]
if subnet is not None and subnet in subnets: if subnet is not None and subnet in subnets:
subnet_idx = subnets.index(subnet) subnet_idx = subnets.index(subnet)
# FIXME: Changes based on index are DANGEROUS # FIXME: Changes based on index are DANGEROUS
subnet_path = '/sites/{0}/vrfs/{1}/regions/{2}/cidrs/{3}/subnets/{4}'.format(site_template, vrf, region, cidr_idx, subnet_idx) subnet_path = '/sites/{0}/vrfs/{1}/regions/{2}/cidrs/{3}/subnets/{4}'.format(site_template, vrf, region, cidr_idx, subnet_idx)
mso.existing = schema_obj['sites'][site_idx]['vrfs'][vrf_idx]['regions'][region_idx]['cidrs'][cidr_idx]['subnets'][subnet_idx] mso.existing = schema_obj.get('sites')[site_idx]['vrfs'][vrf_idx]['regions'][region_idx]['cidrs'][cidr_idx]['subnets'][subnet_idx]
if state == 'query': if state == 'query':
if subnet is None: if subnet is None:
mso.existing = schema_obj['sites'][site_idx]['vrfs'][vrf_idx]['regions'][region_idx]['cidrs'][cidr_idx]['subnets'] mso.existing = schema_obj.get('sites')[site_idx]['vrfs'][vrf_idx]['regions'][region_idx]['cidrs'][cidr_idx]['subnets']
elif not mso.existing: elif not mso.existing:
mso.fail_json(msg="Subnet IP '{subnet}' not found".format(subnet=subnet)) mso.fail_json(msg="Subnet IP '{subnet}' not found".format(subnet=subnet))
mso.exit_json() mso.exit_json()

View file

@ -128,11 +128,11 @@ def main():
], ],
) )
tenant = module.params['tenant'] tenant = module.params.get('tenant')
schema = module.params['schema'] schema = module.params.get('schema')
template = module.params['template'] template = module.params.get('template')
display_name = module.params['display_name'] display_name = module.params.get('display_name')
state = module.params['state'] state = module.params.get('state')
mso = MSOModule(module) mso = MSOModule(module)
@ -145,13 +145,13 @@ def main():
schema_path = 'schemas/{id}'.format(**schema_obj) schema_path = 'schemas/{id}'.format(**schema_obj)
# Get template # Get template
templates = [t['name'] for t in schema_obj['templates']] templates = [t.get('name') for t in schema_obj.get('templates')]
if template: if template:
if template in templates: if template in templates:
template_idx = templates.index(template) template_idx = templates.index(template)
mso.existing = schema_obj['templates'][template_idx] mso.existing = schema_obj.get('templates')[template_idx]
else: else:
mso.existing = schema_obj['templates'] mso.existing = schema_obj.get('templates')
else: else:
schema_path = 'schemas' schema_path = 'schemas'
@ -204,7 +204,7 @@ def main():
sites=[], sites=[],
) )
mso.existing = payload['templates'][0] mso.existing = payload.get('templates')[0]
if not module.check_mode: if not module.check_mode:
mso.request(schema_path, method='POST', data=payload) mso.request(schema_path, method='POST', data=payload)

View file

@ -125,11 +125,11 @@ def main():
], ],
) )
schema = module.params['schema'] schema = module.params.get('schema')
template = module.params['template'] template = module.params.get('template')
anp = module.params['anp'] anp = module.params.get('anp')
display_name = module.params['display_name'] display_name = module.params.get('display_name')
state = module.params['state'] state = module.params.get('state')
mso = MSOModule(module) mso = MSOModule(module)
@ -141,21 +141,21 @@ def main():
schema_path = 'schemas/{id}'.format(**schema_obj) schema_path = 'schemas/{id}'.format(**schema_obj)
# Get template # Get template
templates = [t['name'] for t in schema_obj['templates']] templates = [t.get('name') for t in schema_obj.get('templates')]
if template not in templates: if template not in templates:
mso.fail_json(msg="Provided template '{0}' does not exist. Existing templates: {1}".format(template, ', '.join(templates))) mso.fail_json(msg="Provided template '{0}' does not exist. Existing templates: {1}".format(template, ', '.join(templates)))
template_idx = templates.index(template) template_idx = templates.index(template)
# Get ANP # Get ANP
anps = [a['name'] for a in schema_obj['templates'][template_idx]['anps']] anps = [a.get('name') for a in schema_obj.get('templates')[template_idx]['anps']]
if anp is not None and anp in anps: if anp is not None and anp in anps:
anp_idx = anps.index(anp) anp_idx = anps.index(anp)
mso.existing = schema_obj['templates'][template_idx]['anps'][anp_idx] mso.existing = schema_obj.get('templates')[template_idx]['anps'][anp_idx]
if state == 'query': if state == 'query':
if anp is None: if anp is None:
mso.existing = schema_obj['templates'][template_idx]['anps'] mso.existing = schema_obj.get('templates')[template_idx]['anps']
elif not mso.existing: elif not mso.existing:
mso.fail_json(msg="ANP '{anp}' not found".format(anp=anp)) mso.fail_json(msg="ANP '{anp}' not found".format(anp=anp))
mso.exit_json() mso.exit_json()

View file

@ -271,52 +271,52 @@ def main():
], ],
) )
schema = module.params['schema'] schema = module.params.get('schema')
template = module.params['template'] template = module.params.get('template')
anp = module.params['anp'] anp = module.params.get('anp')
epg = module.params['epg'] epg = module.params.get('epg')
display_name = module.params['display_name'] display_name = module.params.get('display_name')
bd = module.params['bd'] bd = module.params.get('bd')
vrf = module.params['vrf'] vrf = module.params.get('vrf')
useg_epg = module.params['useg_epg'] useg_epg = module.params.get('useg_epg')
intra_epg_isolation = module.params['intra_epg_isolation'] intra_epg_isolation = module.params.get('intra_epg_isolation')
intersite_multicaste_source = module.params['intersite_multicaste_source'] intersite_multicaste_source = module.params.get('intersite_multicaste_source')
subnets = module.params['subnets'] subnets = module.params.get('subnets')
state = module.params['state'] state = module.params.get('state')
preferred_group = module.params['preferred_group'] preferred_group = module.params.get('preferred_group')
mso = MSOModule(module) mso = MSOModule(module)
# Get schema_id # Get schema_id
schema_obj = mso.get_obj('schemas', displayName=schema) schema_obj = mso.get_obj('schemas', displayName=schema)
if schema_obj: if schema_obj:
schema_id = schema_obj['id'] schema_id = schema_obj.get('id')
else: else:
mso.fail_json(msg="Provided schema '{0}' does not exist".format(schema)) mso.fail_json(msg="Provided schema '{0}' does not exist".format(schema))
schema_path = 'schemas/{id}'.format(**schema_obj) schema_path = 'schemas/{id}'.format(**schema_obj)
# Get template # Get template
templates = [t['name'] for t in schema_obj['templates']] templates = [t.get('name') for t in schema_obj.get('templates')]
if template not in templates: if template not in templates:
mso.fail_json(msg="Provided template '{0}' does not exist. Existing templates: {1}".format(template, ', '.join(templates))) mso.fail_json(msg="Provided template '{0}' does not exist. Existing templates: {1}".format(template, ', '.join(templates)))
template_idx = templates.index(template) template_idx = templates.index(template)
# Get ANP # Get ANP
anps = [a['name'] for a in schema_obj['templates'][template_idx]['anps']] anps = [a.get('name') for a in schema_obj.get('templates')[template_idx]['anps']]
if anp not in anps: if anp not in anps:
mso.fail_json(msg="Provided anp '{0}' does not exist. Existing anps: {1}".format(anp, ', '.join(anps))) mso.fail_json(msg="Provided anp '{0}' does not exist. Existing anps: {1}".format(anp, ', '.join(anps)))
anp_idx = anps.index(anp) anp_idx = anps.index(anp)
# Get EPG # Get EPG
epgs = [e['name'] for e in schema_obj['templates'][template_idx]['anps'][anp_idx]['epgs']] epgs = [e.get('name') for e in schema_obj.get('templates')[template_idx]['anps'][anp_idx]['epgs']]
if epg is not None and epg in epgs: if epg is not None and epg in epgs:
epg_idx = epgs.index(epg) epg_idx = epgs.index(epg)
mso.existing = schema_obj['templates'][template_idx]['anps'][anp_idx]['epgs'][epg_idx] mso.existing = schema_obj.get('templates')[template_idx]['anps'][anp_idx]['epgs'][epg_idx]
if state == 'query': if state == 'query':
if epg is None: if epg is None:
mso.existing = schema_obj['templates'][template_idx]['anps'][anp_idx]['epgs'] mso.existing = schema_obj.get('templates')[template_idx]['anps'][anp_idx]['epgs']
elif not mso.existing: elif not mso.existing:
mso.fail_json(msg="EPG '{epg}' not found".format(epg=epg)) mso.fail_json(msg="EPG '{epg}' not found".format(epg=epg))
mso.exit_json() mso.exit_json()

View file

@ -164,62 +164,62 @@ def main():
], ],
) )
schema = module.params['schema'] schema = module.params.get('schema')
template = module.params['template'] template = module.params.get('template')
anp = module.params['anp'] anp = module.params.get('anp')
epg = module.params['epg'] epg = module.params.get('epg')
contract = module.params['contract'] contract = module.params.get('contract')
state = module.params['state'] state = module.params.get('state')
mso = MSOModule(module) mso = MSOModule(module)
if contract: if contract:
if contract.get('schema') is None: if contract.get('schema') is None:
contract['schema'] = schema contract['schema'] = schema
contract['schema_id'] = mso.lookup_schema(contract['schema']) contract['schema_id'] = mso.lookup_schema(contract.get('schema'))
if contract.get('template') is None: if contract.get('template') is None:
contract['template'] = template contract['template'] = template
# Get schema_id # Get schema_id
schema_obj = mso.get_obj('schemas', displayName=schema) schema_obj = mso.get_obj('schemas', displayName=schema)
if schema_obj: if schema_obj:
schema_id = schema_obj['id'] schema_id = schema_obj.get('id')
else: else:
mso.fail_json(msg="Provided schema '{0}' does not exist".format(schema)) mso.fail_json(msg="Provided schema '{0}' does not exist".format(schema))
schema_path = 'schemas/{id}'.format(**schema_obj) schema_path = 'schemas/{id}'.format(**schema_obj)
# Get template # Get template
templates = [t['name'] for t in schema_obj['templates']] templates = [t.get('name') for t in schema_obj.get('templates')]
if template not in templates: if template not in templates:
mso.fail_json(msg="Provided template '{0}' does not exist. Existing templates: {1}".format(template, ', '.join(templates))) mso.fail_json(msg="Provided template '{0}' does not exist. Existing templates: {1}".format(template, ', '.join(templates)))
template_idx = templates.index(template) template_idx = templates.index(template)
# Get ANP # Get ANP
anps = [a['name'] for a in schema_obj['templates'][template_idx]['anps']] anps = [a.get('name') for a in schema_obj.get('templates')[template_idx]['anps']]
if anp not in anps: if anp not in anps:
mso.fail_json(msg="Provided anp '{0}' does not exist. Existing anps: {1}".format(anp, ', '.join(anps))) mso.fail_json(msg="Provided anp '{0}' does not exist. Existing anps: {1}".format(anp, ', '.join(anps)))
anp_idx = anps.index(anp) anp_idx = anps.index(anp)
# Get EPG # Get EPG
epgs = [e['name'] for e in schema_obj['templates'][template_idx]['anps'][anp_idx]['epgs']] epgs = [e.get('name') for e in schema_obj.get('templates')[template_idx]['anps'][anp_idx]['epgs']]
if epg not in epgs: if epg not in epgs:
mso.fail_json(msg="Provided epg '{epg}' does not exist. Existing epgs: {epgs}".format(epg=epg, epgs=', '.join(epgs))) mso.fail_json(msg="Provided epg '{epg}' does not exist. Existing epgs: {epgs}".format(epg=epg, epgs=', '.join(epgs)))
epg_idx = epgs.index(epg) epg_idx = epgs.index(epg)
# Get Contract # Get Contract
if contract: if contract:
contracts = [(c['contractRef'], contracts = [(c.get('contractRef'),
c['relationshipType']) for c in schema_obj['templates'][template_idx]['anps'][anp_idx]['epgs'][epg_idx]['contractRelationships']] c.get('relationshipType')) for c in schema_obj.get('templates')[template_idx]['anps'][anp_idx]['epgs'][epg_idx]['contractRelationships']]
contract_ref = mso.contract_ref(**contract) contract_ref = mso.contract_ref(**contract)
if (contract_ref, contract['type']) in contracts: if (contract_ref, contract.get('type')) in contracts:
contract_idx = contracts.index((contract_ref, contract['type'])) contract_idx = contracts.index((contract_ref, contract.get('type')))
contract_path = '/templates/{0}/anps/{1}/epgs/{2}/contractRelationships/{3}'.format(template, anp, epg, contract) contract_path = '/templates/{0}/anps/{1}/epgs/{2}/contractRelationships/{3}'.format(template, anp, epg, contract)
mso.existing = schema_obj['templates'][template_idx]['anps'][anp_idx]['epgs'][epg_idx]['contractRelationships'][contract_idx] mso.existing = schema_obj.get('templates')[template_idx]['anps'][anp_idx]['epgs'][epg_idx]['contractRelationships'][contract_idx]
if state == 'query': if state == 'query':
if not contract: if not contract:
mso.existing = schema_obj['templates'][template_idx]['anps'][anp_idx]['epgs'][epg_idx]['contractRelationships'] mso.existing = schema_obj.get('templates')[template_idx]['anps'][anp_idx]['epgs'][epg_idx]['contractRelationships']
elif not mso.existing: elif not mso.existing:
mso.fail_json(msg="Contract '{0}' not found".format(contract_ref)) mso.fail_json(msg="Contract '{0}' not found".format(contract_ref))
mso.exit_json() mso.exit_json()
@ -235,11 +235,11 @@ def main():
elif state == 'present': elif state == 'present':
payload = dict( payload = dict(
relationshipType=contract['type'], relationshipType=contract.get('type'),
contractRef=dict( contractRef=dict(
contractName=contract['name'], contractName=contract.get('name'),
templateName=contract['template'], templateName=contract.get('template'),
schemaId=contract['schema_id'], schemaId=contract.get('schema_id'),
), ),
) )

View file

@ -157,16 +157,16 @@ def main():
], ],
) )
schema = module.params['schema'] schema = module.params.get('schema')
template = module.params['template'] template = module.params.get('template')
anp = module.params['anp'] anp = module.params.get('anp')
epg = module.params['epg'] epg = module.params.get('epg')
subnet = module.params['subnet'] subnet = module.params.get('subnet')
description = module.params['description'] description = module.params.get('description')
scope = module.params['scope'] scope = module.params.get('scope')
shared = module.params['shared'] shared = module.params.get('shared')
no_default_gateway = module.params['no_default_gateway'] no_default_gateway = module.params.get('no_default_gateway')
state = module.params['state'] state = module.params.get('state')
mso = MSOModule(module) mso = MSOModule(module)
@ -178,35 +178,35 @@ def main():
schema_path = 'schemas/{id}'.format(**schema_obj) schema_path = 'schemas/{id}'.format(**schema_obj)
# Get template # Get template
templates = [t['name'] for t in schema_obj['templates']] templates = [t.get('name') for t in schema_obj.get('templates')]
if template not in templates: if template not in templates:
mso.fail_json(msg="Provided template '{template}' does not exist. Existing templates: {templates}".format(template=template, mso.fail_json(msg="Provided template '{template}' does not exist. Existing templates: {templates}".format(template=template,
templates=', '.join(templates))) templates=', '.join(templates)))
template_idx = templates.index(template) template_idx = templates.index(template)
# Get ANP # Get ANP
anps = [a['name'] for a in schema_obj['templates'][template_idx]['anps']] anps = [a.get('name') for a in schema_obj.get('templates')[template_idx]['anps']]
if anp not in anps: if anp not in anps:
mso.fail_json(msg="Provided anp '{anp}' does not exist. Existing anps: {anps}".format(anp=anp, anps=', '.join(anps))) mso.fail_json(msg="Provided anp '{anp}' does not exist. Existing anps: {anps}".format(anp=anp, anps=', '.join(anps)))
anp_idx = anps.index(anp) anp_idx = anps.index(anp)
# Get EPG # Get EPG
epgs = [e['name'] for e in schema_obj['templates'][template_idx]['anps'][anp_idx]['epgs']] epgs = [e.get('name') for e in schema_obj.get('templates')[template_idx]['anps'][anp_idx]['epgs']]
if epg not in epgs: if epg not in epgs:
mso.fail_json(msg="Provided epg '{epg}' does not exist. Existing epgs: {epgs}".format(epg=epg, epgs=', '.join(epgs))) mso.fail_json(msg="Provided epg '{epg}' does not exist. Existing epgs: {epgs}".format(epg=epg, epgs=', '.join(epgs)))
epg_idx = epgs.index(epg) epg_idx = epgs.index(epg)
# Get Subnet # Get Subnet
subnets = [s['ip'] for s in schema_obj['templates'][template_idx]['anps'][anp_idx]['epgs'][epg_idx]['subnets']] subnets = [s.get('ip') for s in schema_obj.get('templates')[template_idx]['anps'][anp_idx]['epgs'][epg_idx]['subnets']]
if subnet in subnets: if subnet in subnets:
subnet_idx = subnets.index(subnet) subnet_idx = subnets.index(subnet)
# FIXME: Changes based on index are DANGEROUS # FIXME: Changes based on index are DANGEROUS
subnet_path = '/templates/{0}/anps/{1}/epgs/{2}/subnets/{3}'.format(template, anp, epg, subnet_idx) subnet_path = '/templates/{0}/anps/{1}/epgs/{2}/subnets/{3}'.format(template, anp, epg, subnet_idx)
mso.existing = schema_obj['templates'][template_idx]['anps'][anp_idx]['epgs'][epg_idx]['subnets'][subnet_idx] mso.existing = schema_obj.get('templates')[template_idx]['anps'][anp_idx]['epgs'][epg_idx]['subnets'][subnet_idx]
if state == 'query': if state == 'query':
if subnet is None: if subnet is None:
mso.existing = schema_obj['templates'][template_idx]['anps'][anp_idx]['epgs'][epg_idx]['subnets'] mso.existing = schema_obj.get('templates')[template_idx]['anps'][anp_idx]['epgs'][epg_idx]['subnets']
elif not mso.existing: elif not mso.existing:
mso.fail_json(msg="Subnet '{subnet}' not found".format(subnet=subnet)) mso.fail_json(msg="Subnet '{subnet}' not found".format(subnet=subnet))
mso.exit_json() mso.exit_json()

View file

@ -201,46 +201,46 @@ def main():
], ],
) )
schema = module.params['schema'] schema = module.params.get('schema')
template = module.params['template'] template = module.params.get('template')
bd = module.params['bd'] bd = module.params.get('bd')
display_name = module.params['display_name'] display_name = module.params.get('display_name')
intersite_bum_traffic = module.params['intersite_bum_traffic'] intersite_bum_traffic = module.params.get('intersite_bum_traffic')
optimize_wan_bandwidth = module.params['optimize_wan_bandwidth'] optimize_wan_bandwidth = module.params.get('optimize_wan_bandwidth')
layer2_stretch = module.params['layer2_stretch'] layer2_stretch = module.params.get('layer2_stretch')
layer2_unknown_unicast = module.params['layer2_unknown_unicast'] layer2_unknown_unicast = module.params.get('layer2_unknown_unicast')
layer3_multicast = module.params['layer3_multicast'] layer3_multicast = module.params.get('layer3_multicast')
vrf = module.params['vrf'] vrf = module.params.get('vrf')
subnets = module.params['subnets'] subnets = module.params.get('subnets')
state = module.params['state'] state = module.params.get('state')
mso = MSOModule(module) mso = MSOModule(module)
# Get schema_id # Get schema_id
schema_obj = mso.get_obj('schemas', displayName=schema) schema_obj = mso.get_obj('schemas', displayName=schema)
if schema_obj: if schema_obj:
schema_id = schema_obj['id'] schema_id = schema_obj.get('id')
else: else:
mso.fail_json(msg="Provided schema '{0}' does not exist".format(schema)) mso.fail_json(msg="Provided schema '{0}' does not exist".format(schema))
schema_path = 'schemas/{id}'.format(**schema_obj) schema_path = 'schemas/{id}'.format(**schema_obj)
# Get template # Get template
templates = [t['name'] for t in schema_obj['templates']] templates = [t.get('name') for t in schema_obj.get('templates')]
if template not in templates: if template not in templates:
mso.fail_json(msg="Provided template '{0}' does not exist. Existing templates: {1}".format(template, ', '.join(templates))) mso.fail_json(msg="Provided template '{0}' does not exist. Existing templates: {1}".format(template, ', '.join(templates)))
template_idx = templates.index(template) template_idx = templates.index(template)
# Get ANP # Get ANP
bds = [b['name'] for b in schema_obj['templates'][template_idx]['bds']] bds = [b.get('name') for b in schema_obj.get('templates')[template_idx]['bds']]
if bd is not None and bd in bds: if bd is not None and bd in bds:
bd_idx = bds.index(bd) bd_idx = bds.index(bd)
mso.existing = schema_obj['templates'][template_idx]['bds'][bd_idx] mso.existing = schema_obj.get('templates')[template_idx]['bds'][bd_idx]
if state == 'query': if state == 'query':
if bd is None: if bd is None:
mso.existing = schema_obj['templates'][template_idx]['bds'] mso.existing = schema_obj.get('templates')[template_idx]['bds']
elif not mso.existing: elif not mso.existing:
mso.fail_json(msg="BD '{bd}' not found".format(bd=bd)) mso.fail_json(msg="BD '{bd}' not found".format(bd=bd))
mso.exit_json() mso.exit_json()

View file

@ -148,15 +148,15 @@ def main():
], ],
) )
schema = module.params['schema'] schema = module.params.get('schema')
template = module.params['template'] template = module.params.get('template')
bd = module.params['bd'] bd = module.params.get('bd')
subnet = module.params['subnet'] subnet = module.params.get('subnet')
description = module.params['description'] description = module.params.get('description')
scope = module.params['scope'] scope = module.params.get('scope')
shared = module.params['shared'] shared = module.params.get('shared')
no_default_gateway = module.params['no_default_gateway'] no_default_gateway = module.params.get('no_default_gateway')
state = module.params['state'] state = module.params.get('state')
mso = MSOModule(module) mso = MSOModule(module)
@ -168,28 +168,28 @@ def main():
schema_path = 'schemas/{id}'.format(**schema_obj) schema_path = 'schemas/{id}'.format(**schema_obj)
# Get template # Get template
templates = [t['name'] for t in schema_obj['templates']] templates = [t.get('name') for t in schema_obj.get('templates')]
if template not in templates: if template not in templates:
mso.fail_json(msg="Provided template '{0}' does not exist. Existing templates: {1}".format(template, ', '.join(templates))) mso.fail_json(msg="Provided template '{0}' does not exist. Existing templates: {1}".format(template, ', '.join(templates)))
template_idx = templates.index(template) template_idx = templates.index(template)
# Get BD # Get BD
bds = [b['name'] for b in schema_obj['templates'][template_idx]['bds']] bds = [b.get('name') for b in schema_obj.get('templates')[template_idx]['bds']]
if bd not in bds: if bd not in bds:
mso.fail_json(msg="Provided BD '{0}' does not exist. Existing BDs: {1}".format(bd, ', '.join(bds))) mso.fail_json(msg="Provided BD '{0}' does not exist. Existing BDs: {1}".format(bd, ', '.join(bds)))
bd_idx = bds.index(bd) bd_idx = bds.index(bd)
# Get Subnet # Get Subnet
subnets = [s['ip'] for s in schema_obj['templates'][template_idx]['bds'][bd_idx]['subnets']] subnets = [s.get('ip') for s in schema_obj.get('templates')[template_idx]['bds'][bd_idx]['subnets']]
if subnet in subnets: if subnet in subnets:
subnet_idx = subnets.index(subnet) subnet_idx = subnets.index(subnet)
# FIXME: Changes based on index are DANGEROUS # FIXME: Changes based on index are DANGEROUS
subnet_path = '/templates/{0}/bds/{1}/subnets/{2}'.format(template, bd, subnet_idx) subnet_path = '/templates/{0}/bds/{1}/subnets/{2}'.format(template, bd, subnet_idx)
mso.existing = schema_obj['templates'][template_idx]['bds'][bd_idx]['subnets'][subnet_idx] mso.existing = schema_obj.get('templates')[template_idx]['bds'][bd_idx]['subnets'][subnet_idx]
if state == 'query': if state == 'query':
if subnet is None: if subnet is None:
mso.existing = schema_obj['templates'][template_idx]['bds'][bd_idx]['subnets'] mso.existing = schema_obj.get('templates')[template_idx]['bds'][bd_idx]['subnets']
elif not mso.existing: elif not mso.existing:
mso.fail_json(msg="Subnet IP '{subnet}' not found".format(subnet=subnet)) mso.fail_json(msg="Subnet IP '{subnet}' not found".format(subnet=subnet))
mso.exit_json() mso.exit_json()

View file

@ -184,18 +184,18 @@ def main():
], ],
) )
schema = module.params['schema'] schema = module.params.get('schema')
template = module.params['template'] template = module.params.get('template')
contract = module.params['contract'] contract = module.params.get('contract')
contract_display_name = module.params['contract_display_name'] contract_display_name = module.params.get('contract_display_name')
contract_filter_type = module.params['contract_filter_type'] contract_filter_type = module.params.get('contract_filter_type')
contract_scope = module.params['contract_scope'] contract_scope = module.params.get('contract_scope')
filter_name = module.params['filter'] filter_name = module.params.get('filter')
filter_directives = module.params['filter_directives'] filter_directives = module.params.get('filter_directives')
filter_template = module.params['filter_template'] filter_template = module.params.get('filter_template')
filter_schema = module.params['filter_schema'] filter_schema = module.params.get('filter_schema')
filter_type = module.params['filter_type'] filter_type = module.params.get('filter_type')
state = module.params['state'] state = module.params.get('state')
contract_ftype = 'bothWay' if contract_filter_type == 'both-way' else 'oneWay' contract_ftype = 'bothWay' if contract_filter_type == 'both-way' else 'oneWay'
@ -219,14 +219,14 @@ def main():
# Get schema object # Get schema object
schema_obj = mso.get_obj('schemas', displayName=schema) schema_obj = mso.get_obj('schemas', displayName=schema)
if schema_obj: if schema_obj:
schema_id = schema_obj['id'] schema_id = schema_obj.get('id')
else: else:
mso.fail_json(msg="Provided schema '{0}' does not exist".format(schema)) mso.fail_json(msg="Provided schema '{0}' does not exist".format(schema))
schema_path = 'schemas/{id}'.format(**schema_obj) schema_path = 'schemas/{id}'.format(**schema_obj)
# Get template # Get template
templates = [t['name'] for t in schema_obj['templates']] templates = [t.get('name') for t in schema_obj.get('templates')]
if template not in templates: if template not in templates:
mso.fail_json(msg="Provided template '{0}' does not exist. Existing templates: {1}".format(template, ', '.join(templates))) mso.fail_json(msg="Provided template '{0}' does not exist. Existing templates: {1}".format(template, ', '.join(templates)))
template_idx = templates.index(template) template_idx = templates.index(template)
@ -235,24 +235,24 @@ def main():
mso.existing = {} mso.existing = {}
contract_idx = None contract_idx = None
filter_idx = None filter_idx = None
contracts = [c['name'] for c in schema_obj['templates'][template_idx]['contracts']] contracts = [c.get('name') for c in schema_obj.get('templates')[template_idx]['contracts']]
if contract in contracts: if contract in contracts:
contract_idx = contracts.index(contract) contract_idx = contracts.index(contract)
filters = [f['filterRef'] for f in schema_obj['templates'][template_idx]['contracts'][contract_idx][filter_key]] filters = [f.get('filterRef') for f in schema_obj.get('templates')[template_idx]['contracts'][contract_idx][filter_key]]
filter_ref = mso.filter_ref(schema_id=filter_schema_id, template=filter_template, filter=filter_name) filter_ref = mso.filter_ref(schema_id=filter_schema_id, template=filter_template, filter=filter_name)
if filter_ref in filters: if filter_ref in filters:
filter_idx = filters.index(filter_ref) filter_idx = filters.index(filter_ref)
filter_path = '/templates/{0}/contracts/{1}/{2}/{3}'.format(template, contract, filter_key, filter_name) filter_path = '/templates/{0}/contracts/{1}/{2}/{3}'.format(template, contract, filter_key, filter_name)
mso.existing = schema_obj['templates'][template_idx]['contracts'][contract_idx][filter_key][filter_idx] mso.existing = schema_obj.get('templates')[template_idx]['contracts'][contract_idx][filter_key][filter_idx]
if state == 'query': if state == 'query':
if contract_idx is None: if contract_idx is None:
mso.fail_json(msg="Provided contract '{0}' does not exist. Existing contracts: {1}".format(contract, ', '.join(contracts))) mso.fail_json(msg="Provided contract '{0}' does not exist. Existing contracts: {1}".format(contract, ', '.join(contracts)))
if filter_name is None: if filter_name is None:
mso.existing = schema_obj['templates'][template_idx]['contracts'][contract_idx][filter_key] mso.existing = schema_obj.get('templates')[template_idx]['contracts'][contract_idx][filter_key]
elif not mso.existing: elif not mso.existing:
mso.fail_json(msg="FilterRef '{filter_ref}' not found".format(filter_ref=filter_ref)) mso.fail_json(msg="FilterRef '{filter_ref}' not found".format(filter_ref=filter_ref))
mso.exit_json() mso.exit_json()

View file

@ -107,10 +107,10 @@ def main():
], ],
) )
schema = module.params['schema'] schema = module.params.get('schema')
template = module.params['template'] template = module.params.get('template')
site = module.params['site'] site = module.params.get('site')
state = module.params['state'] state = module.params.get('state')
mso = MSOModule(module) mso = MSOModule(module)

View file

@ -144,40 +144,40 @@ def main():
], ],
) )
schema = module.params['schema'] schema = module.params.get('schema')
template = module.params['template'] template = module.params.get('template')
externalepg = module.params['externalepg'] externalepg = module.params.get('externalepg')
display_name = module.params['display_name'] display_name = module.params.get('display_name')
vrf = module.params['vrf'] vrf = module.params.get('vrf')
state = module.params['state'] state = module.params.get('state')
mso = MSOModule(module) mso = MSOModule(module)
# Get schema_id # Get schema_id
schema_obj = mso.get_obj('schemas', displayName=schema) schema_obj = mso.get_obj('schemas', displayName=schema)
if schema_obj: if schema_obj:
schema_id = schema_obj['id'] schema_id = schema_obj.get('id')
else: else:
mso.fail_json(msg="Provided schema '{0}' does not exist".format(schema)) mso.fail_json(msg="Provided schema '{0}' does not exist".format(schema))
schema_path = 'schemas/{id}'.format(**schema_obj) schema_path = 'schemas/{id}'.format(**schema_obj)
# Get template # Get template
templates = [t['name'] for t in schema_obj['templates']] templates = [t.get('name') for t in schema_obj.get('templates')]
if template not in templates: if template not in templates:
mso.fail_json(msg="Provided template '{0}' does not exist. Existing templates: {1}".format(template, ', '.join(templates))) mso.fail_json(msg="Provided template '{0}' does not exist. Existing templates: {1}".format(template, ', '.join(templates)))
template_idx = templates.index(template) template_idx = templates.index(template)
# Get external EPGs # Get external EPGs
externalepgs = [e['name'] for e in schema_obj['templates'][template_idx]['externalEpgs']] externalepgs = [e.get('name') for e in schema_obj.get('templates')[template_idx]['externalEpgs']]
if externalepg is not None and externalepg in externalepgs: if externalepg is not None and externalepg in externalepgs:
externalepg_idx = externalepgs.index(externalepg) externalepg_idx = externalepgs.index(externalepg)
mso.existing = schema_obj['templates'][template_idx]['externalEpgs'][externalepg_idx] mso.existing = schema_obj.get('templates')[template_idx]['externalEpgs'][externalepg_idx]
if state == 'query': if state == 'query':
if externalepg is None: if externalepg is None:
mso.existing = schema_obj['templates'][template_idx]['externalEpgs'] mso.existing = schema_obj.get('templates')[template_idx]['externalEpgs']
elif not mso.existing: elif not mso.existing:
mso.fail_json(msg="External EPG '{externalepg}' not found".format(externalepg=externalepg)) mso.fail_json(msg="External EPG '{externalepg}' not found".format(externalepg=externalepg))
mso.exit_json() mso.exit_json()

View file

@ -201,24 +201,24 @@ def main():
], ],
) )
schema = module.params['schema'] schema = module.params.get('schema')
template = module.params['template'] template = module.params.get('template')
filter_name = module.params['filter'] filter_name = module.params.get('filter')
filter_display_name = module.params['filter_display_name'] filter_display_name = module.params.get('filter_display_name')
entry = module.params['entry'] entry = module.params.get('entry')
display_name = module.params['display_name'] display_name = module.params.get('display_name')
description = module.params['description'] description = module.params.get('description')
ethertype = module.params['ethertype'] ethertype = module.params.get('ethertype')
ip_protocol = module.params['ip_protocol'] ip_protocol = module.params.get('ip_protocol')
tcp_session_rules = module.params['tcp_session_rules'] tcp_session_rules = module.params.get('tcp_session_rules')
source_from = module.params['source_from'] source_from = module.params.get('source_from')
source_to = module.params['source_to'] source_to = module.params.get('source_to')
destination_from = module.params['destination_from'] destination_from = module.params.get('destination_from')
destination_to = module.params['destination_to'] destination_to = module.params.get('destination_to')
arp_flag = module.params['arp_flag'] arp_flag = module.params.get('arp_flag')
stateful = module.params['stateful'] stateful = module.params.get('stateful')
fragments_only = module.params['fragments_only'] fragments_only = module.params.get('fragments_only')
state = module.params['state'] state = module.params.get('state')
mso = MSOModule(module) mso = MSOModule(module)
@ -230,7 +230,7 @@ def main():
schema_path = 'schemas/{id}'.format(**schema_obj) schema_path = 'schemas/{id}'.format(**schema_obj)
# Get template # Get template
templates = [t['name'] for t in schema_obj['templates']] templates = [t.get('name') for t in schema_obj.get('templates')]
if template not in templates: if template not in templates:
mso.fail_json(msg="Provided template '{template}' does not exist. Existing templates: {templates}".format(template=template, mso.fail_json(msg="Provided template '{template}' does not exist. Existing templates: {templates}".format(template=template,
templates=', '.join(templates))) templates=', '.join(templates)))
@ -240,20 +240,20 @@ def main():
mso.existing = {} mso.existing = {}
filter_idx = None filter_idx = None
entry_idx = None entry_idx = None
filters = [f['name'] for f in schema_obj['templates'][template_idx]['filters']] filters = [f.get('name') for f in schema_obj.get('templates')[template_idx]['filters']]
if filter_name in filters: if filter_name in filters:
filter_idx = filters.index(filter_name) filter_idx = filters.index(filter_name)
entries = [f['name'] for f in schema_obj['templates'][template_idx]['filters'][filter_idx]['entries']] entries = [f.get('name') for f in schema_obj.get('templates')[template_idx]['filters'][filter_idx]['entries']]
if entry in entries: if entry in entries:
entry_idx = entries.index(entry) entry_idx = entries.index(entry)
mso.existing = schema_obj['templates'][template_idx]['filters'][filter_idx]['entries'][entry_idx] mso.existing = schema_obj.get('templates')[template_idx]['filters'][filter_idx]['entries'][entry_idx]
if state == 'query': if state == 'query':
if entry is None: if entry is None:
if filter_idx is None: if filter_idx is None:
mso.fail_json(msg="Filter '{filter}' not found".format(filter=filter_name)) mso.fail_json(msg="Filter '{filter}' not found".format(filter=filter_name))
mso.existing = schema_obj['templates'][template_idx]['filters'][filter_idx]['entries'] mso.existing = schema_obj.get('templates')[template_idx]['filters'][filter_idx]['entries']
elif not mso.existing: elif not mso.existing:
mso.fail_json(msg="Entry '{entry}' not found".format(entry=entry)) mso.fail_json(msg="Entry '{entry}' not found".format(entry=entry))
mso.exit_json() mso.exit_json()

View file

@ -144,40 +144,40 @@ def main():
], ],
) )
schema = module.params['schema'] schema = module.params.get('schema')
template = module.params['template'] template = module.params.get('template')
l3out = module.params['l3out'] l3out = module.params.get('l3out')
display_name = module.params['display_name'] display_name = module.params.get('display_name')
vrf = module.params['vrf'] vrf = module.params.get('vrf')
state = module.params['state'] state = module.params.get('state')
mso = MSOModule(module) mso = MSOModule(module)
# Get schema_id # Get schema_id
schema_obj = mso.get_obj('schemas', displayName=schema) schema_obj = mso.get_obj('schemas', displayName=schema)
if schema_obj: if schema_obj:
schema_id = schema_obj['id'] schema_id = schema_obj.get('id')
else: else:
mso.fail_json(msg="Provided schema '{0}' does not exist".format(schema)) mso.fail_json(msg="Provided schema '{0}' does not exist".format(schema))
schema_path = 'schemas/{id}'.format(**schema_obj) schema_path = 'schemas/{id}'.format(**schema_obj)
# Get template # Get template
templates = [t['name'] for t in schema_obj['templates']] templates = [t.get('name') for t in schema_obj.get('templates')]
if template not in templates: if template not in templates:
mso.fail_json(msg="Provided template '{0}' does not exist. Existing templates: {1}".format(template, ', '.join(templates))) mso.fail_json(msg="Provided template '{0}' does not exist. Existing templates: {1}".format(template, ', '.join(templates)))
template_idx = templates.index(template) template_idx = templates.index(template)
# Get L3out # Get L3out
l3outs = [l['name'] for l in schema_obj['templates'][template_idx]['intersiteL3outs']] l3outs = [l.get('name') for l in schema_obj.get('templates')[template_idx]['intersiteL3outs']]
if l3out is not None and l3out in l3outs: if l3out is not None and l3out in l3outs:
l3out_idx = l3outs.index(l3out) l3out_idx = l3outs.index(l3out)
mso.existing = schema_obj['templates'][template_idx]['intersiteL3outs'][l3out_idx] mso.existing = schema_obj.get('templates')[template_idx]['intersiteL3outs'][l3out_idx]
if state == 'query': if state == 'query':
if l3out is None: if l3out is None:
mso.existing = schema_obj['templates'][template_idx]['intersiteL3outs'] mso.existing = schema_obj.get('templates')[template_idx]['intersiteL3outs']
elif not mso.existing: elif not mso.existing:
mso.fail_json(msg="L3out '{l3out}' not found".format(l3out=l3out)) mso.fail_json(msg="L3out '{l3out}' not found".format(l3out=l3out))
mso.exit_json() mso.exit_json()

View file

@ -128,12 +128,12 @@ def main():
], ],
) )
schema = module.params['schema'] schema = module.params.get('schema')
template = module.params['template'] template = module.params.get('template')
vrf = module.params['vrf'] vrf = module.params.get('vrf')
display_name = module.params['display_name'] display_name = module.params.get('display_name')
layer3_multicast = module.params['layer3_multicast'] layer3_multicast = module.params.get('layer3_multicast')
state = module.params['state'] state = module.params.get('state')
mso = MSOModule(module) mso = MSOModule(module)
@ -145,21 +145,21 @@ def main():
schema_path = 'schemas/{id}'.format(**schema_obj) schema_path = 'schemas/{id}'.format(**schema_obj)
# Get template # Get template
templates = [t['name'] for t in schema_obj['templates']] templates = [t.get('name') for t in schema_obj.get('templates')]
if template not in templates: if template not in templates:
mso.fail_json(msg="Provided template '{0}' does not exist. Existing templates: {1}".format(template, ', '.join(templates))) mso.fail_json(msg="Provided template '{0}' does not exist. Existing templates: {1}".format(template, ', '.join(templates)))
template_idx = templates.index(template) template_idx = templates.index(template)
# Get ANP # Get ANP
vrfs = [v['name'] for v in schema_obj['templates'][template_idx]['vrfs']] vrfs = [v.get('name') for v in schema_obj.get('templates')[template_idx]['vrfs']]
if vrf is not None and vrf in vrfs: if vrf is not None and vrf in vrfs:
vrf_idx = vrfs.index(vrf) vrf_idx = vrfs.index(vrf)
mso.existing = schema_obj['templates'][template_idx]['vrfs'][vrf_idx] mso.existing = schema_obj.get('templates')[template_idx]['vrfs'][vrf_idx]
if state == 'query': if state == 'query':
if vrf is None: if vrf is None:
mso.existing = schema_obj['templates'][template_idx]['vrfs'] mso.existing = schema_obj.get('templates')[template_idx]['vrfs']
elif not mso.existing: elif not mso.existing:
mso.fail_json(msg="VRF '{vrf}' not found".format(vrf=vrf)) mso.fail_json(msg="VRF '{vrf}' not found".format(vrf=vrf))
mso.exit_json() mso.exit_json()

View file

@ -163,16 +163,16 @@ def main():
], ],
) )
apic_username = module.params['apic_username'] apic_username = module.params.get('apic_username')
apic_password = module.params['apic_password'] apic_password = module.params.get('apic_password')
apic_site_id = module.params['apic_site_id'] apic_site_id = module.params.get('apic_site_id')
site = module.params['site'] site = module.params.get('site')
location = module.params['location'] location = module.params.get('location')
if location is not None: if location is not None:
latitude = module.params['location']['latitude'] latitude = module.params.get('location')['latitude']
longitude = module.params['location']['longitude'] longitude = module.params.get('location')['longitude']
state = module.params['state'] state = module.params.get('state')
urls = module.params['urls'] urls = module.params.get('urls')
mso = MSOModule(module) mso = MSOModule(module)
@ -180,13 +180,13 @@ def main():
path = 'sites' path = 'sites'
# Convert labels # Convert labels
labels = mso.lookup_labels(module.params['labels'], 'site') labels = mso.lookup_labels(module.params.get('labels'), 'site')
# Query for mso.existing object(s) # Query for mso.existing object(s)
if site: if site:
mso.existing = mso.get_obj(path, name=site) mso.existing = mso.get_obj(path, name=site)
if mso.existing: if mso.existing:
site_id = mso.existing['id'] site_id = mso.existing.get('id')
# If we found an existing object, continue with it # If we found an existing object, continue with it
path = 'sites/{id}'.format(id=site_id) path = 'sites/{id}'.format(id=site_id)
else: else:

Some files were not shown because too many files have changed in this diff Show more