Ejemplo n.º 1
0
def main():
    argument_spec = dict(
        assets=dict(required=False),
        files=dict(required=False, default=[], type='list'),
        prevent=dict(required=False, default=[], type='list'),
        password_management=dict(required=False, default='default', choices=['default', 'random']),
    )

    module = TowerModule(argument_spec=argument_spec, supports_check_mode=False)

    if not HAS_TOWER_CLI:
        module.fail_json(msg='ansible-tower-cli required for this module')

    if not TOWER_CLI_HAS_EXPORT:
        module.fail_json(msg='ansible-tower-cli version does not support export')

    assets = module.params.get('assets')
    prevent = module.params.get('prevent')
    password_management = module.params.get('password_management')
    files = module.params.get('files')

    result = dict(
        changed=False,
        msg='',
        output='',
    )

    if not assets and not files:
        result['msg'] = "Assets or files must be specified"
        module.fail_json(**result)

    path = None
    if assets:
        # We got assets so we need to dump this out to a temp file and append that to files
        handle, path = mkstemp(prefix='', suffix='', dir='')
        with open(path, 'w') as f:
            f.write(assets)
        files.append(path)

    tower_auth = tower_auth_config(module)
    failed = False
    with settings.runtime_values(**tower_auth):
        try:
            sender = Sender(no_color=False)
            old_stdout = sys.stdout
            sys.stdout = captured_stdout = StringIO()
            try:
                sender.send(files, prevent, password_management)
            except TypeError as e:
                # Newer versions of TowerCLI require 4 parameters
                sender.send(files, prevent, [], password_management)

            if sender.error_messages > 0:
                failed = True
                result['msg'] = "Transfer Failed with %d errors" % sender.error_messages
            if sender.changed_messages > 0:
                result['changed'] = True
        except TowerCLIError as e:
            result['msg'] = e.message
            failed = True
        finally:
            if path is not None:
                os.remove(path)
            result['output'] = captured_stdout.getvalue().split("\n")
            sys.stdout = old_stdout

    # Return stdout so that module returns will work
    if failed:
        module.fail_json(**result)
    else:
        module.exit_json(**result)
Ejemplo n.º 2
0
def main():
    argument_spec = dict(
        name=dict(required=True),
        description=dict(required=False),
        inventory=dict(required=True),
        source=dict(required=True,
                    choices=SOURCE_CHOICES.keys()),
        credential=dict(required=False),
        source_vars=dict(required=False),
        timeout=dict(type='int', required=False),
        source_project=dict(required=False),
        source_path=dict(required=False),
        update_on_project_update=dict(type='bool', required=False),
        source_regions=dict(required=False),
        instance_filters=dict(required=False),
        group_by=dict(required=False),
        source_script=dict(required=False),
        overwrite=dict(type='bool', required=False),
        overwrite_vars=dict(type='bool', required=False),
        update_on_launch=dict(type='bool', required=False),
        update_cache_timeout=dict(type='int', required=False),
        state=dict(choices=['present', 'absent'], default='present'),
    )

    module = TowerModule(argument_spec=argument_spec, supports_check_mode=True)

    name = module.params.get('name')
    inventory = module.params.get('inventory')
    source = module.params.get('source')
    state = module.params.get('state')

    json_output = {'inventory_source': name, 'state': state}

    tower_auth = tower_auth_config(module)
    with settings.runtime_values(**tower_auth):
        tower_check_mode(module)
        inventory_source = tower_cli.get_resource('inventory_source')
        try:
            params = {}
            params['name'] = name
            params['source'] = source

            if module.params.get('description'):
                params['description'] = module.params.get('description')

            if module.params.get('credential'):
                credential_res = tower_cli.get_resource('credential')
                try:
                    credential = credential_res.get(
                        name=module.params.get('credential'))
                    params['credential'] = credential['id']
                except (exc.NotFound) as excinfo:
                    module.fail_json(
                        msg='Failed to update credential source,'
                        'credential not found: {0}'.format(excinfo),
                        changed=False
                    )

            if module.params.get('source_project'):
                source_project_res = tower_cli.get_resource('project')
                try:
                    source_project = source_project_res.get(
                        name=module.params.get('source_project'))
                    params['source_project'] = source_project['id']
                except (exc.NotFound) as excinfo:
                    module.fail_json(
                        msg='Failed to update source project,'
                        'project not found: {0}'.format(excinfo),
                        changed=False
                    )

            if module.params.get('source_script'):
                source_script_res = tower_cli.get_resource('inventory_script')
                try:
                    script = source_script_res.get(
                        name=module.params.get('source_script'))
                    params['source_script'] = script['id']
                except (exc.NotFound) as excinfo:
                    module.fail_json(
                        msg='Failed to update source script,'
                        'script not found: {0}'.format(excinfo),
                        changed=False
                    )

            try:
                inventory_res = tower_cli.get_resource('inventory')
                params['inventory'] = inventory_res.get(name=inventory)['id']
            except (exc.NotFound) as excinfo:
                module.fail_json(
                    msg='Failed to update inventory source, '
                    'inventory not found: {0}'.format(excinfo),
                    changed=False
                )

            for key in ('source_vars', 'timeout', 'source_path',
                        'update_on_project_update', 'source_regions',
                        'instance_filters', 'group_by', 'overwrite',
                        'overwrite_vars', 'update_on_launch',
                        'update_cache_timeout'):
                if module.params.get(key) is not None:
                    params[key] = module.params.get(key)

            if state == 'present':
                params['create_on_missing'] = True
                result = inventory_source.modify(**params)
                json_output['id'] = result['id']
            elif state == 'absent':
                params['fail_on_missing'] = False
                result = inventory_source.delete(**params)

        except (exc.ConnectionError, exc.BadRequest, exc.AuthError) as excinfo:
            module.fail_json(msg='Failed to update inventory source: \
                    {0}'.format(excinfo), changed=False)

    json_output['changed'] = result['changed']
    module.exit_json(**json_output)
Ejemplo n.º 3
0
def main():
    argument_spec = dict(
        name=dict(required=True),
        description=dict(required=False),
        extra_vars=dict(required=False),
        organization=dict(required=False),
        allow_simultaneous=dict(type='bool', required=False),
        schema=dict(required=False),
        survey=dict(required=False),
        survey_enabled=dict(type='bool', required=False),
        inventory=dict(required=False),
        ask_inventory=dict(type='bool', required=False),
        ask_extra_vars=dict(type='bool', required=False),
        state=dict(choices=['present', 'absent'], default='present'),
    )

    module = TowerModule(argument_spec=argument_spec,
                         supports_check_mode=False)

    name = module.params.get('name')
    state = module.params.get('state')

    schema = None
    if module.params.get('schema'):
        schema = module.params.get('schema')

    if schema and state == 'absent':
        module.fail_json(
            msg='Setting schema when state is absent is not allowed',
            changed=False)

    json_output = {'workflow_template': name, 'state': state}

    tower_auth = tower_auth_config(module)
    with settings.runtime_values(**tower_auth):
        tower_check_mode(module)
        wfjt_res = tower_cli.get_resource('workflow')
        params = {}
        params['name'] = name

        if module.params.get('description'):
            params['description'] = module.params.get('description')

        if module.params.get('organization'):
            organization_res = tower_cli.get_resource('organization')
            try:
                organization = organization_res.get(
                    name=module.params.get('organization'))
                params['organization'] = organization['id']
            except exc.NotFound as excinfo:
                module.fail_json(msg='Failed to update organization source,'
                                 'organization not found: {0}'.format(excinfo),
                                 changed=False)

        if module.params.get('survey'):
            params['survey_spec'] = module.params.get('survey')

        if module.params.get('ask_extra_vars'):
            params['ask_variables_on_launch'] = module.params.get(
                'ask_extra_vars')

        if module.params.get('ask_inventory'):
            params['ask_inventory_on_launch'] = module.params.get(
                'ask_inventory')

        for key in ('allow_simultaneous', 'extra_vars', 'inventory',
                    'survey_enabled', 'description'):
            if module.params.get(key):
                params[key] = module.params.get(key)

        try:
            if state == 'present':
                params['create_on_missing'] = True
                result = wfjt_res.modify(**params)
                json_output['id'] = result['id']
                if schema:
                    wfjt_res.schema(result['id'], schema)
            elif state == 'absent':
                params['fail_on_missing'] = False
                result = wfjt_res.delete(**params)
        except (exc.ConnectionError, exc.BadRequest, exc.AuthError) as excinfo:
            module.fail_json(msg='Failed to update workflow template: \
                    {0}'.format(excinfo),
                             changed=False)

    json_output['changed'] = result['changed']
    module.exit_json(**json_output)
Ejemplo n.º 4
0
def main():
    argument_spec = dict(
        workflow_template=dict(required=True),
        extra_vars=dict(required=False),
        wait=dict(required=False, default=True, type='bool'),
        timeout=dict(required=False, default=None, type='int'),
    )

    module = TowerModule(argument_spec=argument_spec, supports_check_mode=True)

    workflow_template = module.params.get('workflow_template')
    extra_vars = module.params.get('extra_vars')
    wait = module.params.get('wait')
    timeout = module.params.get('timeout')

    # If we are going to use this result to return we can consider ourselfs changed
    result = dict(changed=False, msg='initial message')

    tower_auth = tower_auth_config(module)
    with settings.runtime_values(**tower_auth):
        # First we will test the connection. This will be a test for both check and run mode
        # Note, we are not using the tower_check_mode method here because we want to do more than just a ping test
        # If we are in check mode we also want to validate that we can find the workflow
        try:
            ping_result = client.get('/ping').json()
            # Stuff the version into the results as an FYI
            result['tower_version'] = ping_result['version']
        except (ServerError, ConnectionError, BadRequest) as excinfo:
            result['msg'] = "Failed to reach Tower: {0}".format(excinfo)
            module.fail_json(**result)

        # Now that we know we can connect, lets verify that we can resolve the workflow_template
        try:
            workflow = tower_cli.get_resource("workflow").get(
                **{'name': workflow_template})
        except TowerCLIError as e:
            result['msg'] = "Failed to find workflow: {0}".format(e)
            module.fail_json(**result)

        # Since we were able to find the workflow, if we are in check mode we can return now
        if module.check_mode:
            result['msg'] = "Check mode passed"
            module.exit_json(**result)

        # We are no ready to run the workflow
        try:
            result['job_info'] = tower_cli.get_resource('workflow_job').launch(
                workflow_job_template=workflow['id'],
                monitor=False,
                wait=wait,
                timeout=timeout,
                extra_vars=extra_vars)
            if wait:
                # If we were waiting for a result we will fail if the workflow failed
                if result['job_info']['failed']:
                    result['msg'] = "Workflow execution failed"
                    module.fail_json(**result)
                else:
                    module.exit_json(**result)

            # We were not waiting and there should be no way we can make it here without the workflow fired off so we can return a success
            module.exit_json(**result)

        except TowerCLIError as e:
            result['msg'] = "Failed to execute workflow: {0}".format(e)
            module.fail_json(**result)