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.py21
-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, 173 insertions, 5 deletions
diff --git a/roles/lib_utils/filter_plugins/oo_filters.py b/roles/lib_utils/filter_plugins/oo_filters.py
index 0f1b5bc2d..574743ff1 100644
--- a/roles/lib_utils/filter_plugins/oo_filters.py
+++ b/roles/lib_utils/filter_plugins/oo_filters.py
@@ -4,6 +4,7 @@
"""
Custom filters for use in openshift-ansible
"""
+import json
import os
import pdb
import random
@@ -271,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.
@@ -317,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"))
@@ -638,6 +640,18 @@ that result to this filter plugin.
return secret_name
+def lib_utils_oo_l_of_d_to_csv(input_list):
+ """Map a list of dictionaries, input_list, into a csv string
+ of json values.
+
+ Example input:
+ [{'var1': 'val1', 'var2': 'val2'}, {'var1': 'val3', 'var2': 'val4'}]
+ Example output:
+ u'{"var1": "val1", "var2": "val2"},{"var1": "val3", "var2": "val4"}'
+ """
+ return ','.join(json.dumps(x) for x in input_list)
+
+
def map_from_pairs(source, delim="="):
''' Returns a dict given the source and delim delimited '''
if source == '':
@@ -676,5 +690,6 @@ class FilterModule(object):
"lib_utils_oo_contains_rule": lib_utils_oo_contains_rule,
"lib_utils_oo_selector_to_string_list": lib_utils_oo_selector_to_string_list,
"lib_utils_oo_filter_sa_secrets": lib_utils_oo_filter_sa_secrets,
+ "lib_utils_oo_l_of_d_to_csv": lib_utils_oo_l_of_d_to_csv,
"map_from_pairs": map_from_pairs
}
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..b94c0b779 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]:
@@ -151,7 +151,7 @@ def write_config(module, docker_config, dest):
conf_file_path = os.path.join(dest, 'config.json')
try:
with open(conf_file_path, 'w') as conf_file:
- json.dump(docker_config, conf_file, indent=8)
+ json.dump(docker_config.decode(), conf_file, indent=8)
except IOError as ioerror:
result = {'failed': True,
'changed': False,
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()