Exemple #1
0
def main():
    argument_spec = tower_argument_spec()
    argument_spec.update(dict(
        job_id=dict(type='int', required=True),
        fail_if_not_running=dict(type='bool', default=False),
    ))

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

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

    job_id = module.params.get('job_id')
    json_output = {}

    tower_auth = tower_auth_config(module)
    with settings.runtime_values(**tower_auth):
        tower_check_mode(module)
        job = tower_cli.get_resource('job')
        params = module.params.copy()

        try:
            result = job.cancel(job_id, **params)
            json_output['id'] = job_id
        except (exc.ConnectionError, exc.BadRequest, exc.TowerCLIError) as excinfo:
            module.fail_json(msg='Unable to cancel job_id/{0}: {1}'.format(job_id, excinfo), changed=False)

    json_output['changed'] = result['changed']
    json_output['status'] = result['status']
    module.exit_json(**json_output)
def main():
    argument_spec = tower_argument_spec()
    argument_spec.update(dict(
        name=dict(required=True),
        description=dict(),
        state=dict(choices=['present', 'absent'], default='present'),
    ))

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

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

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

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

    tower_auth = tower_auth_config(module)
    with settings.runtime_values(**tower_auth):
        tower_check_mode(module)
        organization = tower_cli.get_resource('organization')
        try:
            if state == 'present':
                result = organization.modify(name=name, description=description, create_on_missing=True)
                json_output['id'] = result['id']
            elif state == 'absent':
                result = organization.delete(name=name)
        except (exc.ConnectionError, exc.BadRequest) as excinfo:
            module.fail_json(msg='Failed to update the organization: {0}'.format(excinfo), changed=False)

    json_output['changed'] = result['changed']
    module.exit_json(**json_output)
def main():
    argument_spec = tower_argument_spec()
    argument_spec.update(dict(
        name=dict(required=True),
        description=dict(),
        state=dict(choices=['present', 'absent'], default='present'),
    ))

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

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

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

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

    tower_auth = tower_auth_config(module)
    with settings.runtime_values(**tower_auth):
        tower_check_mode(module)
        organization = tower_cli.get_resource('organization')
        try:
            if state == 'present':
                result = organization.modify(name=name, description=description, create_on_missing=True)
                json_output['id'] = result['id']
            elif state == 'absent':
                result = organization.delete(name=name)
        except (exc.ConnectionError, exc.BadRequest) as excinfo:
            module.fail_json(msg='Failed to update the organization: {0}'.format(excinfo), changed=False)

    json_output['changed'] = result['changed']
    module.exit_json(**json_output)
def main():
    argument_spec = tower_argument_spec()
    argument_spec.update(dict(
        name=dict(required=True),
        description=dict(),
        job_type=dict(choices=['run', 'check', 'scan'], required=True),
        inventory=dict(),
        project=dict(required=True),
        playbook=dict(required=True),
        machine_credential=dict(),
        cloud_credential=dict(),
        network_credential=dict(),
        forks=dict(type='int'),
        limit=dict(),
        verbosity=dict(choices=['verbose', 'debug']),
        job_tags=dict(),
        skip_tags=dict(),
        host_config_key=dict(),
        extra_vars_path=dict(type='path', required=False),
        ask_extra_vars=dict(type='bool', default=False),
        ask_limit=dict(type='bool', default=False),
        ask_tags=dict(type='bool', default=False),
        ask_job_type=dict(type='bool', default=False),
        ask_inventory=dict(type='bool', default=False),
        ask_credential=dict(type='bool', default=False),
        become_enabled=dict(type='bool', default=False),
        state=dict(choices=['present', 'absent'], default='present'),
    ))

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

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

    name = module.params.get('name')
    state = module.params.pop('state')
    json_output = {'job_template': name, 'state': state}

    tower_auth = tower_auth_config(module)
    with settings.runtime_values(**tower_auth):
        tower_check_mode(module)
        jt = tower_cli.get_resource('job_template')

        params = update_resources(module, module.params)
        params = update_fields(params)
        params['create_on_missing'] = True

        try:
            if state == 'present':
                result = jt.modify(**params)
                json_output['id'] = result['id']
            elif state == 'absent':
                result = jt.delete(**params)
        except (exc.ConnectionError, exc.BadRequest, exc.NotFound) as excinfo:
            module.fail_json(msg='Failed to update job template: {0}'.format(excinfo), changed=False)

    json_output['changed'] = result['changed']
    module.exit_json(**json_output)
def main():
    argument_spec = tower_argument_spec()
    argument_spec.update(dict(
        name=dict(required=True),
        description=dict(),
        job_type=dict(choices=['run', 'check', 'scan'], required=True),
        inventory=dict(),
        project=dict(required=True),
        playbook=dict(required=True),
        machine_credential=dict(),
        cloud_credential=dict(),
        network_credential=dict(),
        forks=dict(type='int'),
        limit=dict(),
        verbosity=dict(choices=['verbose', 'debug']),
        job_tags=dict(),
        skip_tags=dict(),
        host_config_key=dict(),
        extra_vars_path=dict(type='path', required=False),
        ask_extra_vars=dict(type='bool', default=False),
        ask_limit=dict(type='bool', default=False),
        ask_tags=dict(type='bool', default=False),
        ask_job_type=dict(type='bool', default=False),
        ask_inventory=dict(type='bool', default=False),
        ask_credential=dict(type='bool', default=False),
        become_enabled=dict(type='bool', default=False),
        state=dict(choices=['present', 'absent'], default='present'),
    ))

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

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

    name = module.params.get('name')
    state = module.params.get('state')
    json_output = {'job_template': name, 'state': state}

    tower_auth = tower_auth_config(module)
    with settings.runtime_values(**tower_auth):
        tower_check_mode(module)
        jt = tower_cli.get_resource('job_template')

        params = update_resources(module, module.params)
        params = update_fields(params)
        params['create_on_missing'] = True

        try:
            if state == 'present':
                result = jt.modify(**params)
                json_output['id'] = result['id']
            elif state == 'absent':
                result = jt.delete(**params)
        except (exc.ConnectionError, exc.BadRequest, exc.NotFound) as excinfo:
            module.fail_json(msg='Failed to update job template: {0}'.format(excinfo), changed=False)

    json_output['changed'] = result['changed']
    module.exit_json(**json_output)
Exemple #6
0
def main():
    argument_spec = tower_argument_spec()
    argument_spec.update(
        dict(
            username=dict(required=True),
            first_name=dict(),
            last_name=dict(),
            password=dict(no_log=True),
            email=dict(required=True),
            superuser=dict(type='bool', default=False),
            auditor=dict(type='bool', default=False),
            state=dict(choices=['present', 'absent'], default='present'),
        ))

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

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

    username = module.params.get('username')
    first_name = module.params.get('first_name')
    last_name = module.params.get('last_name')
    password = module.params.get('password')
    email = module.params.get('email')
    superuser = module.params.get('superuser')
    auditor = module.params.get('auditor')
    state = module.params.get('state')

    json_output = {'username': username, 'state': state}

    tower_auth = tower_auth_config(module)
    with settings.runtime_values(**tower_auth):
        tower_check_mode(module)
        user = tower_cli.get_resource('user')
        try:
            if state == 'present':
                result = user.modify(username=username,
                                     first_name=first_name,
                                     last_name=last_name,
                                     email=email,
                                     password=password,
                                     is_superuser=superuser,
                                     is_auditor=auditor,
                                     create_on_missing=True)
                json_output['id'] = result['id']
            elif state == 'absent':
                result = user.delete(username=username)
        except (exc.ConnectionError, exc.BadRequest) as excinfo:
            module.fail_json(
                msg='Failed to update the user: {0}'.format(excinfo),
                changed=False)

    json_output['changed'] = result['changed']
    module.exit_json(**json_output)
def main():
    argument_spec = tower_argument_spec()
    argument_spec.update(
        dict(
            job_id=dict(type='int', required=True),
            timeout=dict(type='int'),
            min_interval=dict(type='float', default=1),
            max_interval=dict(type='float', default=30),
        ))

    module = AnsibleModule(argument_spec, supports_check_mode=True)

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

    json_output = {}
    fail_json = None

    tower_auth = tower_auth_config(module)
    with settings.runtime_values(**tower_auth):
        tower_check_mode(module)
        job = tower_cli.get_resource('job')
        params = module.params.copy()

        # tower-cli gets very noisy when monitoring.
        # We pass in our our outfile to suppress the out during our monitor call.
        outfile = StringIO()
        params['outfile'] = outfile

        job_id = params.get('job_id')
        try:
            result = job.monitor(job_id, **params)
        except exc.Timeout as excinfo:
            result = job.status(job_id)
            result['id'] = job_id
            json_output['msg'] = 'Timeout waiting for job to finish.'
            json_output['timeout'] = True
        except exc.NotFound as excinfo:
            fail_json = dict(
                msg='Unable to wait, no job_id {0} found: {1}'.format(
                    job_id, excinfo),
                changed=False)
        except (exc.ConnectionError, exc.BadRequest) as excinfo:
            fail_json = dict(msg='Unable to wait for job: {0}'.format(excinfo),
                             changed=False)

    if fail_json is not None:
        module.fail_json(**fail_json)

    json_output['success'] = True
    for k in ('id', 'status', 'elapsed', 'started', 'finished'):
        json_output[k] = result.get(k)

    module.exit_json(**json_output)
def main():
    argument_spec = tower_argument_spec()
    argument_spec.update(dict(
        job_id=dict(type='int', required=True),
        timeout=dict(type='int'),
        min_interval=dict(type='float', default=1),
        max_interval=dict(type='float', default=30),
    ))

    module = AnsibleModule(
        argument_spec,
        supports_check_mode=True
    )

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

    json_output = {}
    fail_json = None

    tower_auth = tower_auth_config(module)
    with settings.runtime_values(**tower_auth):
        tower_check_mode(module)
        job = tower_cli.get_resource('job')
        params = module.params.copy()

        # tower-cli gets very noisy when monitoring.
        # We pass in our our outfile to suppress the out during our monitor call.
        outfile = StringIO()
        params['outfile'] = outfile

        job_id = params.get('job_id')
        try:
            result = job.monitor(job_id, **params)
        except exc.Timeout as excinfo:
            result = job.status(job_id)
            result['id'] = job_id
            json_output['msg'] = 'Timeout waiting for job to finish.'
            json_output['timeout'] = True
        except exc.NotFound as excinfo:
            fail_json = dict(msg='Unable to wait, no job_id {0} found: {1}'.format(job_id, excinfo), changed=False)
        except (exc.ConnectionError, exc.BadRequest) as excinfo:
            fail_json = dict(msg='Unable to wait for job: {0}'.format(excinfo), changed=False)

    if fail_json is not None:
        module.fail_json(**fail_json)

    json_output['success'] = True
    for k in ('id', 'status', 'elapsed', 'started', 'finished'):
        json_output[k] = result.get(k)

    module.exit_json(**json_output)
Exemple #9
0
def main():
    argument_spec = tower_argument_spec()
    argument_spec.update(
        dict(
            job_template=dict(required=True),
            job_type=dict(choices=['run', 'check', 'scan']),
            inventory=dict(),
            credential=dict(),
            limit=dict(),
            tags=dict(type='list'),
            extra_vars=dict(type='list'),
        ))

    module = AnsibleModule(argument_spec, supports_check_mode=True)

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

    json_output = {}
    tags = module.params.get('tags')

    tower_auth = tower_auth_config(module)
    with settings.runtime_values(**tower_auth):
        tower_check_mode(module)
        try:
            params = module.params.copy()
            if isinstance(tags, list):
                params['tags'] = ','.join(tags)
            job = tower_cli.get_resource('job')

            lookup_fields = ('job_template', 'inventory', 'credential')
            for field in lookup_fields:
                try:
                    name = params.pop(field)
                    result = tower_cli.get_resource(field).get(name=name)
                    params[field] = result['id']
                except exc.NotFound as excinfo:
                    module.fail_json(
                        msg='Unable to launch job, {0}/{1} was not found: {2}'.
                        format(field, name, excinfo),
                        changed=False)

            result = job.launch(no_input=True, **params)
            json_output['id'] = result['id']
            json_output['status'] = result['status']
        except (exc.ConnectionError, exc.BadRequest) as excinfo:
            module.fail_json(msg='Unable to launch job: {0}'.format(excinfo),
                             changed=False)

    json_output['changed'] = result['changed']
    module.exit_json(**json_output)
def main():
    argument_spec = tower_argument_spec()
    argument_spec.update(
        dict(ldap_server_protocol=dict(type='str', default='ldaps'),
             ldap_server_name=dict(type='str'),
             ldap_server_port=dict(type='int', default=636),
             ldap_bind_dn=dict(type='str'),
             ldap_bind_password=dict(type='str', no_log=True),
             ldap_start_tls=dict(type='bool', default=False),
             ldap_user_search=dict(type='list'),
             ldap_group_search=dict(type='str'),
             ldap_group_type=dict(type='str',
                                  choices=['active_directory', 'open_ldap'],
                                  default='active_directory'),
             ldap_superuser=dict(type='str'),
             ldap_organization_map=dict(type='list'),
             ldap_team_map=dict(type='list'),
             state=dict(type='str',
                        choices=['present', 'absent'],
                        default='present'),
             ldap_user_attr_map=transform_ldap_user_attr_map()))
    module = AnsibleModule(argument_spec=argument_spec,
                           supports_check_mode=True)
    if not HAS_TOWER_CLI:
        module.fail_json(msg="ansible-tower-cli required for this module")
    tower_auth = tower_auth_config(module)
    with settings.runtime_values(**tower_auth):
        state = module.params.get('state')
        json_output = {}
        get_ldap_values(module)
        if state == 'absent':
            clear_all_ldap_config(module, module.check_mode)
            if module.changed_values:
                json_output['changed'] = True
                json_output['msg'] = (
                    'The following LDAP settings were cleared %s' %
                    module.changed_values)
            else:
                json_output['changed'] = False
                json_output['msg'] = 'LDAP settings already cleared'
        else:
            modify_ldap_config(module, module.check_mode)
            if module.changed_values:
                json_output['changed'] = True
                json_output['msg'] = (
                    'The following LDAP settings were changed %s' %
                    module.changed_values)
            else:
                json_output['changed'] = False

        module.exit_json(**json_output)
Exemple #11
0
def main():

    argument_spec = tower_argument_spec()
    argument_spec.update(
        dict(
            user=dict(),
            team=dict(),
            role=dict(choices=[
                "admin", "read", "member", "execute", "adhoc", "update", "use",
                "auditor"
            ]),
            target_team=dict(),
            inventory=dict(),
            job_template=dict(),
            credential=dict(),
            organization=dict(),
            project=dict(),
            state=dict(choices=['present', 'absent'], default='present'),
        ))

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

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

    role_type = module.params.pop('role')
    state = module.params.get('state')

    json_output = {'role': role_type, 'state': state}

    tower_auth = tower_auth_config(module)
    with settings.runtime_values(**tower_auth):
        tower_check_mode(module)
        role = tower_cli.get_resource('role')

        params = update_resources(module, module.params)
        params['type'] = role_type

        try:
            if state == 'present':
                result = role.grant(**params)
                json_output['id'] = result['id']
            elif state == 'absent':
                result = role.revoke(**params)
        except (exc.ConnectionError, exc.BadRequest, exc.NotFound) as excinfo:
            module.fail_json(msg='Failed to update role: {0}'.format(excinfo),
                             changed=False)

    json_output['changed'] = result['changed']
    module.exit_json(**json_output)
Exemple #12
0
def main():
    argument_spec = tower_argument_spec()
    argument_spec.update(dict(
        name=dict(required=True),
        description=dict(),
        inventory=dict(required=True),
        enabled=dict(type='bool', default=True),
        variables=dict(),
        state=dict(choices=['present', 'absent'], default='present'),
    ))
    module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)

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

    name = module.params.get('name')
    description = module.params.get('description')
    inventory = module.params.get('inventory')
    enabled = module.params.get('enabled')
    state = module.params.get('state')

    variables = module.params.get('variables')
    if variables:
        if variables.startswith('@'):
            filename = os.path.expanduser(variables[1:])
            variables = module.contents_from_file(filename)

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

    tower_auth = tower_auth_config(module)
    with settings.runtime_values(**tower_auth):
        tower_check_mode(module)
        host = tower_cli.get_resource('host')

        try:
            inv_res = tower_cli.get_resource('inventory')
            inv = inv_res.get(name=inventory)

            if state == 'present':
                result = host.modify(name=name, inventory=inv['id'], enabled=enabled,
                                     variables=variables, description=description, create_on_missing=True)
                json_output['id'] = result['id']
            elif state == 'absent':
                result = host.delete(name=name, inventory=inv['id'])
        except (exc.NotFound) as excinfo:
            module.fail_json(msg='Failed to update host, inventory not found: {0}'.format(excinfo), changed=False)
        except (exc.ConnectionError, exc.BadRequest) as excinfo:
            module.fail_json(msg='Failed to update host: {0}'.format(excinfo), changed=False)

    json_output['changed'] = result['changed']
    module.exit_json(**json_output)
def main():
    argument_spec = tower_argument_spec()
    argument_spec.update(dict(
        job_template=dict(required=True),
        job_type=dict(choices=['run', 'check', 'scan']),
        inventory=dict(),
        credential=dict(),
        limit=dict(),
        tags=dict(type='list'),
        extra_vars=dict(type='list'),
    ))

    module = AnsibleModule(
        argument_spec,
        supports_check_mode=True
    )

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

    json_output = {}
    tags = module.params.get('tags')

    tower_auth = tower_auth_config(module)
    with settings.runtime_values(**tower_auth):
        tower_check_mode(module)
        try:
            params = module.params.copy()
            if isinstance(tags, list):
                params['tags'] = ','.join(tags)
            job = tower_cli.get_resource('job')

            lookup_fields = ('job_template', 'inventory', 'credential')
            for field in lookup_fields:
                try:
                    name = params.pop(field)
                    result = tower_cli.get_resource(field).get(name=name)
                    params[field] = result['id']
                except exc.NotFound as excinfo:
                    module.fail_json(msg='Unable to launch job, {0}/{1} was not found: {2}'.format(field, name, excinfo), changed=False)

            result = job.launch(no_input=True, **params)
            json_output['id'] = result['id']
            json_output['status'] = result['status']
        except (exc.ConnectionError, exc.BadRequest) as excinfo:
            module.fail_json(msg='Unable to launch job: {0}'.format(excinfo), changed=False)

    json_output['changed'] = result['changed']
    module.exit_json(**json_output)
Exemple #14
0
def main():
    argument_spec = tower_argument_spec()
    argument_spec.update(dict(
        username=dict(required=True),
        first_name=dict(),
        last_name=dict(),
        password=dict(no_log=True),
        email=dict(required=True),
        superuser=dict(type='bool', default=False),
        auditor=dict(type='bool', default=False),
        state=dict(choices=['present', 'absent'], default='present'),
    ))

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

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

    username = module.params.get('username')
    first_name = module.params.get('first_name')
    last_name = module.params.get('last_name')
    password = module.params.get('password')
    email = module.params.get('email')
    superuser = module.params.get('superuser')
    auditor = module.params.get('auditor')
    state = module.params.get('state')

    json_output = {'username': username, 'state': state}

    tower_auth = tower_auth_config(module)
    with settings.runtime_values(**tower_auth):
        tower_check_mode(module)
        user = tower_cli.get_resource('user')
        try:
            if state == 'present':
                result = user.modify(username=username, first_name=first_name, last_name=last_name,
                                     email=email, password=password, is_superuser=superuser,
                                     is_auditor=auditor, create_on_missing=True)
                json_output['id'] = result['id']
            elif state == 'absent':
                result = user.delete(username=username)
        except (exc.ConnectionError, exc.BadRequest) as excinfo:
            module.fail_json(msg='Failed to update the user: {0}'.format(excinfo), changed=False)

    json_output['changed'] = result['changed']
    module.exit_json(**json_output)
Exemple #15
0
def main():

    argument_spec = tower_argument_spec()
    argument_spec.update(dict(
        user=dict(),
        team=dict(),
        role=dict(choices=["admin", "read", "member", "execute", "adhoc", "update", "use", "auditor"]),
        target_team=dict(),
        inventory=dict(),
        job_template=dict(),
        credential=dict(),
        organization=dict(),
        project=dict(),
        state=dict(choices=['present', 'absent'], default='present'),
    ))

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

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

    role_type = module.params.pop('role')
    state = module.params.get('state')

    json_output = {'role': role_type, 'state': state}

    tower_auth = tower_auth_config(module)
    with settings.runtime_values(**tower_auth):
        tower_check_mode(module)
        role = tower_cli.get_resource('role')

        params = update_resources(module, module.params)
        params['type'] = role_type

        try:
            if state == 'present':
                result = role.grant(**params)
                json_output['id'] = result['id']
            elif state == 'absent':
                result = role.revoke(**params)
        except (exc.ConnectionError, exc.BadRequest, exc.NotFound) as excinfo:
            module.fail_json(msg='Failed to update role: {0}'.format(excinfo), changed=False)

    json_output['changed'] = result['changed']
    module.exit_json(**json_output)
Exemple #16
0
def main():
    argument_spec = tower_argument_spec()
    argument_spec.update(
        dict(
            status=dict(choices=[
                'pending', 'waiting', 'running', 'error', 'failed', 'canceled',
                'successful'
            ]),
            page=dict(type='int'),
            all_pages=dict(type='bool', default=False),
            query=dict(type='dict'),
        ))

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

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

    json_output = {}

    query = module.params.get('query')
    status = module.params.get('status')
    page = module.params.get('page')
    all_pages = module.params.get('all_pages')

    tower_auth = tower_auth_config(module)
    with settings.runtime_values(**tower_auth):
        tower_check_mode(module)
        try:
            job = tower_cli.get_resource('job')
            params = {'status': status, 'page': page, 'all_pages': all_pages}
            if query:
                params['query'] = query.items()
            json_output = job.list(**params)
        except (exc.ConnectionError, exc.BadRequest) as excinfo:
            module.fail_json(msg='Failed to list jobs: {0}'.format(excinfo),
                             changed=False)

    module.exit_json(**json_output)
def main():
    argument_spec = tower_argument_spec()
    argument_spec.update(dict(
        status=dict(choices=['pending', 'waiting', 'running', 'error', 'failed', 'canceled', 'successful']),
        page=dict(type='int'),
        all_pages=dict(type='bool', default=False),
        query=dict(type='dict'),
    ))

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

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

    json_output = {}

    query = module.params.get('query')
    status = module.params.get('status')
    page = module.params.get('page')
    all_pages = module.params.get('all_pages')

    tower_auth = tower_auth_config(module)
    with settings.runtime_values(**tower_auth):
        tower_check_mode(module)
        try:
            job = tower_cli.get_resource('job')
            params = {'status': status, 'page': page, 'all_pages': all_pages}
            if query:
                params['query'] = query.items()
            json_output = job.list(**params)
        except (exc.ConnectionError, exc.BadRequest) as excinfo:
            module.fail_json(msg='Failed to list jobs: {0}'.format(excinfo), changed=False)

    module.exit_json(**json_output)
Exemple #18
0
def main():
    argument_spec = tower_argument_spec()
    argument_spec.update(dict(
        name=dict(),
        description=dict(),
        organization=dict(),
        scm_type=dict(choices=['manual', 'git', 'hg', 'svn'], default='manual'),
        scm_url=dict(),
        scm_branch=dict(),
        scm_credential=dict(),
        scm_clean=dict(type='bool', default=False),
        scm_delete_on_update=dict(type='bool', default=False),
        scm_update_on_launch=dict(type='bool', default=False),
        local_path=dict(),

        state=dict(choices=['present', 'absent'], default='present'),
    ))

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

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

    name = module.params.get('name')
    description = module.params.get('description')
    organization = module.params.get('organization')
    scm_type = module.params.get('scm_type')
    if scm_type == "manual":
        scm_type = ""
    scm_url = module.params.get('scm_url')
    local_path = module.params.get('local_path')
    scm_branch = module.params.get('scm_branch')
    scm_credential = module.params.get('scm_credential')
    scm_clean = module.params.get('scm_clean')
    scm_delete_on_update = module.params.get('scm_delete_on_update')
    scm_update_on_launch = module.params.get('scm_update_on_launch')
    state = module.params.get('state')

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

    tower_auth = tower_auth_config(module)
    with settings.runtime_values(**tower_auth):
        tower_check_mode(module)
        project = tower_cli.get_resource('project')
        try:
            if state == 'present':
                try:
                    org_res = tower_cli.get_resource('organization')
                    org = org_res.get(name=organization)
                except (exc.NotFound) as excinfo:
                    module.fail_json(msg='Failed to update project, organization not found: {0}'.format(organization), changed=False)
                try:
                    cred_res = tower_cli.get_resource('credential')
                    cred = cred_res.get(name=scm_credential)
                except (exc.NotFound) as excinfo:
                    module.fail_json(msg='Failed to update project, credential not found: {0}'.format(scm_credential), changed=False)

                result = project.modify(name=name, description=description,
                                        organization=org['id'],
                                        scm_type=scm_type, scm_url=scm_url, local_path=local_path,
                                        scm_branch=scm_branch, scm_clean=scm_clean, credential=cred['id'],
                                        scm_delete_on_update=scm_delete_on_update,
                                        scm_update_on_launch=scm_update_on_launch,
                                        create_on_missing=True)
                json_output['id'] = result['id']
            elif state == 'absent':
                result = project.delete(name=name)
        except (exc.ConnectionError, exc.BadRequest) as excinfo:
            module.fail_json(msg='Failed to update project: {0}'.format(excinfo), changed=False)

    json_output['changed'] = result['changed']
    module.exit_json(**json_output)
Exemple #19
0
def main():

    argument_spec = tower_argument_spec()
    argument_spec.update(dict(
        name=dict(required=True),
        user=dict(),
        team=dict(),
        kind=dict(required=True,
                  choices=["ssh", "net", "scm", "aws", "rax", "vmware", "satellite6",
                           "cloudforms", "gce", "azure", "azure_rm", "openstack"]),
        host=dict(),
        username=dict(),
        password=dict(no_log=True),
        ssh_key_data=dict(no_log=True),
        ssh_key_unlock=dict(no_log=True),
        authorize=dict(type='bool', default=False),
        authorize_password=dict(no_log=True),
        client=dict(),
        secret=dict(),
        tenant=dict(),
        subscription=dict(),
        domain=dict(),
        become_method=dict(),
        become_username=dict(),
        become_password=dict(no_log=True),
        vault_password=dict(no_log=True),
        description=dict(),
        organization=dict(required=True),
        project=dict(),
        state=dict(choices=['present', 'absent'], default='present'),
    ))

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

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

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

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

    tower_auth = tower_auth_config(module)
    with settings.runtime_values(**tower_auth):
        tower_check_mode(module)
        credential = tower_cli.get_resource('credential')
        try:
            params = module.params.copy()
            params['create_on_missing'] = True

            if organization:
                org_res = tower_cli.get_resource('organization')
                org = org_res.get(name=organization)
                params['organization'] = org['id']

            if params['ssh_key_data']:
                filename = params['ssh_key_data']
                filename = os.path.expanduser(filename)
                if not os.path.exists(filename):
                    module.fail_json(msg='file not found: %s' % filename)
                if os.path.isdir(filename):
                    module.fail_json(msg='attempted to read contents of directory: %s' % filename)
                with open(filename, 'rb') as f:
                    params['ssh_key_data'] = f.read()

            if state == 'present':
                result = credential.modify(**params)
                json_output['id'] = result['id']
            elif state == 'absent':
                result = credential.delete(**params)
        except (exc.NotFound) as excinfo:
            module.fail_json(msg='Failed to update credential, organization not found: {0}'.format(excinfo), changed=False)
        except (exc.ConnectionError, exc.BadRequest, exc.NotFound) as excinfo:
            module.fail_json(msg='Failed to update credential: {0}'.format(excinfo), changed=False)

    json_output['changed'] = result['changed']
    module.exit_json(**json_output)
def main():
    argument_spec = tower_argument_spec()
    argument_spec.update(
        dict(
            name=dict(required=True),
            description=dict(),
            inventory=dict(required=True),
            variables=dict(),
            credential=dict(),
            source=dict(choices=[
                "manual", "file", "ec2", "rax", "vmware", "gce", "azure",
                "azure_rm", "openstack", "satellite6", "cloudforms", "custom"
            ],
                        default="manual"),
            source_regions=dict(),
            source_vars=dict(),
            instance_filters=dict(),
            group_by=dict(),
            source_script=dict(),
            overwrite=dict(type='bool', default=False),
            overwrite_vars=dict(),
            update_on_launch=dict(type='bool', default=False),
            state=dict(choices=['present', 'absent'], default='present'),
        ))

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

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

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

    variables = module.params.get('variables')
    if variables:
        if variables.startswith('@'):
            filename = os.path.expanduser(variables[1:])
            variables = module.contents_from_file(filename)

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

    tower_auth = tower_auth_config(module)
    with settings.runtime_values(**tower_auth):
        tower_check_mode(module)
        group = tower_cli.get_resource('group')
        try:
            params = module.params.copy()
            params['create_on_missing'] = True
            params['variables'] = variables

            inv_res = tower_cli.get_resource('inventory')
            inv = inv_res.get(name=inventory)
            params['inventory'] = inv['id']

            if credential:
                cred_res = tower_cli.get_resource('credential')
                cred = cred_res.get(name=credential)
                params['credential'] = cred['id']

            if state == 'present':
                result = group.modify(**params)
                json_output['id'] = result['id']
            elif state == 'absent':
                result = group.delete(**params)
        except (exc.NotFound) as excinfo:
            module.fail_json(
                msg='Failed to update the group, inventory not found: {0}'.
                format(excinfo),
                changed=False)
        except (exc.ConnectionError, exc.BadRequest, exc.NotFound) as excinfo:
            module.fail_json(
                msg='Failed to update the group: {0}'.format(excinfo),
                changed=False)

    json_output['changed'] = result['changed']
    module.exit_json(**json_output)
def main():
    argument_spec = tower_argument_spec()
    argument_spec.update(
        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 = AnsibleModule(argument_spec=argument_spec,
                           supports_check_mode=True)

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

    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):
                    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) 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)
Exemple #22
0
def main():
    argument_spec = tower_argument_spec()
    argument_spec.update(
        dict(
            name=dict(required=True),
            description=dict(),
            organization=dict(required=True),
            variables=dict(),
            kind=dict(choices=['', 'smart'], default=''),
            host_filter=dict(),
            state=dict(choices=['present', 'absent'], default='present'),
        ))

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

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

    name = module.params.get('name')
    description = module.params.get('description')
    organization = module.params.get('organization')
    variables = module.params.get('variables')
    state = module.params.get('state')
    kind = module.params.get('kind')
    host_filter = module.params.get('host_filter')

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

    tower_auth = tower_auth_config(module)
    with settings.runtime_values(**tower_auth):
        tower_check_mode(module)
        inventory = tower_cli.get_resource('inventory')

        try:
            org_res = tower_cli.get_resource('organization')
            org = org_res.get(name=organization)

            if state == 'present':
                result = inventory.modify(name=name,
                                          organization=org['id'],
                                          variables=variables,
                                          description=description,
                                          kind=kind,
                                          host_filter=host_filter,
                                          create_on_missing=True)
                json_output['id'] = result['id']
            elif state == 'absent':
                result = inventory.delete(name=name, organization=org['id'])
        except (exc.NotFound) as excinfo:
            module.fail_json(
                msg='Failed to update inventory, organization not found: {0}'.
                format(excinfo),
                changed=False)
        except (exc.ConnectionError, exc.BadRequest) as excinfo:
            module.fail_json(
                msg='Failed to update inventory: {0}'.format(excinfo),
                changed=False)

    json_output['changed'] = result['changed']
    module.exit_json(**json_output)
Exemple #23
0
def main():
    argument_spec = tower_argument_spec()
    argument_spec.update(
        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),
            state=dict(choices=['present', 'absent'], default='present'),
        ))

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

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

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

    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')
        try:
            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')

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

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

            if module.params.get('schema') and state == 'present':
                wfjt_res.schema(result['id'], module.params.get('schema'))

        except (exc.ConnectionError, exc.BadRequest) 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)
Exemple #24
0
def main():

    argument_spec = tower_argument_spec()
    argument_spec.update(
        dict(
            name=dict(required=True),
            user=dict(),
            team=dict(),
            kind=dict(required=True, choices=KIND_CHOICES.keys()),
            host=dict(),
            username=dict(),
            password=dict(no_log=True),
            ssh_key_data=dict(no_log=True, type='path'),
            ssh_key_unlock=dict(no_log=True),
            authorize=dict(type='bool', default=False),
            authorize_password=dict(no_log=True),
            client=dict(),
            security_token=dict(),
            secret=dict(),
            tenant=dict(),
            subscription=dict(),
            domain=dict(),
            become_method=dict(),
            become_username=dict(),
            become_password=dict(no_log=True),
            vault_password=dict(no_log=True),
            description=dict(),
            organization=dict(required=True),
            project=dict(),
            state=dict(choices=['present', 'absent'], default='present'),
        ))

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

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

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

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

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

            if organization:
                org_res = tower_cli.get_resource('organization')
                org = org_res.get(name=organization)
                params['organization'] = org['id']

            try:
                tower_cli.get_resource('credential_type')
            except (ImportError, AttributeError):
                # /api/v1/ backwards compat
                # older versions of tower-cli don't *have* a credential_type
                # resource
                params['kind'] = module.params['kind']
            else:
                credential_type = credential_type_for_v1_kind(
                    module.params, module)
                params['credential_type'] = credential_type['id']

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

            if module.params.get('user'):
                user_res = tower_cli.get_resource('user')
                user = user_res.get(username=module.params.get('user'))
                params['user'] = user['id']

            if module.params.get('team'):
                team_res = tower_cli.get_resource('team')
                team = team_res.get(name=module.params.get('team'))
                params['team'] = team['id']

            if module.params.get('ssh_key_data'):
                filename = module.params.get('ssh_key_data')
                if not os.path.exists(filename):
                    module.fail_json(msg='file not found: %s' % filename)
                if os.path.isdir(filename):
                    module.fail_json(
                        msg='attempted to read contents of directory: %s' %
                        filename)
                with open(filename, 'rb') as f:
                    module.params['ssh_key_data'] = to_text(f.read())

            for key in ('authorize', 'authorize_password', 'client',
                        'security_token', 'secret', 'tenant', 'subscription',
                        'domain', 'become_method', 'become_username',
                        'become_password', 'vault_password', 'project', 'host',
                        'username', 'password', 'ssh_key_data',
                        'ssh_key_unlock'):
                if 'kind' in params:
                    params[key] = module.params.get(key)
                elif module.params.get(key):
                    params.setdefault('inputs',
                                      {})[key] = module.params.get(key)

            if state == 'present':
                result = credential.modify(**params)
                json_output['id'] = result['id']
            elif state == 'absent':
                result = credential.delete(**params)
        except (exc.NotFound) as excinfo:
            module.fail_json(
                msg='Failed to update credential, organization not found: {0}'.
                format(excinfo),
                changed=False)
        except (exc.ConnectionError, exc.BadRequest, exc.NotFound) as excinfo:
            module.fail_json(
                msg='Failed to update credential: {0}'.format(excinfo),
                changed=False)

    json_output['changed'] = result['changed']
    module.exit_json(**json_output)
def main():

    argument_spec = tower_argument_spec()
    argument_spec.update(dict(
        name=dict(required=True),
        user=dict(),
        team=dict(),
        kind=dict(required=True,
                  choices=KIND_CHOICES.keys()),
        host=dict(),
        username=dict(),
        password=dict(no_log=True),
        ssh_key_data=dict(no_log=True, type='path'),
        ssh_key_unlock=dict(no_log=True),
        authorize=dict(type='bool', default=False),
        authorize_password=dict(no_log=True),
        client=dict(),
        security_token=dict(),
        secret=dict(),
        tenant=dict(),
        subscription=dict(),
        domain=dict(),
        become_method=dict(),
        become_username=dict(),
        become_password=dict(no_log=True),
        vault_password=dict(no_log=True),
        description=dict(),
        organization=dict(required=True),
        project=dict(),
        state=dict(choices=['present', 'absent'], default='present'),
    ))

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

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

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

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

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

            if organization:
                org_res = tower_cli.get_resource('organization')
                org = org_res.get(name=organization)
                params['organization'] = org['id']

            try:
                tower_cli.get_resource('credential_type')
            except (ImportError, AttributeError):
                # /api/v1/ backwards compat
                # older versions of tower-cli don't *have* a credential_type
                # resource
                params['kind'] = module.params['kind']
            else:
                credential_type = credential_type_for_v1_kind(module.params, module)
                params['credential_type'] = credential_type['id']

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

            if module.params.get('user'):
                user_res = tower_cli.get_resource('user')
                user = user_res.get(username=module.params.get('user'))
                params['user'] = user['id']

            if module.params.get('team'):
                team_res = tower_cli.get_resource('team')
                team = team_res.get(name=module.params.get('team'))
                params['team'] = team['id']

            if module.params.get('ssh_key_data'):
                filename = module.params.get('ssh_key_data')
                if not os.path.exists(filename):
                    module.fail_json(msg='file not found: %s' % filename)
                if os.path.isdir(filename):
                    module.fail_json(msg='attempted to read contents of directory: %s' % filename)
                with open(filename, 'rb') as f:
                    module.params['ssh_key_data'] = to_text(f.read())

            for key in ('authorize', 'authorize_password', 'client',
                        'security_token', 'secret', 'tenant', 'subscription',
                        'domain', 'become_method', 'become_username',
                        'become_password', 'vault_password', 'project', 'host',
                        'username', 'password', 'ssh_key_data',
                        'ssh_key_unlock'):
                if 'kind' in params:
                    params[key] = module.params.get(key)
                elif module.params.get(key):
                    params.setdefault('inputs', {})[key] = module.params.get(key)

            if state == 'present':
                result = credential.modify(**params)
                json_output['id'] = result['id']
            elif state == 'absent':
                result = credential.delete(**params)
        except (exc.NotFound) as excinfo:
            module.fail_json(msg='Failed to update credential, organization not found: {0}'.format(excinfo), changed=False)
        except (exc.ConnectionError, exc.BadRequest, exc.NotFound) as excinfo:
            module.fail_json(msg='Failed to update credential: {0}'.format(excinfo), changed=False)

    json_output['changed'] = result['changed']
    module.exit_json(**json_output)
Exemple #26
0
def main():
    argument_spec = tower_argument_spec()
    argument_spec.update(dict(
        name=dict(required=True),
        description=dict(),
        inventory=dict(required=True),
        variables=dict(),
        credential=dict(),
        source=dict(choices=["manual", "file", "ec2", "rax", "vmware",
                             "gce", "azure", "azure_rm", "openstack",
                             "satellite6", "cloudforms", "custom"], default="manual"),
        source_regions=dict(),
        source_vars=dict(),
        instance_filters=dict(),
        group_by=dict(),
        source_script=dict(),
        overwrite=dict(type='bool', default=False),
        overwrite_vars=dict(),
        update_on_launch=dict(type='bool', default=False),
        state=dict(choices=['present', 'absent'], default='present'),
    ))

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

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

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

    variables = module.params.get('variables')
    if variables:
        if variables.startswith('@'):
            filename = os.path.expanduser(variables[1:])
            with open(filename, 'r') as f:
                variables = f.read()

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

    tower_auth = tower_auth_config(module)
    with settings.runtime_values(**tower_auth):
        tower_check_mode(module)
        group = tower_cli.get_resource('group')
        try:
            params = module.params.copy()
            params['create_on_missing'] = True
            params['variables'] = variables

            inv_res = tower_cli.get_resource('inventory')
            inv = inv_res.get(name=inventory)
            params['inventory'] = inv['id']

            if credential:
                cred_res = tower_cli.get_resource('credential')
                cred = cred_res.get(name=credential)
                params['credential'] = cred['id']

            if state == 'present':
                result = group.modify(**params)
                json_output['id'] = result['id']
            elif state == 'absent':
                result = group.delete(**params)
        except (exc.NotFound) as excinfo:
            module.fail_json(msg='Failed to update the group, inventory not found: {0}'.format(excinfo), changed=False)
        except (exc.ConnectionError, exc.BadRequest, exc.NotFound) as excinfo:
            module.fail_json(msg='Failed to update the group: {0}'.format(excinfo), changed=False)

    json_output['changed'] = result['changed']
    module.exit_json(**json_output)
Exemple #27
0
def main():
    argument_spec = tower_argument_spec()
    argument_spec.update(dict(
        name=dict(),
        description=dict(),
        organization=dict(),
        scm_type=dict(choices=['manual', 'git', 'hg', 'svn'], default='manual'),
        scm_url=dict(),
        scm_branch=dict(),
        scm_credential=dict(),
        scm_clean=dict(type='bool', default=False),
        scm_delete_on_update=dict(type='bool', default=False),
        scm_update_on_launch=dict(type='bool', default=False),
        local_path=dict(),

        state=dict(choices=['present', 'absent'], default='present'),
    ))

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

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

    name = module.params.get('name')
    description = module.params.get('description')
    organization = module.params.get('organization')
    scm_type = module.params.get('scm_type')
    if scm_type == "manual":
        scm_type = ""
    scm_url = module.params.get('scm_url')
    local_path = module.params.get('local_path')
    scm_branch = module.params.get('scm_branch')
    scm_credential = module.params.get('scm_credential')
    scm_clean = module.params.get('scm_clean')
    scm_delete_on_update = module.params.get('scm_delete_on_update')
    scm_update_on_launch = module.params.get('scm_update_on_launch')
    state = module.params.get('state')

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

    tower_auth = tower_auth_config(module)
    with settings.runtime_values(**tower_auth):
        tower_check_mode(module)
        project = tower_cli.get_resource('project')
        try:
            if state == 'present':
                try:
                    org_res = tower_cli.get_resource('organization')
                    org = org_res.get(name=organization)
                except (exc.NotFound) as excinfo:
                    module.fail_json(msg='Failed to update project, organization not found: {0}'.format(organization), changed=False)
                try:
                    cred_res = tower_cli.get_resource('credential')
                    cred = cred_res.get(name=scm_credential)
                except (exc.NotFound) as excinfo:
                    module.fail_json(msg='Failed to update project, credential not found: {0}'.format(scm_credential), changed=False)

                result = project.modify(name=name, description=description,
                                        organization=org['id'],
                                        scm_type=scm_type, scm_url=scm_url, local_path=local_path,
                                        scm_branch=scm_branch, scm_clean=scm_clean, credential=cred['id'],
                                        scm_delete_on_update=scm_delete_on_update,
                                        scm_update_on_launch=scm_update_on_launch,
                                        create_on_missing=True)
                json_output['id'] = result['id']
            elif state == 'absent':
                result = project.delete(name=name)
        except (exc.ConnectionError, exc.BadRequest) as excinfo:
            module.fail_json(msg='Failed to update project: {0}'.format(excinfo), changed=False)

    json_output['changed'] = result['changed']
    module.exit_json(**json_output)