summaryrefslogtreecommitdiffstats
path: root/roles/lib_utils
diff options
context:
space:
mode:
Diffstat (limited to 'roles/lib_utils')
-rw-r--r--roles/lib_utils/filter_plugins/oo_filters.py60
-rw-r--r--roles/lib_utils/filter_plugins/openshift_aws_filters.py16
-rw-r--r--roles/lib_utils/library/docker_creds.py4
-rw-r--r--roles/lib_utils/library/swapoff.py137
4 files changed, 213 insertions, 4 deletions
diff --git a/roles/lib_utils/filter_plugins/oo_filters.py b/roles/lib_utils/filter_plugins/oo_filters.py
index ef996fefe..574743ff1 100644
--- a/roles/lib_utils/filter_plugins/oo_filters.py
+++ b/roles/lib_utils/filter_plugins/oo_filters.py
@@ -272,7 +272,7 @@ def haproxy_backend_masters(hosts, port):
return servers
-# pylint: disable=too-many-branches
+# pylint: disable=too-many-branches, too-many-nested-blocks
def lib_utils_oo_parse_named_certificates(certificates, named_certs_dir, internal_hostnames):
""" Parses names from list of certificate hashes.
@@ -318,8 +318,9 @@ def lib_utils_oo_parse_named_certificates(certificates, named_certs_dir, interna
certificate['names'].append(str(cert.get_subject().commonName.decode()))
for i in range(cert.get_extension_count()):
if cert.get_extension(i).get_short_name() == 'subjectAltName':
- for name in str(cert.get_extension(i)).replace('DNS:', '').split(', '):
- certificate['names'].append(name)
+ for name in str(cert.get_extension(i)).split(', '):
+ if 'DNS:' in name:
+ certificate['names'].append(name.replace('DNS:', ''))
except Exception:
raise errors.AnsibleFilterError(("|failed to parse certificate '%s', " % certificate['certfile'] +
"please specify certificate names in host inventory"))
@@ -341,6 +342,58 @@ def lib_utils_oo_parse_named_certificates(certificates, named_certs_dir, interna
return certificates
+def lib_utils_oo_parse_certificate_san(certificate):
+ """ Parses SubjectAlternativeNames from a PEM certificate.
+
+ Ex: certificate = '''-----BEGIN CERTIFICATE-----
+ MIIEcjCCAlqgAwIBAgIBAzANBgkqhkiG9w0BAQsFADAhMR8wHQYDVQQDDBZldGNk
+ LXNpZ25lckAxNTE2ODIwNTg1MB4XDTE4MDEyNDE5MDMz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kfGk+COa5riT9hJ7wZY0Hb
+ YiJS74SZgZt/nnr5PI2zFRUiZLECqCkZnC/sz29i+irLabnq7Cif9Mv+TUcXWvry
+ TdJuaaYdTSMRSUkDd/c9Ife8tOr1i1xhFzDNKNkZjTVRk1MBquSXndVCDKucdfGi
+ YoWm+NDFrayw8yxK/KTHo3Db3lu1eIXTHxriodFx898b//hysHr4hs4/tsEFUTZi
+ 705L2ScIFLfnyaPby5GK/3sBIXtuhOFM3QV3JoYKlJB5T6wJioVoUmSLc+UxZMeE
+ t9gGVQbVxtLvNHUdW7uKQ5pd76nIJqApQf8wg2Pja8oo56fRZX2XLt8nm9cswcC4
+ Y1mDMvtfxglQATwMTuoKGdREuu1mbdb8QqdyQmZuMa72q+ax2kQ=
+ -----END CERTIFICATE-----'''
+
+ returns ['192.168.122.186']
+ """
+
+ if not HAS_OPENSSL:
+ raise errors.AnsibleFilterError("|missing OpenSSL python bindings")
+
+ names = []
+
+ try:
+ lcert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, certificate)
+ for i in range(lcert.get_extension_count()):
+ if lcert.get_extension(i).get_short_name() == 'subjectAltName':
+ sanstr = str(lcert.get_extension(i))
+ sanstr = sanstr.replace('DNS:', '')
+ sanstr = sanstr.replace('IP Address:', '')
+ names = sanstr.split(', ')
+ except Exception:
+ raise errors.AnsibleFilterError("|failed to parse certificate")
+
+ return names
+
+
def lib_utils_oo_generate_secret(num_bytes):
""" generate a session secret """
@@ -625,6 +678,7 @@ class FilterModule(object):
"lib_utils_oo_dict_to_keqv_list": lib_utils_oo_dict_to_keqv_list,
"lib_utils_oo_list_to_dict": lib_utils_oo_list_to_dict,
"lib_utils_oo_parse_named_certificates": lib_utils_oo_parse_named_certificates,
+ "lib_utils_oo_parse_certificate_san": lib_utils_oo_parse_certificate_san,
"lib_utils_oo_generate_secret": lib_utils_oo_generate_secret,
"lib_utils_oo_pods_match_component": lib_utils_oo_pods_match_component,
"lib_utils_oo_image_tag_to_rpm_version": lib_utils_oo_image_tag_to_rpm_version,
diff --git a/roles/lib_utils/filter_plugins/openshift_aws_filters.py b/roles/lib_utils/filter_plugins/openshift_aws_filters.py
index dfcb11da3..f16048056 100644
--- a/roles/lib_utils/filter_plugins/openshift_aws_filters.py
+++ b/roles/lib_utils/filter_plugins/openshift_aws_filters.py
@@ -67,8 +67,24 @@ class FilterModule(object):
return tags
+ @staticmethod
+ def get_default_az(subnets):
+ ''' From a list of subnets/AZs in a specific region (from the VPC
+ structure), return the AZ that has the key/value
+ 'default_az=True.' '''
+
+ for subnet in subnets:
+ if subnet.get('default_az'):
+ return subnet['az']
+
+ # if there was none marked with default_az=True, just return the first
+ # one. (this does mean we could possible return an item that has
+ # default_az=False set
+ return subnets[0]['az']
+
def filters(self):
''' returns a mapping of filters to methods '''
return {'build_instance_tags': self.build_instance_tags,
+ 'get_default_az': self.get_default_az,
'scale_groups_match_capacity': self.scale_groups_match_capacity,
'scale_groups_serial': self.scale_groups_serial}
diff --git a/roles/lib_utils/library/docker_creds.py b/roles/lib_utils/library/docker_creds.py
index d4674845e..936fb1c38 100644
--- a/roles/lib_utils/library/docker_creds.py
+++ b/roles/lib_utils/library/docker_creds.py
@@ -135,7 +135,7 @@ def update_config(docker_config, registry, username, password):
docker_config['auths'][registry] = {}
# base64 encode our username:password string
- encoded_data = base64.b64encode('{}:{}'.format(username, password))
+ encoded_data = base64.b64encode('{}:{}'.format(username, password).encode())
# check if the same value is already present for idempotency.
if 'auth' in docker_config['auths'][registry]:
@@ -148,6 +148,8 @@ def update_config(docker_config, registry, username, password):
def write_config(module, docker_config, dest):
'''Write updated credentials into dest/config.json'''
+ if not isinstance(docker_config, dict):
+ docker_config = docker_config.decode()
conf_file_path = os.path.join(dest, 'config.json')
try:
with open(conf_file_path, 'w') as conf_file:
diff --git a/roles/lib_utils/library/swapoff.py b/roles/lib_utils/library/swapoff.py
new file mode 100644
index 000000000..925eeb17d
--- /dev/null
+++ b/roles/lib_utils/library/swapoff.py
@@ -0,0 +1,137 @@
+#!/usr/bin/env python
+# pylint: disable=missing-docstring
+#
+# Copyright 2017 Red Hat, Inc. and/or its affiliates
+# and other contributors as indicated by the @author tags.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import subprocess
+
+from ansible.module_utils.basic import AnsibleModule
+
+
+DOCUMENTATION = '''
+---
+module: swapoff
+
+short_description: Disable swap and comment from /etc/fstab
+
+version_added: "2.4"
+
+description:
+ - This module disables swap and comments entries from /etc/fstab
+
+author:
+ - "Michael Gugino <mgugino@redhat.com>"
+'''
+
+EXAMPLES = '''
+# Pass in a message
+- name: Disable Swap
+ swapoff: {}
+'''
+
+
+def check_swap_in_fstab(module):
+ '''Check for uncommented swap entries in fstab'''
+ res = subprocess.call(['grep', '^[^#].*swap', '/etc/fstab'])
+
+ if res == 2:
+ # rc 2 == cannot open file.
+ result = {'failed': True,
+ 'changed': False,
+ 'msg': 'unable to read /etc/fstab',
+ 'state': 'unknown'}
+ module.fail_json(**result)
+ elif res == 1:
+ # No grep match, fstab looks good.
+ return False
+ elif res == 0:
+ # There is an uncommented entry for fstab.
+ return True
+ else:
+ # Some other grep error code, we shouldn't get here.
+ result = {'failed': True,
+ 'changed': False,
+ 'msg': 'unknow problem with grep "^[^#].*swap" /etc/fstab ',
+ 'state': 'unknown'}
+ module.fail_json(**result)
+
+
+def check_swapon_status(module):
+ '''Check if swap is actually in use.'''
+ try:
+ res = subprocess.check_output(['swapon', '--show'])
+ except subprocess.CalledProcessError:
+ # Some other grep error code, we shouldn't get here.
+ result = {'failed': True,
+ 'changed': False,
+ 'msg': 'unable to execute swapon --show',
+ 'state': 'unknown'}
+ module.fail_json(**result)
+ return 'NAME' in str(res)
+
+
+def comment_swap_fstab(module):
+ '''Comment out swap lines in /etc/fstab'''
+ res = subprocess.call(['sed', '-i.bak', 's/^[^#].*swap.*/#&/', '/etc/fstab'])
+ if res:
+ result = {'failed': True,
+ 'changed': False,
+ 'msg': 'sed failed to comment swap in /etc/fstab',
+ 'state': 'unknown'}
+ module.fail_json(**result)
+
+
+def run_swapoff(module, changed):
+ '''Run swapoff command'''
+ res = subprocess.call(['swapoff', '--all'])
+ if res:
+ result = {'failed': True,
+ 'changed': changed,
+ 'msg': 'swapoff --all returned {}'.format(str(res)),
+ 'state': 'unknown'}
+ module.fail_json(**result)
+
+
+def run_module():
+ '''Run this module'''
+ module = AnsibleModule(
+ supports_check_mode=False,
+ argument_spec={}
+ )
+ changed = False
+
+ swap_fstab_res = check_swap_in_fstab(module)
+ swap_is_inuse_res = check_swapon_status(module)
+
+ if swap_fstab_res:
+ comment_swap_fstab(module)
+ changed = True
+
+ if swap_is_inuse_res:
+ run_swapoff(module, changed)
+ changed = True
+
+ result = {'changed': changed}
+
+ module.exit_json(**result)
+
+
+def main():
+ run_module()
+
+
+if __name__ == '__main__':
+ main()