diff options
Diffstat (limited to 'roles/lib_openshift/src')
27 files changed, 2642 insertions, 1 deletions
diff --git a/roles/lib_openshift/src/ansible/oc_adm_ca_server_cert.py b/roles/lib_openshift/src/ansible/oc_adm_ca_server_cert.py index c80c2eb44..10f1c9b4b 100644 --- a/roles/lib_openshift/src/ansible/oc_adm_ca_server_cert.py +++ b/roles/lib_openshift/src/ansible/oc_adm_ca_server_cert.py @@ -20,6 +20,7 @@ def main(): signer_key=dict(default='/etc/origin/master/ca.key', type='str'), signer_serial=dict(default='/etc/origin/master/ca.serial.txt', type='str'), hostnames=dict(default=[], type='list'), + expire_days=dict(default=None, type='int'), ), supports_check_mode=True, ) diff --git a/roles/lib_openshift/src/ansible/oc_clusterrole.py b/roles/lib_openshift/src/ansible/oc_clusterrole.py new file mode 100644 index 000000000..7e4319d2c --- /dev/null +++ b/roles/lib_openshift/src/ansible/oc_clusterrole.py @@ -0,0 +1,29 @@ +# pylint: skip-file +# flake8: noqa + +def main(): + ''' + ansible oc module for clusterrole + ''' + + module = AnsibleModule( + argument_spec=dict( + kubeconfig=dict(default='/etc/origin/master/admin.kubeconfig', type='str'), + state=dict(default='present', type='str', + choices=['present', 'absent', 'list']), + debug=dict(default=False, type='bool'), + name=dict(default=None, type='str'), + rules=dict(default=None, type='list'), + ), + supports_check_mode=True, + ) + + results = OCClusterRole.run_ansible(module.params, module.check_mode) + + if 'failed' in results: + module.fail_json(**results) + + module.exit_json(**results) + +if __name__ == '__main__': + main() diff --git a/roles/lib_openshift/src/ansible/oc_configmap.py b/roles/lib_openshift/src/ansible/oc_configmap.py new file mode 100644 index 000000000..974f72499 --- /dev/null +++ b/roles/lib_openshift/src/ansible/oc_configmap.py @@ -0,0 +1,32 @@ +# pylint: skip-file +# flake8: noqa + + +def main(): + ''' + ansible oc module for managing OpenShift configmap objects + ''' + + module = AnsibleModule( + argument_spec=dict( + kubeconfig=dict(default='/etc/origin/master/admin.kubeconfig', type='str'), + state=dict(default='present', type='str', + choices=['present', 'absent', 'list']), + debug=dict(default=False, type='bool'), + namespace=dict(default='default', type='str'), + name=dict(default=None, required=True, type='str'), + from_file=dict(default=None, type='dict'), + from_literal=dict(default=None, type='dict'), + ), + supports_check_mode=True, + ) + + + rval = OCConfigMap.run_ansible(module.params, module.check_mode) + if 'failed' in rval: + module.fail_json(**rval) + + module.exit_json(**rval) + +if __name__ == '__main__': + main() diff --git a/roles/lib_openshift/src/ansible/oc_image.py b/roles/lib_openshift/src/ansible/oc_image.py new file mode 100644 index 000000000..447d62f20 --- /dev/null +++ b/roles/lib_openshift/src/ansible/oc_image.py @@ -0,0 +1,34 @@ +# pylint: skip-file +# flake8: noqa + + +def main(): + ''' + ansible oc module for image import + ''' + + module = AnsibleModule( + argument_spec=dict( + kubeconfig=dict(default='/etc/origin/master/admin.kubeconfig', type='str'), + state=dict(default='present', type='str', + choices=['present', 'list']), + debug=dict(default=False, type='bool'), + namespace=dict(default='default', type='str'), + registry_url=dict(default=None, type='str'), + image_name=dict(default=None, required=True, type='str'), + image_tag=dict(default=None, type='str'), + force=dict(default=False, type='bool'), + ), + + supports_check_mode=True, + ) + + rval = OCImage.run_ansible(module.params, module.check_mode) + + if 'failed' in rval: + module.fail_json(**rval) + + module.exit_json(**rval) + +if __name__ == '__main__': + main() diff --git a/roles/lib_openshift/src/ansible/oc_user.py b/roles/lib_openshift/src/ansible/oc_user.py new file mode 100644 index 000000000..6b1440796 --- /dev/null +++ b/roles/lib_openshift/src/ansible/oc_user.py @@ -0,0 +1,34 @@ +# pylint: skip-file +# flake8: noqa + +def main(): + ''' + ansible oc module for user + ''' + + module = AnsibleModule( + argument_spec=dict( + kubeconfig=dict(default='/etc/origin/master/admin.kubeconfig', type='str'), + state=dict(default='present', type='str', + choices=['present', 'absent', 'list']), + debug=dict(default=False, type='bool'), + username=dict(default=None, type='str'), + full_name=dict(default=None, type='str'), + # setting groups for user data will not populate the + # 'groups' field in the user data. + # it will call out to the group data and make the user + # entry there + groups=dict(default=[], type='list'), + ), + supports_check_mode=True, + ) + + results = OCUser.run_ansible(module.params, module.check_mode) + + if 'failed' in results: + module.fail_json(**results) + + module.exit_json(**results) + +if __name__ == '__main__': + main() diff --git a/roles/lib_openshift/src/class/oc_adm_ca_server_cert.py b/roles/lib_openshift/src/class/oc_adm_ca_server_cert.py index 18c69f2fa..fa0c4e3af 100644 --- a/roles/lib_openshift/src/class/oc_adm_ca_server_cert.py +++ b/roles/lib_openshift/src/class/oc_adm_ca_server_cert.py @@ -102,6 +102,7 @@ class CAServerCert(OpenShiftCLI): 'signer_cert': {'value': params['signer_cert'], 'include': True}, 'signer_key': {'value': params['signer_key'], 'include': True}, 'signer_serial': {'value': params['signer_serial'], 'include': True}, + 'expire_days': {'value': params['expire_days'], 'include': True}, 'backup': {'value': params['backup'], 'include': False}, }) diff --git a/roles/lib_openshift/src/class/oc_clusterrole.py b/roles/lib_openshift/src/class/oc_clusterrole.py new file mode 100644 index 000000000..1d3d977db --- /dev/null +++ b/roles/lib_openshift/src/class/oc_clusterrole.py @@ -0,0 +1,163 @@ +# pylint: skip-file +# flake8: noqa + + +# pylint: disable=too-many-instance-attributes +class OCClusterRole(OpenShiftCLI): + ''' Class to manage clusterrole objects''' + kind = 'clusterrole' + + def __init__(self, + name, + rules=None, + kubeconfig=None, + verbose=False): + ''' Constructor for OCClusterRole ''' + super(OCClusterRole, self).__init__(None, kubeconfig=kubeconfig, verbose=verbose) + self.verbose = verbose + self.name = name + self._clusterrole = None + self._inc_clusterrole = ClusterRole.builder(name, rules) + + @property + def clusterrole(self): + ''' property for clusterrole''' + if not self._clusterrole: + self.get() + return self._clusterrole + + @clusterrole.setter + def clusterrole(self, data): + ''' setter function for clusterrole property''' + self._clusterrole = data + + @property + def inc_clusterrole(self): + ''' property for inc_clusterrole''' + return self._inc_clusterrole + + @inc_clusterrole.setter + def inc_clusterrole(self, data): + ''' setter function for inc_clusterrole property''' + self._inc_clusterrole = data + + def exists(self): + ''' return whether a clusterrole exists ''' + if self.clusterrole: + return True + + return False + + def get(self): + '''return a clusterrole ''' + result = self._get(self.kind, self.name) + + if result['returncode'] == 0: + self.clusterrole = ClusterRole(content=result['results'][0]) + result['results'] = self.clusterrole.yaml_dict + + elif 'clusterrole "{}" not found'.format(self.name) in result['stderr']: + result['returncode'] = 0 + + return result + + def delete(self): + '''delete the object''' + return self._delete(self.kind, self.name) + + def create(self): + '''create a clusterrole from the proposed incoming clusterrole''' + return self._create_from_content(self.name, self.inc_clusterrole.yaml_dict) + + def update(self): + '''update a project''' + return self._replace_content(self.kind, self.name, self.inc_clusterrole.yaml_dict) + + def needs_update(self): + ''' verify an update is needed''' + return not self.clusterrole.compare(self.inc_clusterrole, self.verbose) + + # pylint: disable=too-many-return-statements,too-many-branches + @staticmethod + def run_ansible(params, check_mode): + '''run the idempotent ansible code''' + + oc_clusterrole = OCClusterRole(params['name'], + params['rules'], + params['kubeconfig'], + params['debug']) + + state = params['state'] + + api_rval = oc_clusterrole.get() + + ##### + # Get + ##### + if state == 'list': + return {'changed': False, 'results': api_rval, 'state': state} + + ######## + # Delete + ######## + if state == 'absent': + if oc_clusterrole.exists(): + + if check_mode: + return {'changed': True, 'msg': 'CHECK_MODE: Would have performed a delete.'} + + api_rval = oc_clusterrole.delete() + + if api_rval['returncode'] != 0: + return {'failed': True, 'msg': api_rval} + + return {'changed': True, 'results': api_rval, 'state': state} + + return {'changed': False, 'state': state} + + if state == 'present': + ######## + # Create + ######## + if not oc_clusterrole.exists(): + + if check_mode: + return {'changed': True, 'msg': 'CHECK_MODE: Would have performed a create.'} + + # Create it here + api_rval = oc_clusterrole.create() + + # return the created object + api_rval = oc_clusterrole.get() + + if api_rval['returncode'] != 0: + return {'failed': True, 'msg': api_rval} + + return {'changed': True, 'results': api_rval, 'state': state} + + ######## + # Update + ######## + if oc_clusterrole.needs_update(): + + if check_mode: + return {'changed': True, 'msg': 'CHECK_MODE: Would have performed an update.'} + + api_rval = oc_clusterrole.update() + + if api_rval['returncode'] != 0: + return {'failed': True, 'msg': api_rval} + + # return the created object + api_rval = oc_clusterrole.get() + + if api_rval['returncode'] != 0: + return {'failed': True, 'msg': api_rval} + + return {'changed': True, 'results': api_rval, 'state': state} + + return {'changed': False, 'results': api_rval, 'state': state} + + return {'failed': True, + 'changed': False, + 'msg': 'Unknown state passed. [%s]' % state} diff --git a/roles/lib_openshift/src/class/oc_configmap.py b/roles/lib_openshift/src/class/oc_configmap.py new file mode 100644 index 000000000..87de3e1df --- /dev/null +++ b/roles/lib_openshift/src/class/oc_configmap.py @@ -0,0 +1,187 @@ +# pylint: skip-file +# flake8: noqa + + +# pylint: disable=too-many-arguments +class OCConfigMap(OpenShiftCLI): + ''' Openshift ConfigMap Class + + ConfigMaps are a way to store data inside of objects + ''' + def __init__(self, + name, + from_file, + from_literal, + state, + namespace, + kubeconfig='/etc/origin/master/admin.kubeconfig', + verbose=False): + ''' Constructor for OpenshiftOC ''' + super(OCConfigMap, self).__init__(namespace, kubeconfig=kubeconfig, verbose=verbose) + self.name = name + self.state = state + self._configmap = None + self._inc_configmap = None + self.from_file = from_file if from_file is not None else {} + self.from_literal = from_literal if from_literal is not None else {} + + @property + def configmap(self): + if self._configmap is None: + self._configmap = self.get() + + return self._configmap + + @configmap.setter + def configmap(self, inc_map): + self._configmap = inc_map + + @property + def inc_configmap(self): + if self._inc_configmap is None: + results = self.create(dryrun=True, output=True) + self._inc_configmap = results['results'] + + return self._inc_configmap + + @inc_configmap.setter + def inc_configmap(self, inc_map): + self._inc_configmap = inc_map + + def from_file_to_params(self): + '''return from_files in a string ready for cli''' + return ["--from-file={}={}".format(key, value) for key, value in self.from_file.items()] + + def from_literal_to_params(self): + '''return from_literal in a string ready for cli''' + return ["--from-literal={}={}".format(key, value) for key, value in self.from_literal.items()] + + def get(self): + '''return a configmap by name ''' + results = self._get('configmap', self.name) + if results['returncode'] == 0 and results['results'][0]: + self.configmap = results['results'][0] + + if results['returncode'] != 0 and '"{}" not found'.format(self.name) in results['stderr']: + results['returncode'] = 0 + + return results + + def delete(self): + '''delete a configmap by name''' + return self._delete('configmap', self.name) + + def create(self, dryrun=False, output=False): + '''Create a configmap + + :dryrun: Product what you would have done. default: False + :output: Whether to parse output. default: False + ''' + + cmd = ['create', 'configmap', self.name] + if self.from_literal is not None: + cmd.extend(self.from_literal_to_params()) + + if self.from_file is not None: + cmd.extend(self.from_file_to_params()) + + if dryrun: + cmd.extend(['--dry-run', '-ojson']) + + results = self.openshift_cmd(cmd, output=output) + + return results + + def update(self): + '''run update configmap ''' + return self._replace_content('configmap', self.name, self.inc_configmap) + + def needs_update(self): + '''compare the current configmap with the proposed and return if they are equal''' + return not Utils.check_def_equal(self.inc_configmap, self.configmap, debug=self.verbose) + + @staticmethod + # pylint: disable=too-many-return-statements,too-many-branches + # TODO: This function should be refactored into its individual parts. + def run_ansible(params, check_mode): + '''run the ansible idempotent code''' + + oc_cm = OCConfigMap(params['name'], + params['from_file'], + params['from_literal'], + params['state'], + params['namespace'], + kubeconfig=params['kubeconfig'], + verbose=params['debug']) + + state = params['state'] + + api_rval = oc_cm.get() + + if 'failed' in api_rval: + return {'failed': True, 'msg': api_rval} + + ##### + # Get + ##### + if state == 'list': + return {'changed': False, 'results': api_rval, 'state': state} + + ######## + # Delete + ######## + if state == 'absent': + if not Utils.exists(api_rval['results'], params['name']): + return {'changed': False, 'state': 'absent'} + + if check_mode: + return {'changed': True, 'msg': 'CHECK_MODE: Would have performed a delete.'} + + api_rval = oc_cm.delete() + + if api_rval['returncode'] != 0: + return {'failed': True, 'msg': api_rval} + + return {'changed': True, 'results': api_rval, 'state': state} + + ######## + # Create + ######## + if state == 'present': + if not Utils.exists(api_rval['results'], params['name']): + + if check_mode: + return {'changed': True, 'msg': 'Would have performed a create.'} + + api_rval = oc_cm.create() + + if api_rval['returncode'] != 0: + return {'failed': True, 'msg': api_rval} + + api_rval = oc_cm.get() + + if api_rval['returncode'] != 0: + return {'failed': True, 'msg': api_rval} + + return {'changed': True, 'results': api_rval, 'state': state} + + ######## + # Update + ######## + if oc_cm.needs_update(): + + api_rval = oc_cm.update() + + if api_rval['returncode'] != 0: + return {'failed': True, 'msg': api_rval} + + api_rval = oc_cm.get() + + if api_rval['returncode'] != 0: + return {'failed': True, 'msg': api_rval} + + return {'changed': True, 'results': api_rval, 'state': state} + + return {'changed': False, 'results': api_rval, 'state': state} + + return {'failed': True, 'msg': 'Unknown state passed. {}'.format(state)} diff --git a/roles/lib_openshift/src/class/oc_image.py b/roles/lib_openshift/src/class/oc_image.py new file mode 100644 index 000000000..d25349127 --- /dev/null +++ b/roles/lib_openshift/src/class/oc_image.py @@ -0,0 +1,91 @@ +# pylint: skip-file +# flake8: noqa + + +# pylint: disable=too-many-arguments +class OCImage(OpenShiftCLI): + ''' Class to import and create an imagestream object''' + def __init__(self, + namespace, + registry_url, + image_name, + image_tag, + kubeconfig='/etc/origin/master/admin.kubeconfig', + verbose=False): + ''' Constructor for OCImage''' + super(OCImage, self).__init__(namespace, kubeconfig) + self.registry_url = registry_url + self.image_name = image_name + self.image_tag = image_tag + self.verbose = verbose + + def get(self): + '''return a image by name ''' + results = self._get('imagestream', self.image_name) + results['exists'] = False + if results['returncode'] == 0 and results['results'][0]: + results['exists'] = True + + if results['returncode'] != 0 and '"{}" not found'.format(self.image_name) in results['stderr']: + results['returncode'] = 0 + + return results + + def create(self, url=None, name=None, tag=None): + '''Create an image ''' + return self._import_image(url, name, tag) + + + # pylint: disable=too-many-return-statements + @staticmethod + def run_ansible(params, check_mode): + ''' run the ansible idempotent code ''' + + ocimage = OCImage(params['namespace'], + params['registry_url'], + params['image_name'], + params['image_tag'], + kubeconfig=params['kubeconfig'], + verbose=params['debug']) + + state = params['state'] + + api_rval = ocimage.get() + + ##### + # Get + ##### + if state == 'list': + if api_rval['returncode'] != 0: + return {"failed": True, "msg": api_rval} + return {"changed": False, "results": api_rval, "state": "list"} + + ######## + # Create + ######## + if state == 'present': + + if not Utils.exists(api_rval['results'], params['image_name']): + + if check_mode: + return {"changed": False, "msg": 'CHECK_MODE: Would have performed a create'} + + api_rval = ocimage.create(params['registry_url'], + params['image_name'], + params['image_tag']) + + if api_rval['returncode'] != 0: + return {"failed": True, "msg": api_rval} + + # return the newly created object + api_rval = ocimage.get() + + if api_rval['returncode'] != 0: + return {"failed": True, "msg": api_rval} + + return {"changed": True, "results": api_rval, "state": "present"} + + # image exists, no change + return {"changed": False, "results": api_rval, "state": "present"} + + return {"failed": True, "changed": False, "msg": "Unknown state passed. {0}".format(state)} diff --git a/roles/lib_openshift/src/class/oc_user.py b/roles/lib_openshift/src/class/oc_user.py new file mode 100644 index 000000000..d9e4eac13 --- /dev/null +++ b/roles/lib_openshift/src/class/oc_user.py @@ -0,0 +1,227 @@ +# pylint: skip-file +# flake8: noqa + +# pylint: disable=too-many-instance-attributes +class OCUser(OpenShiftCLI): + ''' Class to wrap the oc command line tools ''' + kind = 'users' + + def __init__(self, + config, + groups=None, + verbose=False): + ''' Constructor for OCUser ''' + # namespace has no meaning for user operations, hardcode to 'default' + super(OCUser, self).__init__('default', config.kubeconfig) + self.config = config + self.groups = groups + self._user = None + + @property + def user(self): + ''' property function user''' + if not self._user: + self.get() + return self._user + + @user.setter + def user(self, data): + ''' setter function for user ''' + self._user = data + + def exists(self): + ''' return whether a user exists ''' + if self.user: + return True + + return False + + def get(self): + ''' return user information ''' + result = self._get(self.kind, self.config.username) + if result['returncode'] == 0: + self.user = User(content=result['results'][0]) + elif 'users \"%s\" not found' % self.config.username in result['stderr']: + result['returncode'] = 0 + result['results'] = [{}] + + return result + + def delete(self): + ''' delete the object ''' + return self._delete(self.kind, self.config.username) + + def create_group_entries(self): + ''' make entries for user to the provided group list ''' + if self.groups != None: + for group in self.groups: + cmd = ['groups', 'add-users', group, self.config.username] + rval = self.openshift_cmd(cmd, oadm=True) + if rval['returncode'] != 0: + return rval + + return rval + + return {'returncode': 0} + + def create(self): + ''' create the object ''' + rval = self.create_group_entries() + if rval['returncode'] != 0: + return rval + + return self._create_from_content(self.config.username, self.config.data) + + def group_update(self): + ''' update group membership ''' + rval = {'returncode': 0} + cmd = ['get', 'groups', '-o', 'json'] + all_groups = self.openshift_cmd(cmd, output=True) + + # pylint misindentifying all_groups['results']['items'] type + # pylint: disable=invalid-sequence-index + for group in all_groups['results']['items']: + # If we're supposed to be in this group + if group['metadata']['name'] in self.groups \ + and (group['users'] is None or self.config.username not in group['users']): + cmd = ['groups', 'add-users', group['metadata']['name'], + self.config.username] + rval = self.openshift_cmd(cmd, oadm=True) + if rval['returncode'] != 0: + return rval + # else if we're in the group, but aren't supposed to be + elif group['users'] != None and self.config.username in group['users'] \ + and group['metadata']['name'] not in self.groups: + cmd = ['groups', 'remove-users', group['metadata']['name'], + self.config.username] + rval = self.openshift_cmd(cmd, oadm=True) + if rval['returncode'] != 0: + return rval + + return rval + + def update(self): + ''' update the object ''' + rval = self.group_update() + if rval['returncode'] != 0: + return rval + + # need to update the user's info + return self._replace_content(self.kind, self.config.username, self.config.data, force=True) + + def needs_group_update(self): + ''' check if there are group membership changes ''' + cmd = ['get', 'groups', '-o', 'json'] + all_groups = self.openshift_cmd(cmd, output=True) + + # pylint misindentifying all_groups['results']['items'] type + # pylint: disable=invalid-sequence-index + for group in all_groups['results']['items']: + # If we're supposed to be in this group + if group['metadata']['name'] in self.groups \ + and (group['users'] is None or self.config.username not in group['users']): + return True + # else if we're in the group, but aren't supposed to be + elif group['users'] != None and self.config.username in group['users'] \ + and group['metadata']['name'] not in self.groups: + return True + + return False + + def needs_update(self): + ''' verify an update is needed ''' + skip = [] + if self.needs_group_update(): + return True + + return not Utils.check_def_equal(self.config.data, self.user.yaml_dict, skip_keys=skip, debug=True) + + # pylint: disable=too-many-return-statements + @staticmethod + def run_ansible(params, check_mode=False): + ''' run the idempotent ansible code + + params comes from the ansible portion of this module + check_mode: does the module support check mode. (module.check_mode) + ''' + + uconfig = UserConfig(params['kubeconfig'], + params['username'], + params['full_name'], + ) + + oc_user = OCUser(uconfig, params['groups'], + verbose=params['debug']) + state = params['state'] + + api_rval = oc_user.get() + + ##### + # Get + ##### + if state == 'list': + return {'changed': False, 'results': api_rval['results'], 'state': "list"} + + ######## + # Delete + ######## + if state == 'absent': + if oc_user.exists(): + + if check_mode: + return {'changed': False, 'msg': 'Would have performed a delete.'} + + api_rval = oc_user.delete() + + return {'changed': True, 'results': api_rval, 'state': "absent"} + return {'changed': False, 'state': "absent"} + + if state == 'present': + ######## + # Create + ######## + if not oc_user.exists(): + + if check_mode: + return {'changed': False, 'msg': 'Would have performed a create.'} + + # Create it here + api_rval = oc_user.create() + + if api_rval['returncode'] != 0: + return {'failed': True, 'msg': api_rval} + + # return the created object + api_rval = oc_user.get() + + if api_rval['returncode'] != 0: + return {'failed': True, 'msg': api_rval} + + return {'changed': True, 'results': api_rval, 'state': "present"} + + ######## + # Update + ######## + if oc_user.needs_update(): + api_rval = oc_user.update() + + if api_rval['returncode'] != 0: + return {'failed': True, 'msg': api_rval} + + orig_cmd = api_rval['cmd'] + # return the created object + api_rval = oc_user.get() + # overwrite the get/list cmd + api_rval['cmd'] = orig_cmd + + if api_rval['returncode'] != 0: + return {'failed': True, 'msg': api_rval} + + return {'changed': True, 'results': api_rval, 'state': "present"} + + return {'changed': False, 'results': api_rval, 'state': "present"} + + return {'failed': True, + 'changed': False, + 'results': 'Unknown state passed. %s' % state, + 'state': "unknown"} diff --git a/roles/lib_openshift/src/class/oc_volume.py b/roles/lib_openshift/src/class/oc_volume.py index 5211a1afd..45b58a516 100644 --- a/roles/lib_openshift/src/class/oc_volume.py +++ b/roles/lib_openshift/src/class/oc_volume.py @@ -157,7 +157,7 @@ class OCVolume(OpenShiftCLI): if not oc_volume.exists(): if check_mode: - exit_json(changed=False, msg='Would have performed a create.') + return {'changed': True, 'msg': 'CHECK_MODE: Would have performed a create.'} # Create it here api_rval = oc_volume.put() diff --git a/roles/lib_openshift/src/doc/ca_server_cert b/roles/lib_openshift/src/doc/ca_server_cert index ff9229281..7f2be4ada 100644 --- a/roles/lib_openshift/src/doc/ca_server_cert +++ b/roles/lib_openshift/src/doc/ca_server_cert @@ -79,6 +79,12 @@ options: required: false default: True aliases: [] + expire_days: + description + - Validity of the certificate in days + required: false + default: None + aliases: [] author: - "Kenny Woodson <kwoodson@redhat.com>" extends_documentation_fragment: [] diff --git a/roles/lib_openshift/src/doc/clusterrole b/roles/lib_openshift/src/doc/clusterrole new file mode 100644 index 000000000..3d14a2dfb --- /dev/null +++ b/roles/lib_openshift/src/doc/clusterrole @@ -0,0 +1,66 @@ +# flake8: noqa +# pylint: skip-file + +DOCUMENTATION = ''' +--- +module: oc_clusterrole +short_description: Modify, and idempotently manage openshift clusterroles +description: + - Manage openshift clusterroles +options: + state: + description: + - Supported states, present, absent, list + - present - will ensure object is created or updated to the value specified + - list - will return a clusterrole + - absent - will remove a clusterrole + required: False + default: present + choices: ["present", 'absent', 'list'] + aliases: [] + kubeconfig: + description: + - The path for the kubeconfig file to use for authentication + required: false + default: /etc/origin/master/admin.kubeconfig + aliases: [] + debug: + description: + - Turn on debug output. + required: false + default: False + aliases: [] + name: + description: + - Name of the object that is being queried. + required: false + default: None + aliases: [] + rules: + description: + - A list of dictionaries that have the rule parameters. + - e.g. rules=[{'apiGroups': [""], 'attributeRestrictions': None, 'verbs': ['get'], 'resources': []}] + required: false + default: None + aliases: [] +author: +- "Kenny Woodson <kwoodson@redhat.com>" +extends_documentation_fragment: [] +''' + +EXAMPLES = ''' +- name: query a list of env vars on dc + oc_clusterrole: + name: myclusterrole + state: list + +- name: Set the following variables. + oc_clusterrole: + name: myclusterrole + rules: + apiGroups: + - "" + attributeRestrictions: null + verbs: [] + resources: [] +''' diff --git a/roles/lib_openshift/src/doc/configmap b/roles/lib_openshift/src/doc/configmap new file mode 100644 index 000000000..5ca8292c4 --- /dev/null +++ b/roles/lib_openshift/src/doc/configmap @@ -0,0 +1,72 @@ +# flake8: noqa +# pylint: skip-file + +DOCUMENTATION = ''' +--- +module: oc_configmap +short_description: Modify, and idempotently manage openshift configmaps +description: + - Modify openshift configmaps programmatically. +options: + state: + description: + - Supported states, present, absent, list + - present - will ensure object is created or updated to the value specified + - list - will return a configmap + - absent - will remove the configmap + required: False + default: present + choices: ["present", 'absent', 'list'] + aliases: [] + kubeconfig: + description: + - The path for the kubeconfig file to use for authentication + required: false + default: /etc/origin/master/admin.kubeconfig + aliases: [] + debug: + description: + - Turn on debug output. + required: false + default: False + aliases: [] + name: + description: + - Name of the object that is being queried. + required: True + default: None + aliases: [] + namespace: + description: + - The namespace where the object lives. + required: false + default: default + aliases: [] + from_file: + description: + - A dict of key, value pairs representing the configmap key and the value represents the file path. + required: false + default: None + aliases: [] + from_literal: + description: + - A dict of key, value pairs representing the configmap key and the value represents the string content + required: false + default: None + aliases: [] +author: +- "kenny woodson <kwoodson@redhat.com>" +extends_documentation_fragment: [] +''' + +EXAMPLES = ''' +- name: create group + oc_configmap: + state: present + name: testmap + from_file: + secret: /path/to/secret + from_literal: + title: systemadmin + register: configout +''' diff --git a/roles/lib_openshift/src/doc/image b/roles/lib_openshift/src/doc/image new file mode 100644 index 000000000..18cf4e168 --- /dev/null +++ b/roles/lib_openshift/src/doc/image @@ -0,0 +1,75 @@ +# flake8: noqa +# pylint: skip-file + +DOCUMENTATION = ''' +--- +module: oc_image +short_description: Create, modify, and idempotently manage openshift labels. +description: + - Modify openshift labels programmatically. +options: + state: + description: + - State controls the action that will be taken with resource + - 'present' will create. Does _not_ support update. + - 'list' will read the labels + default: present + choices: ["present", "list"] + aliases: [] + kubeconfig: + description: + - The path for the kubeconfig file to use for authentication + required: false + default: /etc/origin/master/admin.kubeconfig + aliases: [] + namespace: + description: + - The namespace where this object lives + required: false + default: default + aliases: [] + debug: + description: + - Turn on debug output. + required: false + default: False + aliases: [] + registry_url: + description: + - The url for the registry so that openshift can pull the image + required: false + default: None + aliases: [] + image_name: + description: + - The name of the image being imported + required: false + default: False + aliases: [] + image_tag: + description: + - The tag of the image being imported + required: false + default: None + aliases: [] +author: +- "Ivan Horvath<ihorvath@redhat.com>" +extends_documentation_fragment: [] +''' + +EXAMPLES = ''' +- name: Get an imagestream + oc_image: + name: php55 + state: list + register: imageout + +- name: create an imagestream + oc_image: + state: present + image_name: php55 + image_tag: int + registry_url: registry.example.com + namespace: default + register: imageout +''' diff --git a/roles/lib_openshift/src/doc/user b/roles/lib_openshift/src/doc/user new file mode 100644 index 000000000..65ee01eb7 --- /dev/null +++ b/roles/lib_openshift/src/doc/user @@ -0,0 +1,128 @@ +# flake8: noqa +# pylint: skip-file + +DOCUMENTATION = ''' +--- +module: oc_user +short_description: Create, modify, and idempotently manage openshift users. +description: + - Modify openshift users programmatically. +options: + state: + description: + - State controls the action that will be taken with resource + - 'present' will create or update a user to the desired state + - 'absent' will ensure user is removed + - 'list' will read and return a list of users + default: present + choices: ["present", "absent", "list"] + aliases: [] + kubeconfig: + description: + - The path for the kubeconfig file to use for authentication + required: false + default: /etc/origin/master/admin.kubeconfig + aliases: [] + debug: + description: + - Turn on debug output. + required: false + default: False + aliases: [] + username: + description: + - Short username to query/modify. + required: false + default: None + aliases: [] + full_name: + description: + - String with the full name/description of the user. + required: false + default: None + aliases: [] + groups: + description: + - List of groups the user should be a member of. This does not add/update the legacy 'groups' field in the OpenShift user object, but makes user entries into the appropriate OpenShift group object for the given user. + required: false + default: [] + aliases: [] +author: +- "Joel Diaz <jdiaz@redhat.com>" +extends_documentation_fragment: [] +''' + +EXAMPLES = ''' +- name: Ensure user exists + oc_user: + state: present + username: johndoe + full_name "John Doe" + groups: + - dedicated-admins + register: user_johndoe + +user_johndoe variable will have contents like: +ok: [ded-int-aws-master-61034] => { + "user_johndoe": { + "changed": true, + "results": { + "cmd": "oc -n default get users johndoe -o json", + "results": [ + { + "apiVersion": "v1", + "fullName": "John DOe", + "groups": null, + "identities": null, + "kind": "User", + "metadata": { + "creationTimestamp": "2017-02-28T15:09:21Z", + "name": "johndoe", + "resourceVersion": "848781", + "selfLink": "/oapi/v1/users/johndoe", + "uid": "e23d3300-fdc7-11e6-9e3e-12822d6b7656" + } + } + ], + "returncode": 0 + }, + "state": "present" + } +} +'groups' is empty because this field is the OpenShift user object's 'group' field. + +- name: Ensure user does not exist + oc_user: + state: absent + username: johndoe + +- name: List user's info + oc_user: + state: list + username: johndoe + register: user_johndoe + +user_johndoe will have contents similar to: +ok: [ded-int-aws-master-61034] => { + "user_johndoe": { + "changed": false, + "results": [ + { + "apiVersion": "v1", + "fullName": "John Doe", + "groups": null, + "identities": null, + "kind": "User", + "metadata": { + "creationTimestamp": "2017-02-28T15:04:44Z", + "name": "johndoe", + "resourceVersion": "848280", + "selfLink": "/oapi/v1/users/johndoe", + "uid": "3d479ad2-fdc7-11e6-9e3e-12822d6b7656" + } + } + ], + "state": "list" + } +} +''' diff --git a/roles/lib_openshift/src/lib/clusterrole.py b/roles/lib_openshift/src/lib/clusterrole.py new file mode 100644 index 000000000..93ffababf --- /dev/null +++ b/roles/lib_openshift/src/lib/clusterrole.py @@ -0,0 +1,68 @@ +# pylint: skip-file +# flake8: noqa + + +# pylint: disable=too-many-public-methods +class ClusterRole(Yedit): + ''' Class to model an openshift ClusterRole''' + rules_path = "rules" + + def __init__(self, name=None, content=None): + ''' Constructor for clusterrole ''' + if content is None: + content = ClusterRole.builder(name).yaml_dict + + super(ClusterRole, self).__init__(content=content) + + self.__rules = Rule.parse_rules(self.get(ClusterRole.rules_path)) or [] + + @property + def rules(self): + return self.__rules + + @rules.setter + def rules(self, data): + self.__rules = data + self.put(ClusterRole.rules_path, self.__rules) + + def rule_exists(self, inc_rule): + '''attempt to find the inc_rule in the rules list''' + for rule in self.rules: + if rule == inc_rule: + return True + + return False + + def compare(self, other, verbose=False): + '''compare function for clusterrole''' + for rule in other.rules: + if rule not in self.rules: + if verbose: + print('Rule in other not found in self. [{}]'.format(rule)) + return False + + for rule in self.rules: + if rule not in other.rules: + if verbose: + print('Rule in self not found in other. [{}]'.format(rule)) + return False + + return True + + @staticmethod + def builder(name='default_clusterrole', rules=None): + '''return a clusterrole with name and/or rules''' + if rules is None: + rules = [{'apiGroups': [""], + 'attributeRestrictions': None, + 'verbs': [], + 'resources': []}] + content = { + 'apiVersion': 'v1', + 'kind': 'ClusterRole', + 'metadata': {'name': '{}'.format(name)}, + 'rules': rules, + } + + return ClusterRole(content=content) + diff --git a/roles/lib_openshift/src/lib/rule.py b/roles/lib_openshift/src/lib/rule.py new file mode 100644 index 000000000..4590dcf90 --- /dev/null +++ b/roles/lib_openshift/src/lib/rule.py @@ -0,0 +1,144 @@ +# pylint: skip-file +# flake8: noqa + + +class Rule(object): + '''class to represent a clusterrole rule + + Example Rule Object's yaml: + - apiGroups: + - "" + attributeRestrictions: null + resources: + - persistentvolumes + verbs: + - create + - delete + - deletecollection + - get + - list + - patch + - update + - watch + + ''' + def __init__(self, + api_groups=None, + attr_restrictions=None, + resources=None, + verbs=None): + self.__api_groups = api_groups if api_groups is not None else [""] + self.__verbs = verbs if verbs is not None else [] + self.__resources = resources if resources is not None else [] + self.__attribute_restrictions = attr_restrictions if attr_restrictions is not None else None + + @property + def verbs(self): + '''property for verbs''' + if self.__verbs is None: + return [] + + return self.__verbs + + @verbs.setter + def verbs(self, data): + '''setter for verbs''' + self.__verbs = data + + @property + def api_groups(self): + '''property for api_groups''' + if self.__api_groups is None: + return [] + return self.__api_groups + + @api_groups.setter + def api_groups(self, data): + '''setter for api_groups''' + self.__api_groups = data + + @property + def resources(self): + '''property for resources''' + if self.__resources is None: + return [] + + return self.__resources + + @resources.setter + def resources(self, data): + '''setter for resources''' + self.__resources = data + + @property + def attribute_restrictions(self): + '''property for attribute_restrictions''' + return self.__attribute_restrictions + + @attribute_restrictions.setter + def attribute_restrictions(self, data): + '''setter for attribute_restrictions''' + self.__attribute_restrictions = data + + def add_verb(self, inc_verb): + '''add a verb to the verbs array''' + self.verbs.append(inc_verb) + + def add_api_group(self, inc_apigroup): + '''add an api_group to the api_groups array''' + self.api_groups.append(inc_apigroup) + + def add_resource(self, inc_resource): + '''add an resource to the resources array''' + self.resources.append(inc_resource) + + def remove_verb(self, inc_verb): + '''add a verb to the verbs array''' + try: + self.verbs.remove(inc_verb) + return True + except ValueError: + pass + + return False + + def remove_api_group(self, inc_api_group): + '''add a verb to the verbs array''' + try: + self.api_groups.remove(inc_api_group) + return True + except ValueError: + pass + + return False + + def remove_resource(self, inc_resource): + '''add a verb to the verbs array''' + try: + self.resources.remove(inc_resource) + return True + except ValueError: + pass + + return False + + def __eq__(self, other): + '''return whether rules are equal''' + return (self.attribute_restrictions == other.attribute_restrictions and + self.api_groups == other.api_groups and + self.resources == other.resources and + self.verbs == other.verbs) + + + @staticmethod + def parse_rules(inc_rules): + '''create rules from an array''' + + results = [] + for rule in inc_rules: + results.append(Rule(rule['apiGroups'], + rule['attributeRestrictions'], + rule['resources'], + rule['verbs'])) + + return results diff --git a/roles/lib_openshift/src/lib/user.py b/roles/lib_openshift/src/lib/user.py new file mode 100644 index 000000000..a14d5fc91 --- /dev/null +++ b/roles/lib_openshift/src/lib/user.py @@ -0,0 +1,37 @@ +# pylint: skip-file +# flake8: noqa + + +class UserConfig(object): + ''' Handle user options ''' + def __init__(self, + kubeconfig, + username, + full_name): + ''' constructor for handling user options ''' + self.kubeconfig = kubeconfig + self.username = username + self.full_name = full_name + + self.data = {} + self.create_dict() + + def create_dict(self): + ''' return a user as a dict ''' + self.data['apiVersion'] = 'v1' + self.data['fullName'] = self.full_name + self.data['groups'] = None + self.data['identities'] = None + self.data['kind'] = 'User' + self.data['metadata'] = {} + self.data['metadata']['name'] = self.username + + +# pylint: disable=too-many-instance-attributes +class User(Yedit): + ''' Class to wrap the oc command line tools ''' + kind = 'user' + + def __init__(self, content): + '''User constructor''' + super(User, self).__init__(content=content) diff --git a/roles/lib_openshift/src/sources.yml b/roles/lib_openshift/src/sources.yml index 0dba6016b..9fa2a6c0e 100644 --- a/roles/lib_openshift/src/sources.yml +++ b/roles/lib_openshift/src/sources.yml @@ -79,6 +79,28 @@ oc_atomic_container.py: - doc/atomic_container - ansible/oc_atomic_container.py +oc_configmap.py: +- doc/generated +- doc/license +- lib/import.py +- doc/configmap +- ../../lib_utils/src/class/yedit.py +- lib/base.py +- class/oc_configmap.py +- ansible/oc_configmap.py + +oc_clusterrole.py: +- doc/generated +- doc/license +- lib/import.py +- doc/clusterrole +- ../../lib_utils/src/class/yedit.py +- lib/base.py +- lib/rule.py +- lib/clusterrole.py +- class/oc_clusterrole.py +- ansible/oc_clusterrole.py + oc_edit.py: - doc/generated - doc/license @@ -100,6 +122,7 @@ oc_env.py: - class/oc_env.py - ansible/oc_env.py + oc_group.py: - doc/generated - doc/license @@ -111,6 +134,16 @@ oc_group.py: - class/oc_group.py - ansible/oc_group.py +oc_image.py: +- doc/generated +- doc/license +- lib/import.py +- doc/image +- ../../lib_utils/src/class/yedit.py +- lib/base.py +- class/oc_image.py +- ansible/oc_image.py + oc_label.py: - doc/generated - doc/license @@ -230,6 +263,17 @@ oc_service.py: - class/oc_service.py - ansible/oc_service.py +oc_user.py: +- doc/generated +- doc/license +- lib/import.py +- doc/user +- ../../lib_utils/src/class/yedit.py +- lib/base.py +- lib/user.py +- class/oc_user.py +- ansible/oc_user.py + oc_version.py: - doc/generated - doc/license diff --git a/roles/lib_openshift/src/test/integration/oc_clusterrole.yml b/roles/lib_openshift/src/test/integration/oc_clusterrole.yml new file mode 100755 index 000000000..91b143f55 --- /dev/null +++ b/roles/lib_openshift/src/test/integration/oc_clusterrole.yml @@ -0,0 +1,106 @@ +#!/usr/bin/ansible-playbook --module-path=../../../library/ +## ./oc_configmap.yml -M ../../../library -e "cli_master_test=$OPENSHIFT_MASTER +--- +- hosts: "{{ cli_master_test }}" + gather_facts: no + user: root + + post_tasks: + - name: create a test project + oc_project: + name: test + description: for tests only + + ###### create test ########### + - name: create a clusterrole + oc_clusterrole: + state: present + name: operations + rules: + - apiGroups: + - "" + resources: + - persistentvolumes + attributeRestrictions: null + verbs: + - create + - delete + - deletecollection + - get + - list + - patch + - update + - watch + + - name: fetch the created clusterrole + oc_clusterrole: + name: operations + state: list + register: croleout + + - debug: var=croleout + + - name: assert clusterrole exists + assert: + that: + - croleout.results.results.metadata.name == 'operations' + - croleout.results.results.rules[0].resources[0] == 'persistentvolumes' + ###### end create test ########### + + ###### update test ########### + - name: update a clusterrole + oc_clusterrole: + state: present + name: operations + rules: + - apiGroups: + - "" + resources: + - persistentvolumes + - serviceaccounts + - services + attributeRestrictions: null + verbs: + - create + - delete + - deletecollection + - get + - list + - patch + - update + - watch + + - name: fetch the created clusterrole + oc_clusterrole: + name: operations + state: list + register: croleout + + - debug: var=croleout + + - name: assert clusterrole is updated + assert: + that: + - croleout.results.results.metadata.name == 'operations' + - "'persistentvolumes' in croleout.results.results.rules[0].resources" + - "'serviceaccounts' in croleout.results.results.rules[0].resources" + - "'services' in croleout.results.results.rules[0].resources" + ###### end create test ########### + + ###### delete test ########### + - name: delete a clusterrole + oc_clusterrole: + state: absent + name: operations + + - name: fetch the clusterrole + oc_clusterrole: + name: operations + state: list + register: croleout + + - debug: var=croleout + + - name: assert operations does not exist + assert: + that: "'\"operations\" not found' in croleout.results.stderr" diff --git a/roles/lib_openshift/src/test/integration/oc_configmap.yml b/roles/lib_openshift/src/test/integration/oc_configmap.yml new file mode 100755 index 000000000..c0d200e73 --- /dev/null +++ b/roles/lib_openshift/src/test/integration/oc_configmap.yml @@ -0,0 +1,95 @@ +#!/usr/bin/ansible-playbook --module-path=../../../library/ +## ./oc_configmap.yml -M ../../../library -e "cli_master_test=$OPENSHIFT_MASTER +--- +- hosts: "{{ cli_master_test }}" + gather_facts: no + user: root + vars: + filename: /tmp/test_configmap_from_file + + post_tasks: + - name: Setup a file with known contents + copy: + content: This is a file + dest: "{{ filename }}" + + - name: create a test project + oc_project: + name: test + description: for tests only + + ###### create test ########### + - name: create a configmap + oc_configmap: + state: present + name: configmaptest + namespace: test + from_file: + config: "{{ filename }}" + from_literal: + foo: bar + + - name: fetch the created configmap + oc_configmap: + name: configmaptest + state: list + namespace: test + register: cmout + + - debug: var=cmout + + - name: assert configmaptest exists + assert: + that: + - cmout.results.results[0].metadata.name == 'configmaptest' + - cmout.results.results[0].data.foo == 'bar' + ###### end create test ########### + + ###### update test ########### + - name: create a configmap + oc_configmap: + state: present + name: configmaptest + namespace: test + from_file: + config: "{{ filename }}" + from_literal: + foo: notbar + deployment_type: online + + - name: fetch the updated configmap + oc_configmap: + name: configmaptest + state: list + namespace: test + register: cmout + + - debug: var=cmout + + - name: assert configmaptest exists + assert: + that: + - cmout.results.results[0].metadata.name == 'configmaptest' + - cmout.results.results[0].data.deployment_type == 'online' + - cmout.results.results[0].data.foo == 'notbar' + ###### end update test ########### + + ###### delete test ########### + - name: delete a configmap + oc_configmap: + state: absent + name: configmaptest + namespace: test + + - name: fetch the updated configmap + oc_configmap: + name: configmaptest + state: list + namespace: test + register: cmout + + - debug: var=cmout + + - name: assert configmaptest exists + assert: + that: "'\"configmaptest\" not found' in cmout.results.stderr" diff --git a/roles/lib_openshift/src/test/integration/oc_user.yml b/roles/lib_openshift/src/test/integration/oc_user.yml new file mode 100755 index 000000000..ad1f9d188 --- /dev/null +++ b/roles/lib_openshift/src/test/integration/oc_user.yml @@ -0,0 +1,240 @@ +#!/usr/bin/ansible-playbook --module-path=../../../library/ +# +# ./oc_user.yml -e "cli_master_test=$OPENSHIFT_MASTER +# +--- +- hosts: "{{ cli_master_test }}" + gather_facts: no + user: root + + vars: + test_user: testuser@email.com + test_user_fullname: "Test User" + pre_tasks: + - name: ensure needed vars are defined + fail: + msg: "{{ item }} no defined" + when: "{{ item}} is not defined" + with_items: + - cli_master_test # ansible inventory instance to run playbook against + + tasks: + - name: delete test user (so future tests work) + oc_user: + state: absent + username: "{{ test_user }}" + + - name: get user list + oc_user: + state: list + username: "{{ test_user }}" + register: user_out + - name: "assert test user does not exist" + assert: + that: user_out['results'][0] == {} + msg: "{{ user_out }}" + + - name: get all list + oc_user: + state: list + register: user_out + #- debug: var=user_out + + - name: add test user + oc_user: + state: present + username: "{{ test_user }}" + full_name: "{{ test_user_fullname }}" + register: user_out + - name: assert result set to changed + assert: + that: user_out['changed'] == True + msg: "{{ user_out }}" + + - name: check test user actually added + oc_user: + state: list + username: "{{ test_user }}" + register: user_out + - name: assert user actually added + assert: + that: user_out['results'][0]['metadata']['name'] == "{{ test_user }}" and + user_out['results'][0]['fullName'] == "{{ test_user_fullname }}" + msg: "{{ user_out }}" + + - name: re-add test user + oc_user: + state: present + username: "{{ test_user }}" + full_name: "{{ test_user_fullname }}" + register: user_out + - name: assert re-add result set to not changed + assert: + that: user_out['changed'] == False + msg: "{{ user_out }}" + + - name: modify existing user + oc_user: + state: present + username: "{{ test_user }}" + full_name: 'Something Different' + register: user_out + - name: assert modify existing user result set to changed + assert: + that: user_out['changed'] == True + msg: "{{ user_out }}" + + - name: check modify test user + oc_user: + state: list + username: "{{ test_user }}" + register: user_out + - name: assert modification successful + assert: + that: user_out['results'][0]['metadata']['name'] == "{{ test_user }}" and + user_out['results'][0]['fullName'] == 'Something Different' + msg: "{{ user_out }}" + + - name: delete test user + oc_user: + state: absent + username: "{{ test_user }}" + register: user_out + - name: assert delete marked changed + assert: + that: user_out['changed'] == True + msg: "{{ user_out }}" + + - name: check delete user + oc_user: + state: list + username: "{{ test_user }}" + register: user_out + - name: assert deletion successful + assert: + that: user_out['results'][0] == {} + msg: "{{ user_out }}" + + - name: re-delete test user + oc_user: + state: absent + username: "{{ test_user }}" + register: user_out + - name: check re-delete marked not changed + assert: + that: user_out['changed'] == False + msg: "{{ user_out }}" + + - name: delete test group + oc_obj: + kind: group + state: absent + name: integration-test-group + + - name: create test group + command: oadm groups new integration-test-group + + - name: check group creation + oc_obj: + kind: group + state: list + name: integration-test-group + register: user_out + - name: assert test group created + assert: + that: user_out['results']['results'][0]['metadata']['name'] == "integration-test-group" + msg: "{{ user_out }}" + + - name: create user with group membership + oc_user: + state: present + username: "{{ test_user }}" + groups: + - "integration-test-group" + register: user_out + - debug: var=user_out + - name: get group user members + oc_obj: + kind: group + state: list + name: integration-test-group + register: user_out + - name: assert user group membership + assert: + that: "'{{ test_user }}' in user_out['results']['results'][0]['users'][0]" + msg: "{{ user_out }}" + + - name: delete second test group + oc_obj: + kind: group + state: absent + name: integration-test-group2 + + - name: create empty second group + command: oadm groups new integration-test-group2 + + - name: update user with second group membership + oc_user: + state: present + username: "{{ test_user }}" + groups: + - "integration-test-group" + - "integration-test-group2" + register: user_out + - name: assert adding more group changed + assert: + that: user_out['changed'] == True + + - name: get group memberships + oc_obj: + kind: group + state: list + name: "{{ item }}" + with_items: + - integration-test-group + - integration-test-group2 + register: user_out + - name: assert user member of above groups + assert: + that: "'{{ test_user }}' in user_out['results'][0]['results']['results'][0]['users'] and \ + '{{ test_user }}' in user_out['results'][1]['results']['results'][0]['users']" + msg: "{{ user_out }}" + + - name: update user with only one group + oc_user: + state: present + username: "{{ test_user }}" + groups: + - "integration-test-group2" + register: user_out + - assert: + that: user_out['changed'] == True + + - name: get group memberships + oc_obj: + kind: group + state: list + name: "{{ item }}" + with_items: + - "integration-test-group" + - "integration-test-group2" + register: user_out + - debug: var=user_out + - name: assert proper user membership + assert: + that: "'{{ test_user }}' not in user_out['results'][0]['results']['results'][0]['users'] and \ + '{{ test_user }}' in user_out['results'][1]['results']['results'][0]['users']" + + - name: clean up test groups + oc_obj: + kind: group + state: absent + name: "{{ item }}" + with_items: + - "integration-test-group" + - "integration-test-group2" + + - name: clean up test user + oc_user: + state: absent + username: "{{ test_user }}" diff --git a/roles/lib_openshift/src/test/unit/test_oc_clusterrole.py b/roles/lib_openshift/src/test/unit/test_oc_clusterrole.py new file mode 100755 index 000000000..189f16bda --- /dev/null +++ b/roles/lib_openshift/src/test/unit/test_oc_clusterrole.py @@ -0,0 +1,115 @@ +''' + Unit tests for oc clusterrole +''' + +import copy +import os +import sys +import unittest +import mock + +# Removing invalid variable names for tests so that I can +# keep them brief +# pylint: disable=invalid-name,no-name-in-module +# Disable import-error b/c our libraries aren't loaded in jenkins +# pylint: disable=import-error,wrong-import-position +# place class in our python path +module_path = os.path.join('/'.join(os.path.realpath(__file__).split('/')[:-4]), 'library') # noqa: E501 +sys.path.insert(0, module_path) +from oc_clusterrole import OCClusterRole # noqa: E402 + + +class OCClusterRoleTest(unittest.TestCase): + ''' + Test class for OCClusterRole + ''' + + # run_ansible input parameters + params = { + 'state': 'present', + 'name': 'operations', + 'rules': [ + {'apiGroups': [''], + 'attributeRestrictions': None, + 'verbs': ['create', 'delete', 'deletecollection', + 'get', 'list', 'patch', 'update', 'watch'], + 'resources': ['persistentvolumes']} + ], + 'kubeconfig': '/etc/origin/master/admin.kubeconfig', + 'debug': False, + } + + @mock.patch('oc_clusterrole.locate_oc_binary') + @mock.patch('oc_clusterrole.Utils.create_tmpfile_copy') + @mock.patch('oc_clusterrole.Utils._write') + @mock.patch('oc_clusterrole.OCClusterRole._run') + def test_adding_a_clusterrole(self, mock_cmd, mock_write, mock_tmpfile_copy, mock_loc_binary): + ''' Testing adding a project ''' + + params = copy.deepcopy(OCClusterRoleTest.params) + + clusterrole = '''{ + "apiVersion": "v1", + "kind": "ClusterRole", + "metadata": { + "creationTimestamp": "2017-03-27T14:19:09Z", + "name": "operations", + "resourceVersion": "23", + "selfLink": "/oapi/v1/clusterrolesoperations", + "uid": "57d358fe-12f8-11e7-874a-0ec502977670" + }, + "rules": [ + { + "apiGroups": [ + "" + ], + "attributeRestrictions": null, + "resources": [ + "persistentvolumes" + ], + "verbs": [ + "create", + "delete", + "deletecollection", + "get", + "list", + "patch", + "update", + "watch" + ] + } + ] + }''' + + # Return values of our mocked function call. These get returned once per call. + mock_cmd.side_effect = [ + (1, '', 'Error from server: clusterrole "operations" not found'), + (1, '', 'Error from server: namespaces "operations" not found'), + (0, '', ''), # created + (0, clusterrole, ''), # fetch it + ] + + mock_tmpfile_copy.side_effect = [ + '/tmp/mocked_kubeconfig', + ] + + mock_loc_binary.side_effect = [ + 'oc', + ] + + # Act + results = OCClusterRole.run_ansible(params, False) + + # Assert + self.assertTrue(results['changed']) + self.assertEqual(results['results']['returncode'], 0) + self.assertEqual(results['results']['results']['metadata']['name'], 'operations') + self.assertEqual(results['state'], 'present') + + # Making sure our mock was called as we expected + mock_cmd.assert_has_calls([ + mock.call(['oc', 'get', 'clusterrole', 'operations', '-o', 'json'], None), + mock.call(['oc', 'get', 'clusterrole', 'operations', '-o', 'json'], None), + mock.call(['oc', 'create', '-f', mock.ANY], None), + mock.call(['oc', 'get', 'clusterrole', 'operations', '-o', 'json'], None), + ]) diff --git a/roles/lib_openshift/src/test/unit/test_oc_configmap.py b/roles/lib_openshift/src/test/unit/test_oc_configmap.py new file mode 100755 index 000000000..318fd6167 --- /dev/null +++ b/roles/lib_openshift/src/test/unit/test_oc_configmap.py @@ -0,0 +1,239 @@ +''' + Unit tests for oc configmap +''' + +import copy +import os +import six +import sys +import unittest +import mock + +# Removing invalid variable names for tests so that I can +# keep them brief +# pylint: disable=invalid-name,no-name-in-module +# Disable import-error b/c our libraries aren't loaded in jenkins +# pylint: disable=import-error,wrong-import-position +# place class in our python path +module_path = os.path.join('/'.join(os.path.realpath(__file__).split('/')[:-4]), 'library') # noqa: E501 +sys.path.insert(0, module_path) +from oc_configmap import OCConfigMap, locate_oc_binary # noqa: E402 + + +class OCConfigMapTest(unittest.TestCase): + ''' + Test class for OCConfigMap + ''' + params = {'kubeconfig': '/etc/origin/master/admin.kubeconfig', + 'state': 'present', + 'debug': False, + 'name': 'configmap', + 'from_file': {}, + 'from_literal': {}, + 'namespace': 'test'} + + @mock.patch('oc_configmap.Utils._write') + @mock.patch('oc_configmap.Utils.create_tmpfile_copy') + @mock.patch('oc_configmap.OCConfigMap._run') + def test_create_configmap(self, mock_run, mock_tmpfile_copy, mock_write): + ''' Testing a configmap create ''' + # TODO + return + params = copy.deepcopy(OCConfigMapTest.params) + params['from_file'] = {'test': '/root/file'} + params['from_literal'] = {'foo': 'bar'} + + configmap = '''{ + "apiVersion": "v1", + "data": { + "foo": "bar", + "test": "this is a file\\n" + }, + "kind": "ConfigMap", + "metadata": { + "creationTimestamp": "2017-03-20T20:24:35Z", + "name": "configmap", + "namespace": "test" + } + }''' + + mock_run.side_effect = [ + (1, '', 'Error from server (NotFound): configmaps "configmap" not found'), + (0, '', ''), + (0, configmap, ''), + ] + + mock_tmpfile_copy.side_effect = [ + '/tmp/mocked_kubeconfig', + ] + + results = OCConfigMap.run_ansible(params, False) + + self.assertTrue(results['changed']) + self.assertEqual(results['results']['results'][0]['metadata']['name'], 'configmap') + + @mock.patch('oc_configmap.Utils._write') + @mock.patch('oc_configmap.Utils.create_tmpfile_copy') + @mock.patch('oc_configmap.OCConfigMap._run') + def test_update_configmap(self, mock_run, mock_tmpfile_copy, mock_write): + ''' Testing a configmap create ''' + params = copy.deepcopy(OCConfigMapTest.params) + params['from_file'] = {'test': '/root/file'} + params['from_literal'] = {'foo': 'bar', 'deployment_type': 'online'} + + configmap = '''{ + "apiVersion": "v1", + "data": { + "foo": "bar", + "test": "this is a file\\n" + }, + "kind": "ConfigMap", + "metadata": { + "creationTimestamp": "2017-03-20T20:24:35Z", + "name": "configmap", + "namespace": "test" + + } + }''' + + mod_configmap = '''{ + "apiVersion": "v1", + "data": { + "foo": "bar", + "deployment_type": "online", + "test": "this is a file\\n" + }, + "kind": "ConfigMap", + "metadata": { + "creationTimestamp": "2017-03-20T20:24:35Z", + "name": "configmap", + "namespace": "test" + + } + }''' + + mock_run.side_effect = [ + (0, configmap, ''), + (0, mod_configmap, ''), + (0, configmap, ''), + (0, '', ''), + (0, mod_configmap, ''), + ] + + mock_tmpfile_copy.side_effect = [ + '/tmp/mocked_kubeconfig', + ] + + results = OCConfigMap.run_ansible(params, False) + + self.assertTrue(results['changed']) + self.assertEqual(results['results']['results'][0]['metadata']['name'], 'configmap') + self.assertEqual(results['results']['results'][0]['data']['deployment_type'], 'online') + + @unittest.skipIf(six.PY3, 'py2 test only') + @mock.patch('os.path.exists') + @mock.patch('os.environ.get') + def test_binary_lookup_fallback(self, mock_env_get, mock_path_exists): + ''' Testing binary lookup fallback ''' + + mock_env_get.side_effect = lambda _v, _d: '' + + mock_path_exists.side_effect = lambda _: False + + self.assertEqual(locate_oc_binary(), 'oc') + + @unittest.skipIf(six.PY3, 'py2 test only') + @mock.patch('os.path.exists') + @mock.patch('os.environ.get') + def test_binary_lookup_in_path(self, mock_env_get, mock_path_exists): + ''' Testing binary lookup in path ''' + + oc_bin = '/usr/bin/oc' + + mock_env_get.side_effect = lambda _v, _d: '/bin:/usr/bin' + + mock_path_exists.side_effect = lambda f: f == oc_bin + + self.assertEqual(locate_oc_binary(), oc_bin) + + @unittest.skipIf(six.PY3, 'py2 test only') + @mock.patch('os.path.exists') + @mock.patch('os.environ.get') + def test_binary_lookup_in_usr_local(self, mock_env_get, mock_path_exists): + ''' Testing binary lookup in /usr/local/bin ''' + + oc_bin = '/usr/local/bin/oc' + + mock_env_get.side_effect = lambda _v, _d: '/bin:/usr/bin' + + mock_path_exists.side_effect = lambda f: f == oc_bin + + self.assertEqual(locate_oc_binary(), oc_bin) + + @unittest.skipIf(six.PY3, 'py2 test only') + @mock.patch('os.path.exists') + @mock.patch('os.environ.get') + def test_binary_lookup_in_home(self, mock_env_get, mock_path_exists): + ''' Testing binary lookup in ~/bin ''' + + oc_bin = os.path.expanduser('~/bin/oc') + + mock_env_get.side_effect = lambda _v, _d: '/bin:/usr/bin' + + mock_path_exists.side_effect = lambda f: f == oc_bin + + self.assertEqual(locate_oc_binary(), oc_bin) + + @unittest.skipIf(six.PY2, 'py3 test only') + @mock.patch('shutil.which') + @mock.patch('os.environ.get') + def test_binary_lookup_fallback_py3(self, mock_env_get, mock_shutil_which): + ''' Testing binary lookup fallback ''' + + mock_env_get.side_effect = lambda _v, _d: '' + + mock_shutil_which.side_effect = lambda _f, path=None: None + + self.assertEqual(locate_oc_binary(), 'oc') + + @unittest.skipIf(six.PY2, 'py3 test only') + @mock.patch('shutil.which') + @mock.patch('os.environ.get') + def test_binary_lookup_in_path_py3(self, mock_env_get, mock_shutil_which): + ''' Testing binary lookup in path ''' + + oc_bin = '/usr/bin/oc' + + mock_env_get.side_effect = lambda _v, _d: '/bin:/usr/bin' + + mock_shutil_which.side_effect = lambda _f, path=None: oc_bin + + self.assertEqual(locate_oc_binary(), oc_bin) + + @unittest.skipIf(six.PY2, 'py3 test only') + @mock.patch('shutil.which') + @mock.patch('os.environ.get') + def test_binary_lookup_in_usr_local_py3(self, mock_env_get, mock_shutil_which): + ''' Testing binary lookup in /usr/local/bin ''' + + oc_bin = '/usr/local/bin/oc' + + mock_env_get.side_effect = lambda _v, _d: '/bin:/usr/bin' + + mock_shutil_which.side_effect = lambda _f, path=None: oc_bin + + self.assertEqual(locate_oc_binary(), oc_bin) + + @unittest.skipIf(six.PY2, 'py3 test only') + @mock.patch('shutil.which') + @mock.patch('os.environ.get') + def test_binary_lookup_in_home_py3(self, mock_env_get, mock_shutil_which): + ''' Testing binary lookup in ~/bin ''' + + oc_bin = os.path.expanduser('~/bin/oc') + + mock_env_get.side_effect = lambda _v, _d: '/bin:/usr/bin' + + mock_shutil_which.side_effect = lambda _f, path=None: oc_bin + + self.assertEqual(locate_oc_binary(), oc_bin) diff --git a/roles/lib_openshift/src/test/unit/test_oc_image.py b/roles/lib_openshift/src/test/unit/test_oc_image.py new file mode 100755 index 000000000..943c8ca17 --- /dev/null +++ b/roles/lib_openshift/src/test/unit/test_oc_image.py @@ -0,0 +1,280 @@ +''' + Unit tests for oc image +''' +import os +import sys +import unittest +import mock +import six + +# Removing invalid variable names for tests so that I can +# keep them brief +# pylint: disable=invalid-name,no-name-in-module +# Disable import-error b/c our libraries aren't loaded in jenkins +# pylint: disable=import-error +# place class in our python path +module_path = os.path.join('/'.join(os.path.realpath(__file__).split('/')[:-4]), 'library') # noqa: E501 +sys.path.insert(0, module_path) +from oc_image import OCImage, locate_oc_binary # noqa: E402 + + +class OCImageTest(unittest.TestCase): + ''' + Test class for OCImage + ''' + + @mock.patch('oc_image.Utils.create_tmpfile_copy') + @mock.patch('oc_image.OCImage._run') + def test_state_list(self, mock_cmd, mock_tmpfile_copy): + ''' Testing a label list ''' + params = {'registry_url': 'registry.ops.openshift.com', + 'image_name': 'oso-rhel7-zagg-web', + 'image_tag': 'int', + 'namespace': 'default', + 'state': 'list', + 'kubeconfig': '/etc/origin/master/admin.kubeconfig', + 'debug': False} + + istream = '''{ + "kind": "ImageStream", + "apiVersion": "v1", + "metadata": { + "name": "oso-rhel7-zagg-web", + "namespace": "default", + "selfLink": "/oapi/v1/namespaces/default/imagestreams/oso-rhel7-zagg-web", + "uid": "6ca2b199-dcdb-11e6-8ffd-0a5f8e3e32be", + "resourceVersion": "8135944", + "generation": 1, + "creationTimestamp": "2017-01-17T17:36:05Z", + "annotations": { + "openshift.io/image.dockerRepositoryCheck": "2017-01-17T17:36:05Z" + } + }, + "spec": { + "tags": [ + { + "name": "int", + "annotations": null, + "from": { + "kind": "DockerImage", + "name": "registry.ops.openshift.com/ops/oso-rhel7-zagg-web:int" + }, + "generation": 1, + "importPolicy": {} + } + ] + }, + "status": { + "dockerImageRepository": "172.30.183.164:5000/default/oso-rhel7-zagg-web", + "tags": [ + { + "tag": "int", + "items": [ + { + "created": "2017-01-17T17:36:05Z", + "dockerImageReference": "registry.ops.openshift.com/ops/oso-rhel7-zagg-web@sha256:645bab780cf18a9b764d64b02ca65c39d13cb16f19badd0a49a1668629759392", + "image": "sha256:645bab780cf18a9b764d64b02ca65c39d13cb16f19badd0a49a1668629759392", + "generation": 1 + } + ] + } + ] + } + } + ''' + + mock_cmd.side_effect = [ + (0, istream, ''), + ] + + mock_tmpfile_copy.side_effect = [ + '/tmp/mocked_kubeconfig', + ] + + results = OCImage.run_ansible(params, False) + + self.assertFalse(results['changed']) + self.assertEquals(results['results']['results'][0]['metadata']['name'], 'oso-rhel7-zagg-web') + + @mock.patch('oc_image.Utils.create_tmpfile_copy') + @mock.patch('oc_image.OCImage._run') + def test_state_present(self, mock_cmd, mock_tmpfile_copy): + ''' Testing a image present ''' + params = {'registry_url': 'registry.ops.openshift.com', + 'image_name': 'oso-rhel7-zagg-web', + 'image_tag': 'int', + 'namespace': 'default', + 'state': 'present', + 'kubeconfig': '/etc/origin/master/admin.kubeconfig', + 'debug': False} + + istream = '''{ + "kind": "ImageStream", + "apiVersion": "v1", + "metadata": { + "name": "oso-rhel7-zagg-web", + "namespace": "default", + "selfLink": "/oapi/v1/namespaces/default/imagestreams/oso-rhel7-zagg-web", + "uid": "6ca2b199-dcdb-11e6-8ffd-0a5f8e3e32be", + "resourceVersion": "8135944", + "generation": 1, + "creationTimestamp": "2017-01-17T17:36:05Z", + "annotations": { + "openshift.io/image.dockerRepositoryCheck": "2017-01-17T17:36:05Z" + } + }, + "spec": { + "tags": [ + { + "name": "int", + "annotations": null, + "from": { + "kind": "DockerImage", + "name": "registry.ops.openshift.com/ops/oso-rhel7-zagg-web:int" + }, + "generation": 1, + "importPolicy": {} + } + ] + }, + "status": { + "dockerImageRepository": "172.30.183.164:5000/default/oso-rhel7-zagg-web", + "tags": [ + { + "tag": "int", + "items": [ + { + "created": "2017-01-17T17:36:05Z", + "dockerImageReference": "registry.ops.openshift.com/ops/oso-rhel7-zagg-web@sha256:645bab780cf18a9b764d64b02ca65c39d13cb16f19badd0a49a1668629759392", + "image": "sha256:645bab780cf18a9b764d64b02ca65c39d13cb16f19badd0a49a1668629759392", + "generation": 1 + } + ] + } + ] + } + } + ''' + + mock_cmd.side_effect = [ + (1, '', 'Error from server: imagestreams "oso-rhel7-zagg-web" not found'), + (0, '', ''), + (0, istream, ''), + ] + + mock_tmpfile_copy.side_effect = [ + '/tmp/mocked_kubeconfig', + ] + + results = OCImage.run_ansible(params, False) + + self.assertTrue(results['changed']) + self.assertTrue(results['results']['results'][0]['metadata']['name'] == 'oso-rhel7-zagg-web') + + @unittest.skipIf(six.PY3, 'py2 test only') + @mock.patch('os.path.exists') + @mock.patch('os.environ.get') + def test_binary_lookup_fallback(self, mock_env_get, mock_path_exists): + ''' Testing binary lookup fallback ''' + + mock_env_get.side_effect = lambda _v, _d: '' + + mock_path_exists.side_effect = lambda _: False + + self.assertEqual(locate_oc_binary(), 'oc') + + @unittest.skipIf(six.PY3, 'py2 test only') + @mock.patch('os.path.exists') + @mock.patch('os.environ.get') + def test_binary_lookup_in_path(self, mock_env_get, mock_path_exists): + ''' Testing binary lookup in path ''' + + oc_bin = '/usr/bin/oc' + + mock_env_get.side_effect = lambda _v, _d: '/bin:/usr/bin' + + mock_path_exists.side_effect = lambda f: f == oc_bin + + self.assertEqual(locate_oc_binary(), oc_bin) + + @unittest.skipIf(six.PY3, 'py2 test only') + @mock.patch('os.path.exists') + @mock.patch('os.environ.get') + def test_binary_lookup_in_usr_local(self, mock_env_get, mock_path_exists): + ''' Testing binary lookup in /usr/local/bin ''' + + oc_bin = '/usr/local/bin/oc' + + mock_env_get.side_effect = lambda _v, _d: '/bin:/usr/bin' + + mock_path_exists.side_effect = lambda f: f == oc_bin + + self.assertEqual(locate_oc_binary(), oc_bin) + + @unittest.skipIf(six.PY3, 'py2 test only') + @mock.patch('os.path.exists') + @mock.patch('os.environ.get') + def test_binary_lookup_in_home(self, mock_env_get, mock_path_exists): + ''' Testing binary lookup in ~/bin ''' + + oc_bin = os.path.expanduser('~/bin/oc') + + mock_env_get.side_effect = lambda _v, _d: '/bin:/usr/bin' + + mock_path_exists.side_effect = lambda f: f == oc_bin + + self.assertEqual(locate_oc_binary(), oc_bin) + + @unittest.skipIf(six.PY2, 'py3 test only') + @mock.patch('shutil.which') + @mock.patch('os.environ.get') + def test_binary_lookup_fallback_py3(self, mock_env_get, mock_shutil_which): + ''' Testing binary lookup fallback ''' + + mock_env_get.side_effect = lambda _v, _d: '' + + mock_shutil_which.side_effect = lambda _f, path=None: None + + self.assertEqual(locate_oc_binary(), 'oc') + + @unittest.skipIf(six.PY2, 'py3 test only') + @mock.patch('shutil.which') + @mock.patch('os.environ.get') + def test_binary_lookup_in_path_py3(self, mock_env_get, mock_shutil_which): + ''' Testing binary lookup in path ''' + + oc_bin = '/usr/bin/oc' + + mock_env_get.side_effect = lambda _v, _d: '/bin:/usr/bin' + + mock_shutil_which.side_effect = lambda _f, path=None: oc_bin + + self.assertEqual(locate_oc_binary(), oc_bin) + + @unittest.skipIf(six.PY2, 'py3 test only') + @mock.patch('shutil.which') + @mock.patch('os.environ.get') + def test_binary_lookup_in_usr_local_py3(self, mock_env_get, mock_shutil_which): + ''' Testing binary lookup in /usr/local/bin ''' + + oc_bin = '/usr/local/bin/oc' + + mock_env_get.side_effect = lambda _v, _d: '/bin:/usr/bin' + + mock_shutil_which.side_effect = lambda _f, path=None: oc_bin + + self.assertEqual(locate_oc_binary(), oc_bin) + + @unittest.skipIf(six.PY2, 'py3 test only') + @mock.patch('shutil.which') + @mock.patch('os.environ.get') + def test_binary_lookup_in_home_py3(self, mock_env_get, mock_shutil_which): + ''' Testing binary lookup in ~/bin ''' + + oc_bin = os.path.expanduser('~/bin/oc') + + mock_env_get.side_effect = lambda _v, _d: '/bin:/usr/bin' + + mock_shutil_which.side_effect = lambda _f, path=None: oc_bin + + self.assertEqual(locate_oc_binary(), oc_bin) diff --git a/roles/lib_openshift/src/test/unit/test_oc_user.py b/roles/lib_openshift/src/test/unit/test_oc_user.py new file mode 100755 index 000000000..f7a17cc2c --- /dev/null +++ b/roles/lib_openshift/src/test/unit/test_oc_user.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python2 +''' + Unit tests for oc user +''' +# To run +# ./oc_user.py +# +# .. +# ---------------------------------------------------------------------- +# Ran 2 tests in 0.003s +# +# OK + +import os +import sys +import unittest +import mock + +# Removing invalid variable names for tests so that I can +# keep them brief +# pylint: disable=invalid-name,no-name-in-module +# Disable import-error b/c our libraries aren't loaded in jenkins +# pylint: disable=import-error +# place class in our python path +module_path = os.path.join('/'.join(os.path.realpath(__file__).split('/')[:-4]), 'library') # noqa: E501 +sys.path.insert(0, module_path) +from oc_user import OCUser # noqa: E402 + + +class OCUserTest(unittest.TestCase): + ''' + Test class for OCUser + ''' + + def setUp(self): + ''' setup method will create a file and set to known configuration ''' + pass + + @mock.patch('oc_user.Utils.create_tmpfile_copy') + @mock.patch('oc_user.OCUser._run') + def test_state_list(self, mock_cmd, mock_tmpfile_copy): + ''' Testing a user list ''' + params = {'username': 'testuser@email.com', + 'state': 'list', + 'kubeconfig': '/etc/origin/master/admin.kubeconfig', + 'full_name': None, + 'groups': [], + 'debug': False} + + user = '''{ + "kind": "User", + "apiVersion": "v1", + "metadata": { + "name": "testuser@email.com", + "selfLink": "/oapi/v1/users/testuser@email.com", + "uid": "02fee6c9-f20d-11e6-b83b-12e1a7285e80", + "resourceVersion": "38566887", + "creationTimestamp": "2017-02-13T16:53:58Z" + }, + "fullName": "Test User", + "identities": null, + "groups": null + }''' + + mock_cmd.side_effect = [ + (0, user, ''), + ] + + mock_tmpfile_copy.side_effect = [ + '/tmp/mocked_kubeconfig', + ] + + results = OCUser.run_ansible(params, False) + + self.assertFalse(results['changed']) + self.assertTrue(results['results'][0]['metadata']['name'] == "testuser@email.com") + + @mock.patch('oc_user.Utils.create_tmpfile_copy') + @mock.patch('oc_user.OCUser._run') + def test_state_present(self, mock_cmd, mock_tmpfile_copy): + ''' Testing a user list ''' + params = {'username': 'testuser@email.com', + 'state': 'present', + 'kubeconfig': '/etc/origin/master/admin.kubeconfig', + 'full_name': 'Test User', + 'groups': [], + 'debug': False} + + created_user = '''{ + "kind": "User", + "apiVersion": "v1", + "metadata": { + "name": "testuser@email.com", + "selfLink": "/oapi/v1/users/testuser@email.com", + "uid": "8d508039-f224-11e6-b83b-12e1a7285e80", + "resourceVersion": "38646241", + "creationTimestamp": "2017-02-13T19:42:28Z" + }, + "fullName": "Test User", + "identities": null, + "groups": null + }''' + + mock_cmd.side_effect = [ + (1, '', 'Error from server: users "testuser@email.com" not found'), # get + (1, '', 'Error from server: users "testuser@email.com" not found'), # get + (0, 'user "testuser@email.com" created', ''), # create + (0, created_user, ''), # get + ] + + mock_tmpfile_copy.side_effect = [ + '/tmp/mocked_kubeconfig', + ] + + results = OCUser.run_ansible(params, False) + + self.assertTrue(results['changed']) + self.assertTrue(results['results']['results'][0]['metadata']['name'] == + "testuser@email.com") + + def tearDown(self): + '''TearDown method''' + pass + + +if __name__ == "__main__": + unittest.main() |