Esempio n. 1
0
def main():
    module = AnsibleModule(argument_spec=dict(
        state=dict(default='present',
                   choices=['present', 'absent'],
                   type='str'),
        login=dict(required=False, type='str'),
        password=dict(required=False, type='str'),
        topic=dict(required=False, type='str'),
        remoteci=dict(type='str'),
        url=dict(required=False, type='str'),
    ), )

    if not requests_found:
        module.fail_json(msg='The python requests module is required')

    topic_list = [module.params['topic'], os.getenv('DCI_TOPIC')]
    topic = next((item for item in topic_list if item is not None), None)

    login, password, url = get_details(module)
    if not login or not password:
        module.fail_json(msg='login and/or password have not been specified')

    ctx = dci_context.build_dci_context(url, login, password, 'ansible')

    topic_id = dci_topic.get(ctx, topic).json()['topic']['id']
    remoteci = dci_remoteci.get(ctx, module.params['remoteci']).json()
    remoteci_id = remoteci['remoteci']['id']

    dci_job.schedule(ctx, remoteci_id, topic_id=topic_id)
    jb = dci_job.get_full_data(ctx, ctx.last_job_id)
    jb['job_id'] = ctx.last_job_id

    module.exit_json(**jb)
Esempio n. 2
0
def get_keys(remoteci_id):
    context = build_signature_context()
    remoteci = dci_remoteci.get(context, remoteci_id).json()["remoteci"]
    res = dci_remoteci.refresh_keys(context,
                                    id=remoteci_id,
                                    etag=remoteci["etag"])

    if res.status_code == 201:
        return res.json()["keys"]
Esempio n. 3
0
def test_embed(dci_context):
    team_id = team.create(dci_context, name="teama").json()["team"]["id"]

    rci = remoteci.create(dci_context, name="boa", team_id=team_id).json()
    rci_id = rci["remoteci"]["id"]

    rci_with_embed = remoteci.get(dci_context, id=rci_id, embed="team").json()
    embed_team_id = rci_with_embed["remoteci"]["team"]["id"]

    assert team_id == embed_team_id
Esempio n. 4
0
def test_embed(dci_context):
    team_id = team.create(dci_context, name="teama").json()["team"]["id"]

    rci = remoteci.create(dci_context, name="boa", team_id=team_id).json()
    rci_id = rci["remoteci"]["id"]

    rci_with_embed = remoteci.get(dci_context, id=rci_id, embed=["team"]).json()
    embed_team_id = rci_with_embed["remoteci"]["team"]["id"]

    assert team_id == embed_team_id
def test_embed(dci_context):
    team_id = team.create(dci_context, name='teama').json()['team']['id']

    rci = remoteci.create(dci_context, name='boa', team_id=team_id).json()
    rci_id = rci['remoteci']['id']

    rci_with_embed = remoteci.get(dci_context,
                                  id=rci_id, embed='team').json()
    embed_team_id = rci_with_embed['remoteci']['team']['id']

    assert team_id == embed_team_id
Esempio n. 6
0
def show(context, id):
    """show(context, id)

    Show a Remote CI.

    >>> dcictl remoteci-show [OPTIONS]

    :param string id: ID of the remote CI to show [required]
    """
    result = remoteci.get(context, id=id)
    utils.format_output(result, context.format,
                        remoteci.RESOURCE[:-1], remoteci.TABLE_HEADERS)
Esempio n. 7
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            state=dict(default='present',
                       choices=['present', 'absent'],
                       type='str'),
            # Authentication related parameters
            #
            login=dict(required=False, type='str'),
            password=dict(required=False, type='str'),
            url=dict(required=False, type='str'),
            # Resource related parameters
            #
            id=dict(type='str'),
            topic=dict(required=False, type='str'),
            remoteci=dict(type='str'),
            comment=dict(type='str'),
            status=dict(type='str'),
            configuration=dict(type='dict'),
        ), )

    if not dciclient_found:
        module.fail_json(msg='The python dciclient module is required')

    topic_list = [module.params['topic'], os.getenv('DCI_TOPIC')]
    topic = next((item for item in topic_list if item is not None), None)

    login, password, url = get_details(module)
    if not login or not password:
        module.fail_json(msg='login and/or password have not been specified')

    ctx = dci_context.build_dci_context(url, login, password, 'Ansible')

    # Action required: Delete the job matching the job id
    # Endpoint called: /jobs/<job_id> DELETE via dci_job.delete()
    #
    # If the job exist and it has been succesfully deleted the changed is
    # set to true, else if the file does not exist changed is set to False
    if module.params['state'] == 'absent':
        if not module.params['id']:
            module.fail_json(msg='id parameter is required')
        res = dci_job.get(ctx, module.params['id'])
        if res.status_code not in [400, 401, 404, 422]:
            kwargs = {
                'id': module.params['id'],
                'etag': res.json()['job']['etag']
            }
            res = dci_job.delete(ctx, **kwargs)

    # Action required: Retrieve job informations
    # Endpoint called: /jobs/<job_id> GET via dci_job.get()
    #
    # Get job informations
    elif module.params[
            'id'] and not module.params['comment'] and not module.params[
                'status'] and not module.params['configuration']:
        res = dci_job.get(ctx, module.params['id'])

    # Action required: Update an existing job
    # Endpoint called: /jobs/<job_id> PUT via dci_job.update()
    #
    # Update the job with the specified characteristics.
    elif module.params['id']:
        res = dci_job.get(ctx, module.params['id'])
        if res.status_code not in [400, 401, 404, 422]:
            kwargs = {
                'id': module.params['id'],
                'etag': res.json()['job']['etag']
            }
            if module.params['comment']:
                kwargs['comment'] = module.params['comment']
            if module.params['status']:
                kwargs['status'] = module.params['status']
            if module.params['configuration']:
                kwargs['configuration'] = module.params['configuration']
            res = dci_job.update(ctx, **kwargs)

    # Action required: Schedule a new job
    # Endpoint called: /jobs/schedule POST via dci_job.schedule()
    #
    # Schedule a new job against the DCI Control-Server
    else:
        topic_id = dci_topic.get(ctx, topic).json()['topic']['id']
        remoteci = dci_remoteci.get(ctx, module.params['remoteci']).json()
        remoteci_id = remoteci['remoteci']['id']

        res = dci_job.schedule(ctx, remoteci_id, topic_id=topic_id)
        if res.status_code not in [400, 401, 404, 422]:
            res = dci_job.get_full_data(ctx, ctx.last_job_id)

    try:
        result = res.json()
        if res.status_code == 404:
            module.fail_json(msg='The resource does not exist')
        if res.status_code in [400, 401, 422]:
            result['changed'] = False
        else:
            result['changed'] = True
    except AttributeError:
        # Enter here if new job has been schedule, return of get_full_data is already json.
        result = res
        result['changed'] = True
        result['job_id'] = ctx.last_job_id
    except:
        result = {}
        result['changed'] = True

    module.exit_json(**result)
Esempio n. 8
0
def remoteci_api_secret(dci_context, remoteci_id):
    rci = api_remoteci.get(dci_context, remoteci_id).json()
    return rci["remoteci"]["api_secret"]
Esempio n. 9
0
def show(context, id):
    result = remoteci.get(context, id=id)
    utils.format_output(result.json(), context.format,
                        remoteci.RESOURCE[:-1], remoteci.TABLE_HEADERS)
Esempio n. 10
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            state=dict(default='present', choices=['present', 'absent'], type='str'),
            # Authentication related parameters
            #
            login=dict(required=False, type='str'),
            password=dict(required=False, type='str'),
            url=dict(required=False, type='str'),
            # Resource related parameters
            #
            id=dict(type='str'),
            name=dict(type='str'),
            data=dict(type='dict'),
            active=dict(type='bool'),
            team_id=dict(type='str'),
        ),
    )

    if not dciclient_found:
        module.fail_json(msg='The python dciclient module is required')

    login, password, url = get_details(module)
    if not login or not password:
        module.fail_json(msg='login and/or password have not been specified')

    ctx = dci_context.build_dci_context(url, login, password, 'Ansible')

    # Action required: Delete the remoteci matching remoteci id
    # Endpoint called: /remotecis/<remoteci_id> DELETE via dci_remoteci.delete()
    #
    # If the remoteci exists and it has been succesfully deleted the changed is
    # set to true, else if the remoteci does not exist changed is set to False
    if module.params['state'] == 'absent':
        if not module.params['id']:
            module.fail_json(msg='id parameter is required')
        res = dci_remoteci.get(ctx, module.params['id'])
        if res.status_code not in [400, 401, 404, 422]:
            kwargs = {
                'id': module.params['id'],
                'etag': res.json()['remoteci']['etag']
            }
            res = dci_remoteci.delete(ctx, **kwargs)

    # Action required: Retrieve remoteci informations
    # Endpoint called: /remotecis/<remoteci_id> GET via dci_remoteci.get()
    #
    # Get remoteci informations
    elif module.params['id'] and not module.params['name'] and not module.params['data'] and not module.params['team_id'] and module.params['active'] is None:
        res = dci_remoteci.get(ctx, module.params['id'])

    # Action required: Update an existing remoteci
    # Endpoint called: /remotecis/<remoteci_id> PUT via dci_remoteci.update()
    #
    # Update the remoteci with the specified characteristics.
    elif module.params['id']:
        res = dci_remoteci.get(ctx, module.params['id'])
        if res.status_code not in [400, 401, 404, 422]:
            kwargs = {
                'id': module.params['id'],
                'etag': res.json()['remoteci']['etag']
            }
            if module.params['name']:
                kwargs['name'] = module.params['name']
            if module.params['data']:
                kwargs['data'] = module.params['data']
            if module.params['team_id']:
                kwargs['team_id'] = module.params['team_id']
            if module.params['active'] is not None:
                kwargs['active'] = module.params['active']
            open('/tmp/tuiti', 'w').write(str(kwargs.keys()))
            res = dci_remoteci.update(ctx, **kwargs)

    # Action required: Create a remoteci with the specified content
    # Endpoint called: /remotecis POST via dci_remoteci.create()
    #
    # Create the new remoteci.
    else:
        if not module.params['name']:
            module.fail_json(msg='name parameter must be specified')
        if not module.params['team_id']:
            module.fail_json(msg='team_id parameter must be specified')

        kwargs = {
            'name': module.params['name'],
            'team_id': module.params['team_id']
        }
        if module.params['data']:
            kwargs['data'] = module.params['data']
        if module.params['active'] is not None:
            kwargs['active'] = module.params['active']

        res = dci_remoteci.create(ctx, **kwargs)

    try:
        result = res.json()
        if res.status_code == 404:
            module.fail_json(msg='The resource does not exist')
        if res.status_code == 422:
            result['changed'] = False
        else:
            result['changed'] = True
    except:
        result = {}
        result['changed'] = True

    module.exit_json(**result)
Esempio n. 11
0
def main(argv=None):
    logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
    parser = argparse.ArgumentParser()
    parser.add_argument('--topic')
    parser.add_argument('--config', default='/etc/dci/dci_agent.yaml')
    parser.add_argument('--version',
                        action='version',
                        version=('dci-agent %s' % version))
    args = parser.parse_args(argv)

    dci_conf = load_config(args.config)
    ctx = get_dci_context(**dci_conf['auth'])
    topic_name = args.topic if args.topic else dci_conf['topic']
    topic = dci_topic.get(ctx, topic_name).json()['topic']
    remoteci = dci_remoteci.get(ctx, dci_conf['remoteci']).json()['remoteci']
    r = dci_job.schedule(ctx, remoteci['id'], topic_id=topic['id'])
    if r.status_code == 412:
        logging.info('Nothing to do')
        exit(0)
    elif r.status_code != 201:
        logging.error('Unexpected code: %d' % r.status_code)
        logging.error(r.text)
        exit(1)
    components = dci_job.get_components(ctx,
                                        ctx.last_job_id).json()['components']
    logging.debug(components)

    try:
        prepare_local_mirror(ctx, dci_conf['mirror']['directory'],
                             dci_conf['mirror']['url'], components)
        dci_jobstate.create(ctx, 'pre-run', 'director node provisioning',
                            ctx.last_job_id)
        for c in dci_conf['hooks']['provisioning']:
            dci_helper.run_command(ctx, c, shell=True)
        init_undercloud_host(dci_conf['undercloud_ip'],
                             dci_conf['key_filename'])
        dci_jobstate.create(ctx, 'running', 'undercloud deployment',
                            ctx.last_job_id)
        for c in dci_conf['hooks']['undercloud']:
            dci_helper.run_command(ctx, c, shell=True)
        dci_jobstate.create(ctx, 'running', 'overcloud deployment',
                            ctx.last_job_id)
        for c in dci_conf['hooks']['overcloud']:
            dci_helper.run_command(ctx, c, shell=True)
        dci_tripleo_helper.run_tests(ctx,
                                     undercloud_ip=dci_conf['undercloud_ip'],
                                     key_filename=dci_conf['key_filename'],
                                     remoteci_id=remoteci['id'],
                                     stack_name=dci_conf.get(
                                         'stack_name', 'overcloud'))
        final_status = 'success'
        backtrace = ''
        msg = ''
    except Exception as e:
        final_status = 'failure'
        backtrace = traceback.format_exc()
        msg = str(e)
        pass

    # Teardown should happen even in case of failure and should not make the
    # agent run fail.
    try:
        teardown_commands = dci_conf['hooks'].get('teardown')
        if teardown_commands:
            dci_jobstate.create(ctx, 'post-run', 'teardown', ctx.last_job_id)
            for c in teardown_commands:
                dci_helper.run_command(ctx, c, shell=True)
    except Exception as e:
        backtrace_teardown = str(e) + '\n' + traceback.format_exc()
        logging.error(backtrace_teardown)
        dci_file.create(ctx,
                        'backtrace_teardown',
                        backtrace_teardown,
                        mime='text/plain',
                        jobstate_id=ctx.last_jobstate_id)
        pass

    dci_jobstate.create(ctx, final_status, msg, ctx.last_job_id)
    logging.info('Final status: ' + final_status)
    if backtrace:
        logging.error(backtrace)
        dci_file.create(ctx,
                        'backtrace',
                        backtrace,
                        mime='text/plain',
                        jobstate_id=ctx.last_jobstate_id)
    sys.exit(0 if final_status == 'success' else 1)
Esempio n. 12
0
def show(context, args):
    return remoteci.get(context, id=args.id)