diff --git a/library/ceph_dashboard_user.py b/library/ceph_dashboard_user.py new file mode 100644 index 000000000..154effab5 --- /dev/null +++ b/library/ceph_dashboard_user.py @@ -0,0 +1,349 @@ +# Copyright 2020, Red Hat, Inc. +# +# 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. + +from __future__ import absolute_import, division, print_function +__metaclass__ = type + + +ANSIBLE_METADATA = { + 'metadata_version': '1.1', + 'status': ['preview'], + 'supported_by': 'community' +} + +DOCUMENTATION = ''' +--- +module: ceph_dashboard_user + +short_description: Manage Ceph Dashboard User + +version_added: "2.8" + +description: + - Manage Ceph Dashboard user(s) creation, deletion and updates. +options: + cluster: + description: + - The ceph cluster name. + required: false + default: ceph + name: + description: + - name of the Ceph Dashboard user. + required: true + state: + description: + If 'present' is used, the module creates a user if it doesn't + exist or update it if it already exists. + If 'absent' is used, the module will simply delete the user. + If 'info' is used, the module will return all details about the + existing user (json formatted). + required: false + choices: ['present', 'absent', 'info'] + default: present + password: + description: + - password of the Ceph Dashboard user. + required: false + roles: + description: + - roles of the Ceph Dashboard user. + required: false + default: [] + +author: + - Dimitri Savineau +''' + +EXAMPLES = ''' +- name: create a Ceph Dashboard user + ceph_dashboard_user: + name: foo + password: bar + +- name: create a read-only/block-manager Ceph Dashboard user + ceph_dashboard_user: + name: foo + password: bar + roles: + - 'read-only' + - 'block-manager' + +- name: create a Ceph Dashboard admin user + ceph_dashboard_user: + name: foo + password: bar + roles: ['administrator'] + +- name: get a Ceph Dashboard user information + ceph_dashboard_user: + name: foo + state: info + +- name: delete a Ceph Dashboard user + ceph_dashboard_user: + name: foo + state: absent +''' + +RETURN = '''# ''' + +from ansible.module_utils.basic import AnsibleModule # noqa E402 +import datetime # noqa E402 +import json # noqa E402 +import os # noqa E402 +import stat # noqa E402 +import time # noqa E402 + + +def container_exec(binary, container_image): + ''' + Build the docker CLI to run a command inside a container + ''' + + container_binary = os.getenv('CEPH_CONTAINER_BINARY') + command_exec = [container_binary, + 'run', + '--rm', + '--net=host', + '-v', '/etc/ceph:/etc/ceph:z', + '-v', '/var/lib/ceph/:/var/lib/ceph/:z', + '-v', '/var/log/ceph/:/var/log/ceph/:z', + '--entrypoint=' + binary, container_image] + return command_exec + + +def is_containerized(): + ''' + Check if we are running on a containerized cluster + ''' + + if 'CEPH_CONTAINER_IMAGE' in os.environ: + container_image = os.getenv('CEPH_CONTAINER_IMAGE') + else: + container_image = None + + return container_image + + +def pre_generate_ceph_cmd(container_image=None): + ''' + Generate ceph prefix comaand + ''' + if container_image: + cmd = container_exec('ceph', container_image) + else: + cmd = ['ceph'] + + return cmd + + +def generate_ceph_cmd(cluster, args, container_image=None): + ''' + Generate 'ceph' command line to execute + ''' + + cmd = pre_generate_ceph_cmd(container_image=container_image) + + base_cmd = [ + '--cluster', + cluster, + 'dashboard' + ] + + cmd.extend(base_cmd + args) + + return cmd + + +def exec_commands(module, cmd): + ''' + Execute command(s) + ''' + + rc, out, err = module.run_command(cmd) + + return rc, cmd, out, err + + +def create_user(module, container_image=None): + ''' + Create a new user + ''' + + cluster = module.params.get('cluster') + name = module.params.get('name') + password = module.params.get('password') + + args = ['ac-user-create', name, password] + + cmd = generate_ceph_cmd(cluster=cluster, args=args, container_image=container_image) + + return cmd + + +def set_roles(module, container_image=None): + ''' + Set user roles + ''' + + cluster = module.params.get('cluster') + name = module.params.get('name') + roles = module.params.get('roles') + + args = ['ac-user-set-roles', name] + + args.extend(roles) + + cmd = generate_ceph_cmd(cluster=cluster, args=args, container_image=container_image) + + return cmd + + +def set_password(module, container_image=None): + ''' + Set user password + ''' + + cluster = module.params.get('cluster') + name = module.params.get('name') + password = module.params.get('password') + + args = ['ac-user-set-password', name, password] + + cmd = generate_ceph_cmd(cluster=cluster, args=args, container_image=container_image) + + return cmd + + +def get_user(module, container_image=None): + ''' + Get existing user + ''' + + cluster = module.params.get('cluster') + name = module.params.get('name') + + args = ['ac-user-show', name, '--format=json'] + + cmd = generate_ceph_cmd(cluster=cluster, args=args, container_image=container_image) + + return cmd + + +def remove_user(module, container_image=None): + ''' + Remove a user + ''' + + cluster = module.params.get('cluster') + name = module.params.get('name') + + args = ['ac-user-delete', name] + + cmd = generate_ceph_cmd(cluster=cluster, args=args, container_image=container_image) + + return cmd + + +def exit_module(module, out, rc, cmd, err, startd, changed=False): + endd = datetime.datetime.now() + delta = endd - startd + + result = dict( + cmd=cmd, + start=str(startd), + end=str(endd), + delta=str(delta), + rc=rc, + stdout=out.rstrip("\r\n"), + stderr=err.rstrip("\r\n"), + changed=changed, + ) + module.exit_json(**result) + + +def run_module(): + module_args = dict( + cluster=dict(type='str', required=False, default='ceph'), + name=dict(type='str', required=True), + state=dict(type='str', required=False, choices=['present', 'absent', 'info'], default='present'), + password=dict(type='str', required=False, no_log=True), + roles=dict(type='list', required=False, choices=['administrator', 'read-only', 'block-manager', 'rgw-manager', 'cluster-manager', 'pool-manager', 'cephfs-manager'], default=[]), + ) + + module = AnsibleModule( + argument_spec=module_args, + supports_check_mode=True, + required_if=[['state', 'present', ['password']]] + ) + + # Gather module parameters in variables + name = module.params.get('name') + state = module.params.get('state') + roles = module.params.get('roles') + + if module.check_mode: + module.exit_json( + changed=False, + stdout='', + stderr='', + rc=0, + start='', + end='', + delta='', + ) + + startd = datetime.datetime.now() + changed = False + + # will return either the image name or None + container_image = is_containerized() + + if state == "present": + rc, cmd, out, err = exec_commands(module, get_user(module, container_image=container_image)) + if rc == 0: + user = json.loads(out) + user['roles'].sort() + roles.sort() + if user['roles'] != roles: + rc, cmd, out, err = exec_commands(module, set_roles(module, container_image=container_image)) + changed = True + rc, cmd, out, err = exec_commands(module, set_password(module, container_image=container_image)) + else: + rc, cmd, out, err = exec_commands(module, create_user(module, container_image=container_image)) + rc, cmd, out, err = exec_commands(module, set_roles(module, container_image=container_image)) + changed = True + + elif state == "absent": + rc, cmd, out, err = exec_commands(module, get_user(module, container_image=container_image)) + if rc == 0: + rc, cmd, out, err = exec_commands(module, remove_user(module, container_image=container_image)) + changed = True + else: + rc = 0 + out = "Dashboard User {} doesn't exist".format(name) + + elif state == "info": + rc, cmd, out, err = exec_commands(module, get_user(module, container_image=container_image)) + + exit_module(module=module, out=out, rc=rc, cmd=cmd, err=err, startd=startd, changed=changed) + + +def main(): + run_module() + + +if __name__ == '__main__': + main() diff --git a/roles/ceph-dashboard/tasks/configure_dashboard.yml b/roles/ceph-dashboard/tasks/configure_dashboard.yml index 026c9c57c..dbfccced3 100644 --- a/roles/ceph-dashboard/tasks/configure_dashboard.yml +++ b/roles/ceph-dashboard/tasks/configure_dashboard.yml @@ -122,46 +122,17 @@ run_once: true changed_when: false -- name: check if dashboard admin user exists - command: timeout --foreground -s KILL 10 {{ container_exec_cmd }} ceph --cluster {{ cluster }} dashboard ac-user-show {{ dashboard_admin_user | quote }} - register: dashboard_admin_user_exist - retries: 6 - delay: 5 - run_once: true - failed_when: false - changed_when: false - delegate_to: "{{ groups[mon_group_name][0] }}" - until: dashboard_admin_user_exist.rc == 0 - -- name: update dashboard admin password - command: timeout --foreground -s KILL 10 {{ container_exec_cmd }} ceph --cluster {{ cluster }} dashboard ac-user-set-password {{ dashboard_admin_user | quote }} {{ dashboard_admin_password | quote }} - register: update_dashboard_admin_user - retries: 6 - delay: 5 - run_once: true - delegate_to: "{{ groups[mon_group_name][0] }}" - until: update_dashboard_admin_user.rc == 0 - when: dashboard_admin_user_exist.rc == 0 - - name: create dashboard admin user - command: timeout --foreground -s KILL 10 {{ container_exec_cmd }} ceph --cluster {{ cluster }} dashboard ac-user-create {{ dashboard_admin_user | quote }} {{ dashboard_admin_password | quote }} - register: create_dashboard_admin_user - retries: 6 - delay: 5 + ceph_dashboard_user: + name: "{{ dashboard_admin_user }}" + cluster: "{{ cluster }}" + password: "{{ dashboard_admin_password }}" + roles: ["{{ 'read-only' if dashboard_admin_user_ro | bool else 'administrator' }}"] run_once: true delegate_to: "{{ groups[mon_group_name][0] }}" - until: create_dashboard_admin_user.rc == 0 - when: dashboard_admin_user_exist.rc != 0 - -- name: set dashboard admin user role - command: timeout --foreground -s KILL 10 {{ container_exec_cmd }} ceph --cluster {{ cluster }} dashboard ac-user-set-roles {{ dashboard_admin_user | quote }} {{ 'read-only' if dashboard_admin_user_ro | bool else 'administrator' }} - register: dashboard_admin_user_role - retries: 6 - delay: 5 - run_once: true - changed_when: false - delegate_to: "{{ groups[mon_group_name][0] }}" - until: dashboard_admin_user_role.rc == 0 + environment: + CEPH_CONTAINER_IMAGE: "{{ ceph_docker_registry + '/' + ceph_docker_image + ':' + ceph_docker_image_tag if containerized_deployment | bool else None }}" + CEPH_CONTAINER_BINARY: "{{ container_binary }}" - name: set grafana api user command: "{{ container_exec_cmd }} ceph --cluster {{ cluster }} dashboard set-grafana-api-username {{ grafana_admin_user }}" diff --git a/tests/library/test_ceph_dashboard_user.py b/tests/library/test_ceph_dashboard_user.py new file mode 100644 index 000000000..3f8819ca5 --- /dev/null +++ b/tests/library/test_ceph_dashboard_user.py @@ -0,0 +1,135 @@ +import json +import os +import sys +sys.path.append('./library') +import ceph_dashboard_user +from mock.mock import patch, Mock, MagicMock +import pytest + + +fake_binary = 'ceph' +fake_cluster = 'ceph' +fake_container_binary = 'podman' +fake_container_image = 'docker.io/ceph/daemon:latest' +fake_container_cmd = [ + fake_container_binary, + 'run', + '--rm', + '--net=host', + '-v', '/etc/ceph:/etc/ceph:z', + '-v', '/var/lib/ceph/:/var/lib/ceph/:z', + '-v', '/var/log/ceph/:/var/log/ceph/:z', + '--entrypoint=' + fake_binary, + fake_container_image +] +fake_user = 'foo' +fake_password = 'bar' +fake_roles = ['read-only', 'block-manager'] +fake_params = {'cluster': fake_cluster, + 'name': fake_user, + 'password': fake_password, + 'roles': fake_roles} + + +class TestRadosgwRealmModule(object): + + @patch.dict(os.environ, {'CEPH_CONTAINER_BINARY': fake_container_binary}) + def test_container_exec(self): + cmd = ceph_dashboard_user.container_exec(fake_binary, fake_container_image) + assert cmd == fake_container_cmd + + def test_not_is_containerized(self): + assert ceph_dashboard_user.is_containerized() is None + + @patch.dict(os.environ, {'CEPH_CONTAINER_IMAGE': fake_container_image}) + def test_is_containerized(self): + assert ceph_dashboard_user.is_containerized() == fake_container_image + + @pytest.mark.parametrize('image', [None, fake_container_image]) + @patch.dict(os.environ, {'CEPH_CONTAINER_BINARY': fake_container_binary}) + def test_pre_generate_ceph_cmd(self, image): + if image: + expected_cmd = fake_container_cmd + else: + expected_cmd = [fake_binary] + + assert ceph_dashboard_user.pre_generate_ceph_cmd(image) == expected_cmd + + @pytest.mark.parametrize('image', [None, fake_container_image]) + @patch.dict(os.environ, {'CEPH_CONTAINER_BINARY': fake_container_binary}) + def test_generate_ceph_cmd(self, image): + if image: + expected_cmd = fake_container_cmd + else: + expected_cmd = [fake_binary] + + expected_cmd.extend([ + '--cluster', + fake_cluster, + 'dashboard' + ]) + assert ceph_dashboard_user.generate_ceph_cmd(fake_cluster, [], image) == expected_cmd + + def test_create_user(self): + fake_module = MagicMock() + fake_module.params = fake_params + expected_cmd = [ + fake_binary, + '--cluster', fake_cluster, + 'dashboard', 'ac-user-create', + fake_user, + fake_password + ] + + assert ceph_dashboard_user.create_user(fake_module) == expected_cmd + + def test_set_roles(self): + fake_module = MagicMock() + fake_module.params = fake_params + expected_cmd = [ + fake_binary, + '--cluster', fake_cluster, + 'dashboard', 'ac-user-set-roles', + fake_user + ] + expected_cmd.extend(fake_roles) + + assert ceph_dashboard_user.set_roles(fake_module) == expected_cmd + + def test_set_password(self): + fake_module = MagicMock() + fake_module.params = fake_params + expected_cmd = [ + fake_binary, + '--cluster', fake_cluster, + 'dashboard', 'ac-user-set-password', + fake_user, + fake_password + ] + + assert ceph_dashboard_user.set_password(fake_module) == expected_cmd + + def test_get_user(self): + fake_module = MagicMock() + fake_module.params = fake_params + expected_cmd = [ + fake_binary, + '--cluster', fake_cluster, + 'dashboard', 'ac-user-show', + fake_user, + '--format=json' + ] + + assert ceph_dashboard_user.get_user(fake_module) == expected_cmd + + def test_remove_user(self): + fake_module = MagicMock() + fake_module.params = fake_params + expected_cmd = [ + fake_binary, + '--cluster', fake_cluster, + 'dashboard', 'ac-user-delete', + fake_user + ] + + assert ceph_dashboard_user.remove_user(fake_module) == expected_cmd \ No newline at end of file