Exemplo n.º 1
0
def update_pool(module,
                cluster,
                name,
                user,
                user_key,
                delta,
                container_image=None):
    '''
    Update an existing pool
    '''

    report = ""

    for key in delta.keys():
        if key != 'application':
            args = [
                'set', name, delta[key]['cli_set_opt'], delta[key]['value']
            ]

            cmd = generate_ceph_cmd(sub_cmd=['osd', 'pool'],
                                    args=args,
                                    cluster=cluster,
                                    user=user,
                                    user_key=user_key,
                                    container_image=container_image)

            rc, cmd, out, err = exec_command(module, cmd)
            if rc != 0:
                return rc, cmd, out, err

        else:
            rc, cmd, out, err = exec_command(
                module,
                disable_application_pool(
                    cluster,
                    name,
                    delta['application']['old_application'],
                    user,
                    user_key,
                    container_image=container_image))  # noqa: E501
            if rc != 0:
                return rc, cmd, out, err

            rc, cmd, out, err = exec_command(
                module,
                enable_application_pool(
                    cluster,
                    name,
                    delta['application']['new_application'],
                    user,
                    user_key,
                    container_image=container_image))  # noqa: E501
            if rc != 0:
                return rc, cmd, out, err

        report = report + "\n" + "{} has been updated: {} is now {}".format(
            name, key, delta[key]['value'])  # noqa: E501

    out = report
    return rc, cmd, out, err
Exemplo n.º 2
0
def get_pool_details(module,
                     cluster,
                     name,
                     user,
                     user_key,
                     output_format='json',
                     container_image=None):
    '''
    Get details about a given pool
    '''

    args = ['ls', 'detail', '-f', output_format]

    cmd = generate_ceph_cmd(sub_cmd=['osd', 'pool'],
                            args=args,
                            cluster=cluster,
                            user=user,
                            user_key=user_key,
                            container_image=container_image)

    rc, cmd, out, err = exec_command(module, cmd)

    if rc == 0:
        out = [p for p in json.loads(out.strip()) if p['pool_name'] == name][0]

    _rc, _cmd, application_pool, _err = exec_command(
        module,
        get_application_pool(
            cluster,  # noqa: E501
            name,  # noqa: E501
            user,  # noqa: E501
            user_key,  # noqa: E501
            container_image=container_image))  # noqa: E501

    # This is a trick because "target_size_ratio" isn't present at the same
    # level in the dict
    # ie:
    # {
    # 'pg_num': 8,
    # 'pgp_num': 8,
    # 'pg_autoscale_mode': 'on',
    #     'options': {
    #          'target_size_ratio': 0.1
    #     }
    # }
    # If 'target_size_ratio' is present in 'options', we set it, this way we
    # end up with a dict containing all needed keys at the same level.
    if 'target_size_ratio' in out['options'].keys():
        out['target_size_ratio'] = out['options']['target_size_ratio']
    else:
        out['target_size_ratio'] = None

    application = list(json.loads(application_pool.strip()).keys())

    if len(application) == 0:
        out['application'] = ''
    else:
        out['application'] = application[0]

    return rc, cmd, out, err
Exemplo n.º 3
0
def run_module():

    module = AnsibleModule(
        argument_spec=yaml.safe_load(DOCUMENTATION)['options'],
        supports_check_mode=True,
        required_if=[['state', 'present', ['data', 'metadata']]],
    )

    # Gather module parameters in variables
    name = module.params.get('name')
    state = module.params.get('state')
    max_mds = module.params.get('max_mds')

    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_command(module, get_fs(module, container_image=container_image))
        if rc == 0:
            fs = json.loads(out)
            if max_mds and fs["mdsmap"]["max_mds"] != max_mds:
                rc, cmd, out, err = exec_command(module, set_fs(module, container_image=container_image))
                if rc == 0:
                    changed = True
        else:
            rc, cmd, out, err = exec_command(module, create_fs(module, container_image=container_image))
            if max_mds and max_mds > 1:
                exec_command(module, set_fs(module, container_image=container_image))
            if rc == 0:
                changed = True

    elif state == "absent":
        rc, cmd, out, err = exec_command(module, get_fs(module, container_image=container_image))
        if rc == 0:
            exec_command(module, fail_fs(module, container_image=container_image))
            rc, cmd, out, err = exec_command(module, remove_fs(module, container_image=container_image))
            if rc == 0:
                changed = True
        else:
            rc = 0
            out = "Ceph File System {} doesn't exist".format(name)

    elif state == "info":
        rc, cmd, out, err = exec_command(module, get_fs(module, container_image=container_image))

    exit_module(module=module, out=out, rc=rc, cmd=cmd, err=err, startd=startd, changed=changed)
Exemplo n.º 4
0
def is_lv(module, vg, lv, container_image):
    '''
    Check if an LV exists
    '''

    args = [
        '--noheadings', '--reportformat', 'json', '--select',
        'lv_name={},vg_name={}'.format(lv, vg)
    ]  # noqa E501

    cmd = build_cmd(args, container_image, binary='lvs')

    rc, cmd, out, err = exec_command(module, cmd)

    result = json.loads(out)['report'][0]['lv']
    if rc == 0 and len(result) > 0:
        return True
    else:
        return False
Exemplo n.º 5
0
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,
                   default='present',
                   choices=['present', 'absent', 'list']),
        details=dict(type='bool', required=False, default=False),
        size=dict(type='str', required=False),
        min_size=dict(type='str', required=False),
        pg_num=dict(type='str', required=False),
        pgp_num=dict(type='str', required=False),
        pg_autoscale_mode=dict(type='str', required=False, default='on'),
        target_size_ratio=dict(type='str', required=False, default=None),
        pool_type=dict(type='str',
                       required=False,
                       default='replicated',
                       choices=['replicated', 'erasure', '1', '3']),
        erasure_profile=dict(type='str', required=False, default='default'),
        rule_name=dict(type='str', required=False, default=None),
        expected_num_objects=dict(type='str', required=False, default="0"),
        application=dict(type='str', required=False, default=None),
    )

    module = AnsibleModule(argument_spec=module_args, supports_check_mode=True)

    # Gather module parameters in variables
    cluster = module.params.get('cluster')
    name = module.params.get('name')
    state = module.params.get('state')
    details = module.params.get('details')
    size = module.params.get('size')
    min_size = module.params.get('min_size')
    pg_num = module.params.get('pg_num')
    pgp_num = module.params.get('pgp_num')
    pg_autoscale_mode = module.params.get('pg_autoscale_mode')
    target_size_ratio = module.params.get('target_size_ratio')
    application = module.params.get('application')

    if (module.params.get('pg_autoscale_mode').lower()
            in ['true', 'on', 'yes']):
        pg_autoscale_mode = 'on'
    elif (module.params.get('pg_autoscale_mode').lower()
          in ['false', 'off', 'no']):
        pg_autoscale_mode = 'off'
    else:
        pg_autoscale_mode = 'warn'

    if module.params.get('pool_type') == '1':
        pool_type = 'replicated'
    elif module.params.get('pool_type') == '3':
        pool_type = 'erasure'
    else:
        pool_type = module.params.get('pool_type')

    if not module.params.get('rule_name'):
        rule_name = 'replicated_rule' if pool_type == 'replicated' else None
    else:
        rule_name = module.params.get('rule_name')

    erasure_profile = module.params.get('erasure_profile')
    expected_num_objects = module.params.get('expected_num_objects')
    user_pool_config = {
        'pool_name': {
            'value': name
        },
        'pg_num': {
            'value': pg_num,
            'cli_set_opt': 'pg_num'
        },
        'pgp_num': {
            'value': pgp_num,
            'cli_set_opt': 'pgp_num'
        },
        'pg_autoscale_mode': {
            'value': pg_autoscale_mode,
            'cli_set_opt': 'pg_autoscale_mode'
        },
        'target_size_ratio': {
            'value': target_size_ratio,
            'cli_set_opt': 'target_size_ratio'
        },
        'application': {
            'value': application
        },
        'type': {
            'value': pool_type
        },
        'erasure_profile': {
            'value': erasure_profile
        },
        'crush_rule': {
            'value': rule_name,
            'cli_set_opt': 'crush_rule'
        },
        'expected_num_objects': {
            'value': expected_num_objects
        },
        'size': {
            'value': size,
            'cli_set_opt': 'size'
        },
        'min_size': {
            'value': min_size
        }
    }

    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()

    user = "******"
    keyring_filename = cluster + '.' + user + '.keyring'
    user_key = os.path.join("/etc/ceph/", keyring_filename)

    if state == "present":
        rc, cmd, out, err = exec_command(
            module,
            check_pool_exist(cluster,
                             name,
                             user,
                             user_key,
                             container_image=container_image))  # noqa: E501
        if rc == 0:
            running_pool_details = get_pool_details(
                module,
                cluster,
                name,
                user,
                user_key,
                container_image=container_image)  # noqa: E501
            user_pool_config['pg_placement_num'] = {
                'value': str(running_pool_details[2]['pg_placement_num']),
                'cli_set_opt': 'pgp_num'
            }  # noqa: E501
            delta = compare_pool_config(user_pool_config,
                                        running_pool_details[2])
            if len(delta) > 0:
                keys = list(delta.keys())
                details = running_pool_details[2]
                if details['erasure_code_profile'] and 'size' in keys:
                    del delta['size']
                if details['pg_autoscale_mode'] == 'on':
                    delta.pop('pg_num', None)
                    delta.pop('pgp_num', None)

                if len(delta) == 0:
                    out = "Skipping pool {}.\nUpdating either 'size' on an erasure-coded pool or 'pg_num'/'pgp_num' on a pg autoscaled pool is incompatible".format(
                        name)  # noqa: E501
                else:
                    rc, cmd, out, err = update_pool(
                        module,
                        cluster,
                        name,
                        user,
                        user_key,
                        delta,
                        container_image=container_image)  # noqa: E501
                    if rc == 0:
                        changed = True
            else:
                out = "Pool {} already exists and there is nothing to update.".format(
                    name)  # noqa: E501
        else:
            rc, cmd, out, err = exec_command(
                module,
                create_pool(
                    cluster,
                    name,
                    user,
                    user_key,
                    user_pool_config=user_pool_config,  # noqa: E501
                    container_image=container_image))  # noqa: E501
            if user_pool_config['application']['value']:
                rc, _, _, _ = exec_command(
                    module,
                    enable_application_pool(
                        cluster,
                        name,
                        user_pool_config['application']['value'],  # noqa: E501
                        user,
                        user_key,
                        container_image=container_image))  # noqa: E501
            if user_pool_config['min_size']['value']:
                # not implemented yet
                pass
            changed = True

    elif state == "list":
        rc, cmd, out, err = exec_command(
            module,
            list_pools(cluster,
                       name,
                       user,
                       user_key,
                       details,
                       container_image=container_image))  # noqa: E501
        if rc != 0:
            out = "Couldn't list pool(s) present on the cluster"

    elif state == "absent":
        rc, cmd, out, err = exec_command(
            module,
            check_pool_exist(cluster,
                             name,
                             user,
                             user_key,
                             container_image=container_image))  # noqa: E501
        if rc == 0:
            rc, cmd, out, err = exec_command(
                module,
                remove_pool(cluster,
                            name,
                            user,
                            user_key,
                            container_image=container_image))  # noqa: E501
            changed = True
        else:
            rc = 0
            out = "Skipped, since pool {} doesn't exist".format(name)

    exit_module(module=module,
                out=out,
                rc=rc,
                cmd=cmd,
                err=err,
                startd=startd,
                changed=changed)
Exemplo n.º 6
0
def run_module():
    module_args = dict(
        cluster=dict(type='str', required=False, default='ceph'),
        objectstore=dict(type='str',
                         required=False,
                         choices=['bluestore', 'filestore'],
                         default='bluestore'),
        action=dict(type='str',
                    required=False,
                    choices=[
                        'create', 'zap', 'batch', 'prepare', 'activate',
                        'list', 'inventory'
                    ],
                    default='create'),  # noqa: 4502
        data=dict(type='str', required=False),
        data_vg=dict(type='str', required=False),
        journal=dict(type='str', required=False),
        journal_vg=dict(type='str', required=False),
        db=dict(type='str', required=False),
        db_vg=dict(type='str', required=False),
        wal=dict(type='str', required=False),
        wal_vg=dict(type='str', required=False),
        crush_device_class=dict(type='str', required=False),
        dmcrypt=dict(type='bool', required=False, default=False),
        batch_devices=dict(type='list', required=False, default=[]),
        osds_per_device=dict(type='int', required=False, default=1),
        journal_size=dict(type='str', required=False, default='5120'),
        journal_devices=dict(type='list', required=False, default=[]),
        block_db_size=dict(type='str', required=False, default='-1'),
        block_db_devices=dict(type='list', required=False, default=[]),
        wal_devices=dict(type='list', required=False, default=[]),
        report=dict(type='bool', required=False, default=False),
        osd_fsid=dict(type='str', required=False),
        osd_id=dict(type='str', required=False),
        destroy=dict(type='bool', required=False, default=True),
    )

    module = AnsibleModule(argument_spec=module_args,
                           supports_check_mode=True,
                           mutually_exclusive=[
                               ('data', 'osd_fsid', 'osd_id'),
                           ],
                           required_if=[('action', 'zap', ('data', 'osd_fsid',
                                                           'osd_id'), True)])

    result = dict(
        changed=False,
        stdout='',
        stderr='',
        rc=0,
        start='',
        end='',
        delta='',
    )

    if module.check_mode:
        module.exit_json(**result)

    # start execution
    startd = datetime.datetime.now()

    # get the desired action
    action = module.params['action']

    # will return either the image name or None
    container_image = is_containerized()

    # Assume the task's status will be 'changed'
    changed = True

    if action == 'create' or action == 'prepare':
        # First test if the device has Ceph LVM Metadata
        rc, cmd, out, err = exec_command(module,
                                         list_osd(module, container_image))

        # list_osd returns a dict, if the dict is empty this means
        # we can not check the return code since it's not consistent
        # with the plain output
        # see: http://tracker.ceph.com/issues/36329
        # FIXME: it's probably less confusing to check for rc

        # convert out to json, ansible returns a string...
        try:
            out_dict = json.loads(out)
        except ValueError:
            fatal(
                "Could not decode json output: {} from the command {}".format(
                    out, cmd), module)  # noqa: E501

        if out_dict:
            data = module.params['data']
            result[
                'stdout'] = 'skipped, since {0} is already used for an osd'.format(
                    data)  # noqa: E501
            result['rc'] = 0
            module.exit_json(**result)

        # Prepare or create the OSD
        rc, cmd, out, err = exec_command(
            module, prepare_or_create_osd(module, action, container_image))
        err = re.sub('[a-zA-Z0-9+/]{38}==', '*' * 8, err)

    elif action == 'activate':
        if container_image:
            fatal(
                "This is not how container's activation happens, nothing to activate",
                module)  # noqa: E501

        # Activate the OSD
        rc, cmd, out, err = exec_command(module, activate_osd())

    elif action == 'zap':
        # Zap the OSD
        skip = []
        for device_type in ['journal', 'data', 'db', 'wal']:
            # 1/ if we passed vg/lv
            if module.params.get('{}_vg'.format(device_type),
                                 None) and module.params.get(
                                     device_type, None):  # noqa: E501
                # 2/ check this is an actual lv/vg
                ret = is_lv(module, module.params['{}_vg'.format(device_type)],
                            module.params[device_type],
                            container_image)  # noqa: E501
                skip.append(ret)
                # 3/ This isn't a lv/vg device
                if not ret:
                    module.params['{}_vg'.format(device_type)] = False
                    module.params[device_type] = False
            # 4/ no journal|data|db|wal|_vg was passed, so it must be a raw device  # noqa: E501
            elif not module.params.get('{}_vg'.format(device_type),
                                       None) and module.params.get(
                                           device_type, None):  # noqa: E501
                skip.append(True)

        cmd = zap_devices(module, container_image)

        if any(skip) or module.params.get('osd_fsid', None) \
                or module.params.get('osd_id', None):
            rc, cmd, out, err = exec_command(module, cmd)
            for scan_cmd in ['vgscan', 'lvscan']:
                module.run_command([scan_cmd, '--cache'])
        else:
            out = 'Skipped, nothing to zap'
            err = ''
            changed = False
            rc = 0

    elif action == 'list':
        # List Ceph LVM Metadata on a device
        rc, cmd, out, err = exec_command(module,
                                         list_osd(module, container_image))

    elif action == 'inventory':
        # List storage device inventory.
        rc, cmd, out, err = exec_command(
            module, list_storage_inventory(module, container_image))

    elif action == 'batch':
        # Batch prepare AND activate OSDs
        report = module.params.get('report', None)

        # Add --report flag for the idempotency test
        report_flags = [
            '--report',
            '--format=json',
        ]

        cmd = batch(module, container_image, report=True)
        batch_report_cmd = copy.copy(cmd)
        batch_report_cmd.extend(report_flags)

        # Run batch --report to see what's going to happen
        # Do not run the batch command if there is nothing to do
        rc, cmd, out, err = exec_command(module, batch_report_cmd)
        try:
            if not out:
                out = '{}'
            report_result = json.loads(out)
        except ValueError:
            strategy_changed_in_out = "strategy changed" in out
            strategy_changed_in_err = "strategy changed" in err
            strategy_changed = strategy_changed_in_out or \
                strategy_changed_in_err
            if strategy_changed:
                if strategy_changed_in_out:
                    out = json.dumps({
                        "changed": False,
                        "stdout": out.rstrip("\r\n")
                    })
                elif strategy_changed_in_err:
                    out = json.dumps({
                        "changed": False,
                        "stderr": err.rstrip("\r\n")
                    })
                rc = 0
                changed = False
            else:
                out = out.rstrip("\r\n")
            result = dict(
                cmd=cmd,
                stdout=out.rstrip('\r\n'),
                stderr=err.rstrip('\r\n'),
                rc=rc,
                changed=changed,
            )
            if strategy_changed:
                module.exit_json(**result)
            module.fail_json(msg='non-zero return code', **result)

        if not report:
            if 'changed' in report_result:
                # we have the old batch implementation
                # if not asking for a report, let's just run the batch command
                changed = report_result['changed']
                if changed:
                    # Batch prepare the OSD
                    rc, cmd, out, err = exec_command(
                        module, batch(module, container_image))
                    err = re.sub('[a-zA-Z0-9+/]{38}==', '*' * 8, err)
            else:
                # we have the refactored batch, its idempotent so lets just
                # run it
                rc, cmd, out, err = exec_command(
                    module, batch(module, container_image))
                err = re.sub('[a-zA-Z0-9+/]{38}==', '*' * 8, err)
        else:
            cmd = batch_report_cmd

    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,
    )

    if rc != 0:
        module.fail_json(msg='non-zero return code', **result)

    module.exit_json(**result)
Exemplo n.º 7
0
def run_module():

    module = AnsibleModule(
        argument_spec=yaml.safe_load(DOCUMENTATION)['options'],
        supports_check_mode=True,
        required_if=[['apply', True, ['render_path']]],
    )

    # Gather module parameters in variables
    cluster = module.params.get('cluster')
    service_type = module.params.get('service_type')
    service_id = module.params.get('service_type')
    service_name = module.params.get('service_name')
    hosts = module.params.get('hosts')
    host_pattern = module.params.get('host_pattern')
    networks = module.params.get('networks')
    labels = module.params.get('labels')
    spec = module.params.get('spec')
    extra = module.params.get('extra')
    apply = module.params.get('apply')
    render_path = module.params.get('render_path')

    if module.check_mode:
        module.exit_json(
            changed=False,
            stdout='',
            stderr='',
            rc=0,
            start='',
            end='',
            delta='',
        )

    startd = datetime.datetime.now()
    changed = False

    # PROCESSING PARAMETERS
    if service_id is None:
        service_id = service_type
    if service_name is None:
        service_name = "{}.{}".format(service_type, service_id)

    # no spec is provided
    if spec is None:
        spec = {}

    # no spec is provided
    if extra is None:
        extra = {}

    # no labels are defined
    if labels is None:
        labels = []

    # no networks are defined
    if networks is None:
        networks = []

    d = ceph_spec.CephDaemonSpec(service_type, service_id, service_name,
                                 hosts, host_pattern, networks, spec, labels, **extra)

    if apply:
        container_image = is_containerized()
        render('{}/{}'.format(render_path, service_type), d.make_daemon_spec())
        cmd = generate_orch_cli(cluster, '{}/{}'.format(render_path, service_type), container_image)
        rc, cmd, out, err = exec_command(module, cmd)
        exit_module(module=module, out=out, rc=rc, cmd=cmd, err=err, startd=startd, changed=changed)
    else:
        # render the dict as the output of the module
        module.exit_json(changed=True, result=d.make_daemon_spec())
Exemplo n.º 8
0
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')
    password = module.params.get('password')

    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_command(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_command(module, set_roles(module, container_image=container_image))
                changed = True
            rc, cmd, out, err = exec_command(module, set_password(module, container_image=container_image), stdin=password)
        else:
            rc, cmd, out, err = exec_command(module, create_user(module, container_image=container_image), stdin=password)
            rc, cmd, out, err = exec_command(module, set_roles(module, container_image=container_image))
            changed = True

    elif state == "absent":
        rc, cmd, out, err = exec_command(module, get_user(module, container_image=container_image))
        if rc == 0:
            rc, cmd, out, err = exec_command(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_command(module, get_user(module, container_image=container_image))

    exit_module(module=module, out=out, rc=rc, cmd=cmd, err=err, startd=startd, changed=changed)
Exemplo n.º 9
0
def main():
    module = AnsibleModule(argument_spec=dict(
        name=dict(type='str', required=True),
        cluster=dict(type='str', required=False, default='ceph'),
        state=dict(type='str',
                   required=False,
                   choices=['present', 'absent', 'info'],
                   default='present'),
        rule_type=dict(type='str',
                       required=False,
                       choices=['replicated', 'erasure']),
        bucket_root=dict(type='str', required=False),
        bucket_type=dict(type='str',
                         required=False,
                         choices=[
                             'osd', 'host', 'chassis', 'rack', 'row', 'pdu',
                             'pod', 'room', 'datacenter', 'zone', 'region',
                             'root'
                         ]),
        device_class=dict(type='str', required=False),
        profile=dict(type='str', required=False)),
                           supports_check_mode=True,
                           required_if=[('state', 'present', ['rule_type']),
                                        ('rule_type', 'replicated',
                                         ['bucket_root', 'bucket_type']),
                                        ('rule_type', 'erasure', ['profile'])])

    # Gather module parameters in variables
    name = module.params.get('name')
    state = module.params.get('state')
    rule_type = module.params.get('rule_type')

    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_command(
            module, get_rule(module, container_image=container_image))
        if rc != 0:
            rc, cmd, out, err = exec_command(
                module, create_rule(module, container_image=container_image))
            changed = True
        else:
            rule = json.loads(out)
            if (rule['type'] == 1 and rule_type == 'erasure') or (
                    rule['type'] == 3 and rule_type == 'replicated'):
                module.fail_json(
                    msg="Can not convert crush rule {} to {}".format(
                        name, rule_type),
                    changed=False,
                    rc=1)

    elif state == "absent":
        rc, cmd, out, err = exec_command(
            module, get_rule(module, container_image=container_image))
        if rc == 0:
            rc, cmd, out, err = exec_command(
                module, remove_rule(module, container_image=container_image))
            changed = True
        else:
            rc = 0
            out = "Crush Rule {} doesn't exist".format(name)

    elif state == "info":
        rc, cmd, out, err = exec_command(
            module, get_rule(module, container_image=container_image))

    exit_module(module=module,
                out=out,
                rc=rc,
                cmd=cmd,
                err=err,
                startd=startd,
                changed=changed)
Exemplo n.º 10
0
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'],
                   default='present'),
        stripe_unit=dict(type='str', required=False),
        k=dict(type='str', required=False),
        m=dict(type='str', required=False),
    )

    module = AnsibleModule(
        argument_spec=module_args,
        supports_check_mode=True,
        required_if=[['state', 'present', ['k', 'm']]],
    )

    # Gather module parameters in variables
    name = module.params.get('name')
    cluster = module.params.get('cluster')
    state = module.params.get('state')
    stripe_unit = module.params.get('stripe_unit')
    k = module.params.get('k')
    m = module.params.get('m')

    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_command(
            module,
            get_profile(module, name, cluster,
                        container_image=container_image))  # noqa: E501
        if rc == 0:
            # the profile already exists, let's check whether we have to
            # update it
            current_profile = json.loads(out)
            if current_profile['k'] != k or \
               current_profile['m'] != m or \
               current_profile.get('stripe_unit', stripe_unit) != stripe_unit:
                rc, cmd, out, err = exec_command(
                    module,
                    create_profile(
                        module,
                        name,
                        k,
                        m,
                        stripe_unit,
                        cluster,
                        force=True,
                        container_image=container_image))  # noqa: E501
                changed = True
        else:
            # the profile doesn't exist, it has to be created
            rc, cmd, out, err = exec_command(
                module,
                create_profile(
                    module,
                    name,
                    k,
                    m,
                    stripe_unit,  # noqa: E501
                    cluster,
                    container_image=container_image))  # noqa: E501
            if rc == 0:
                changed = True

    elif state == "absent":
        rc, cmd, out, err = exec_command(
            module,
            delete_profile(module,
                           name,
                           cluster,
                           container_image=container_image))  # noqa: E501
        if not err:
            out = 'Profile {} removed.'.format(name)
            changed = True
        else:
            rc = 0
            out = "Skipping, the profile {} doesn't exist".format(name)

    exit_module(module=module,
                out=out,
                rc=rc,
                cmd=cmd,
                err=err,
                startd=startd,
                changed=changed)  # noqa: E501
Exemplo n.º 11
0
def run_module():
    module = AnsibleModule(
        argument_spec=yaml.safe_load(DOCUMENTATION)['options'],
        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')
    password = module.params.get('password')

    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_command(
            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_command(
                    module, set_roles(module, container_image=container_image))
                changed = True
            rc, cmd, out, err = exec_command(
                module,
                set_password(module, container_image=container_image),
                stdin=password)
        else:
            rc, cmd, out, err = exec_command(
                module,
                create_user(module, container_image=container_image),
                stdin=password)
            rc, cmd, out, err = exec_command(
                module, set_roles(module, container_image=container_image))
            changed = True

    elif state == "absent":
        rc, cmd, out, err = exec_command(
            module, get_user(module, container_image=container_image))
        if rc == 0:
            rc, cmd, out, err = exec_command(
                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_command(
            module, get_user(module, container_image=container_image))

    exit_module(module=module,
                out=out,
                rc=rc,
                cmd=cmd,
                err=err,
                startd=startd,
                changed=changed)
Exemplo n.º 12
0
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"],
                   default="present"),
        caps=dict(type="list", required=True),
    )

    module = AnsibleModule(
        argument_spec=module_args,
        supports_check_mode=True,
    )

    # Gather module parameters in variables
    name = module.params.get("name")
    state = module.params.get("state")
    caps = module.params.get("caps")

    startd = datetime.datetime.now()
    changed = False

    # will return either the image name or None
    container_image = is_containerized()

    diff = dict(before="", after="")

    # get user infos for diff
    rc, cmd, out, err = exec_command(
        module, get_user(module, container_image=container_image))

    if rc == 0:
        before_user = json.loads(out)
        before_caps = sorted(before_user["caps"], key=lambda d: d["type"])
        diff["before"] = json.dumps(before_caps, indent=4)

        out = ""
        err = ""

        if state == "present":
            cmd = add_caps(module, container_image=container_image)
        elif state == "absent":
            cmd = remove_caps(module, container_image=container_image)

        if not module.check_mode:
            rc, cmd, out, err = exec_command(module, cmd)
        else:
            out_caps = params_to_caps_output(before_user["caps"],
                                             caps,
                                             deletion=(state == "absent"))
            out = json.dumps(dict(caps=out_caps))

        if rc == 0:
            after_user = json.loads(out)["caps"]
            after_user = sorted(after_user, key=lambda d: d["type"])
            diff["after"] = json.dumps(after_user, indent=4)
            changed = diff["before"] != diff["after"]
    else:
        out = "User {} doesn't exist".format(name)

    exit_module(
        module=module,
        out=out,
        rc=rc,
        cmd=cmd,
        err=err,
        startd=startd,
        changed=changed,
        diff=diff,
    )
Exemplo n.º 13
0
def main():
    module = AnsibleModule(
        argument_spec=yaml.safe_load(DOCUMENTATION)['options'],
        supports_check_mode=True,
        required_if=[('state', 'present', ['rule_type']),
                     ('rule_type', 'replicated',
                      ['bucket_root', 'bucket_type']),
                     ('rule_type', 'erasure', ['profile'])])

    # Gather module parameters in variables
    name = module.params.get('name')
    state = module.params.get('state')
    rule_type = module.params.get('rule_type')

    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_command(
            module, get_rule(module, container_image=container_image))
        if rc != 0:
            rc, cmd, out, err = exec_command(
                module, create_rule(module, container_image=container_image))
            changed = True
        else:
            rule = json.loads(out)
            if (rule['type'] == 1 and rule_type == 'erasure') or (
                    rule['type'] == 3 and rule_type == 'replicated'):
                module.fail_json(
                    msg="Can not convert crush rule {} to {}".format(
                        name, rule_type),
                    changed=False,
                    rc=1)

    elif state == "absent":
        rc, cmd, out, err = exec_command(
            module, get_rule(module, container_image=container_image))
        if rc == 0:
            rc, cmd, out, err = exec_command(
                module, remove_rule(module, container_image=container_image))
            changed = True
        else:
            rc = 0
            out = "Crush Rule {} doesn't exist".format(name)

    elif state == "info":
        rc, cmd, out, err = exec_command(
            module, get_rule(module, container_image=container_image))

    exit_module(module=module,
                out=out,
                rc=rc,
                cmd=cmd,
                err=err,
                startd=startd,
                changed=changed)