예제 #1
0
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)
예제 #2
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)
예제 #3
0
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)
예제 #4
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            name=dict(required=True),
            description=dict(),
            inventory=dict(required=True),
            enabled=dict(type='bool', default=True),
            variables=dict(),
            tower_host=dict(),
            tower_username=dict(),
            tower_password=dict(no_log=True),
            tower_verify_ssl=dict(type='bool', default=True),
            tower_config_file=dict(type='path'),
            state=dict(choices=['present', 'absent'], default='present'),
        ),
        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)
예제 #5
0
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)
예제 #6
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)
예제 #7
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            name=dict(required=True),
            description=dict(),
            organization=dict(required=True),
            tower_host=dict(),
            tower_username=dict(),
            tower_password=dict(no_log=True),
            tower_verify_ssl=dict(type='bool', default=True),
            tower_config_file=dict(type='path'),
            state=dict(choices=['present', 'absent'], default='present'),
        ),
        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')
    state = module.params.get('state')

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

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

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

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

    json_output['changed'] = result['changed']
    module.exit_json(**json_output)
예제 #8
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)
예제 #9
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)
예제 #10
0
def main():
    argument_spec = 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 = TowerModule(argument_spec=argument_spec, supports_check_mode=True)

    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)
예제 #11
0
def main():

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

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

    role_type = module.params.pop('role')
    state = module.params.pop('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, exc.AuthError) 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)
def main():
    module = AnsibleModule(argument_spec=dict(
        name=dict(required=True),
        description=dict(),
        tower_host=dict(),
        tower_username=dict(),
        tower_password=dict(no_log=True),
        tower_verify_ssl=dict(type='bool', default=True),
        tower_config_file=dict(type='path'),
        state=dict(choices=['present', 'absent'], default='present'),
    ),
                           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)
예제 #13
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)
예제 #14
0
def main():
    argument_spec = dict()
    module = TowerModule(argument_spec=argument_spec, supports_check_mode=True)

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

        try:
            result = host.list()
            json_output = {'hosts': result}
        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, exc.AuthError) as excinfo:
            module.fail_json(msg='Failed to update host: {0}'.format(excinfo),
                             changed=False)

    module.exit_json(**json_output)
예제 #15
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)
예제 #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)
예제 #17
0
def main():
    argument_spec = dict(
        name=dict(required=True),
        organization=dict(required=True),
        state=dict(choices=['present', 'absent'], default='present'),
    )

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

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

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

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

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

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

    json_output['changed'] = result['changed']
    module.exit_json(**json_output)
예제 #18
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)
예제 #19
0
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)
예제 #20
0
def main():
    argument_spec = dict(
        name=dict(required=True),
        description=dict(required=False),
        organization=dict(required=False),
        notification_type=dict(required=True, choices=['email', 'slack', 'twilio', 'pagerduty', 'hipchat', 'webhook', 'irc']),
        notification_configuration=dict(required=False),
        username=dict(required=False),
        sender=dict(required=False),
        recipients=dict(required=False, type='list'),
        use_tls=dict(required=False, type='bool'),
        host=dict(required=False),
        use_ssl=dict(required=False, type='bool'),
        password=dict(required=False, no_log=True),
        port=dict(required=False, type='int'),
        channels=dict(required=False, type='list'),
        token=dict(required=False, no_log=True),
        account_token=dict(required=False, no_log=True),
        from_number=dict(required=False),
        to_numbers=dict(required=False, type='list'),
        account_sid=dict(required=False),
        subdomain=dict(required=False),
        service_key=dict(required=False, no_log=True),
        client_name=dict(required=False),
        message_from=dict(required=False),
        api_url=dict(required=False),
        color=dict(required=False, choices=['yellow', 'green', 'red', 'purple', 'gray', 'random']),
        rooms=dict(required=False, type='list'),
        notify=dict(required=False, type='bool'),
        url=dict(required=False),
        headers=dict(required=False, type='dict', default={}),
        server=dict(required=False),
        nickname=dict(required=False),
        targets=dict(required=False, type='list'),
        state=dict(choices=['present', 'absent'], default='present'),
    )

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

    name = module.params.get('name')
    description = module.params.get('description')
    organization = module.params.get('organization')
    notification_type = module.params.get('notification_type')
    notification_configuration = module.params.get('notification_configuration')
    username = module.params.get('username')
    sender = module.params.get('sender')
    recipients = module.params.get('recipients')
    use_tls = module.params.get('use_tls')
    host = module.params.get('host')
    use_ssl = module.params.get('use_ssl')
    password = module.params.get('password')
    port = module.params.get('port')
    channels = module.params.get('channels')
    token = module.params.get('token')
    account_token = module.params.get('account_token')
    from_number = module.params.get('from_number')
    to_numbers = module.params.get('to_numbers')
    account_sid = module.params.get('account_sid')
    subdomain = module.params.get('subdomain')
    service_key = module.params.get('service_key')
    client_name = module.params.get('client_name')
    message_from = module.params.get('message_from')
    api_url = module.params.get('api_url')
    color = module.params.get('color')
    rooms = module.params.get('rooms')
    notify = module.params.get('notify')
    url = module.params.get('url')
    headers = module.params.get('headers')
    server = module.params.get('server')
    nickname = module.params.get('nickname')
    targets = module.params.get('targets')
    state = module.params.get('state')

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

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

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

            if state == 'present':
                result = notification_template.modify(name=name, description=description, organization=org['id'],
                                                      notification_type=notification_type,
                                                      notification_configuration=notification_configuration,
                                                      username=username, sender=sender, recipients=recipients,
                                                      use_tls=use_tls, host=host, use_ssl=use_ssl, password=password,
                                                      port=port, channels=channels, token=token,
                                                      account_token=account_token, from_number=from_number,
                                                      to_numbers=to_numbers, account_sid=account_sid,
                                                      subdomain=subdomain, service_key=service_key,
                                                      client_name=client_name, message_from=message_from,
                                                      api_url=api_url, color=color, rooms=rooms, notify=notify,
                                                      url=url, headers=headers, server=server, nickname=nickname,
                                                      targets=targets, create_on_missing=True)
                json_output['id'] = result['id']
            elif state == 'absent':
                result = notification_template.delete(name=name)
        except (exc.NotFound) as excinfo:
            module.fail_json(msg='Failed to update notification template, organization not found: {0}'.format(excinfo), changed=False)
        except (exc.ConnectionError, exc.BadRequest, exc.AuthError) as excinfo:
            module.fail_json(msg='Failed to update notification template: {0}'.format(excinfo), changed=False)

    json_output['changed'] = result['changed']
    module.exit_json(**json_output)
예제 #21
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)
예제 #22
0
def main():
    module = AnsibleModule(
        argument_spec=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(),
            tower_host=dict(),
            tower_username=dict(),
            tower_password=dict(no_log=True),
            tower_verify_ssl=dict(type='bool', default=True),
            tower_config_file=dict(type='path'),
            state=dict(choices=['present', 'absent'], default='present'),
        ),
        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)
예제 #23
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)
예제 #24
0
def main():
    module = AnsibleModule(
        argument_spec=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(),
            tower_host=dict(),
            tower_username=dict(),
            tower_password=dict(no_log=True),
            tower_verify_ssl=dict(type='bool', default=True),
            tower_config_file=dict(type='path'),

            state=dict(choices=['present', 'absent'], default='present'),
        ),
        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)
예제 #25
0
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)
예제 #26
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:])
            with open(filename, 'r') as f:
                variables = f.read()

    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)
예제 #27
0
def main():
    module = AnsibleModule(argument_spec=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),
        tower_host=dict(),
        tower_username=dict(),
        tower_password=dict(no_log=True),
        tower_verify_ssl=dict(type='bool', default=True),
        tower_config_file=dict(type='path'),
        state=dict(choices=['present', 'absent'], default='present'),
    ),
                           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)
예제 #28
0
def main():
    module = AnsibleModule(argument_spec=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(),
        tower_host=dict(),
        tower_username=dict(),
        tower_password=dict(no_log=True),
        tower_verify_ssl=dict(type='bool', default=True),
        tower_config_file=dict(type='path'),
        state=dict(choices=['present', 'absent'], default='present'),
    ),
                           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':
                org_res = tower_cli.get_resource('organization')
                org = org_res.get(name=organization)

                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,
                    scm_credential=scm_credential,
                    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.NotFound) as excinfo:
            module.fail_json(
                msg='Failed to update project, organization not found: {0}'.
                format(excinfo),
                changed=False)
        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)
예제 #29
0
def main():

    argument_spec = dict(
        name=dict(required=True),
        user=dict(),
        team=dict(),
        kind=dict(required=True,
                  choices=list(KIND_CHOICES.keys()) + ['cloud']),
        credential_type=dict(),
        host=dict(),
        username=dict(),
        password=dict(no_log=True),
        ssh_key_data=dict(no_log=True, type='str'),
        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'),
        vault_id=dict(),
    )

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

    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:
                if module.params['kind'] in KIND_CHOICES:
                    # built-in credential type
                    credential_type = credential_type_for_v1_kind(
                        module.params, module)
                else:
                    # custom 'cloud' kind credential type
                    if not module.params.get('credential_type'):
                        module.fail_json(
                            msg=
                            "Parameter 'credential_type' required for non built-in type"
                        )
                    credential_type = credential_type_custom(
                        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'):
                data = module.params.get('ssh_key_data')
                if os.path.exists(data):
                    module.deprecate(
                        msg=
                        'ssh_key_data should be a string, not a path to a file. Use lookup(\'file\', \'/path/to/file\') instead',
                        version="2.12")
                    if os.path.isdir(data):
                        module.fail_json(
                            msg='attempted to read contents of directory: %s' %
                            data)
                    with open(data, 'rb') as f:
                        module.params['ssh_key_data'] = to_text(f.read())
                else:
                    module.params['ssh_key_data'] = data

            if module.params.get(
                    'vault_id', None) and module.params.get('kind') != 'vault':
                module.fail_json(
                    msg=
                    "Parameter 'vault_id' is only valid if parameter 'kind' is specified as 'vault'"
                )

            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', 'vault_id',
                        '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,
                exc.AuthError) 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 = dict(
        name=dict(required=True),
        description=dict(default=''),
        job_type=dict(choices=['run', 'check', 'scan'], required=True),
        inventory=dict(default=''),
        project=dict(required=True),
        playbook=dict(required=True),
        credential=dict(default=''),
        vault_credential=dict(default=''),
        forks=dict(type='int'),
        limit=dict(default=''),
        verbosity=dict(type='int', choices=[0, 1, 2, 3, 4], default=0),
        extra_vars_path=dict(type='path', required=False),
        job_tags=dict(default=''),
        force_handlers_enabled=dict(type='bool', default=False),
        skip_tags=dict(default=''),
        start_at_task=dict(default=''),
        timeout=dict(type='int', default=0),
        fact_caching_enabled=dict(type='bool', default=False),
        host_config_key=dict(default=''),
        ask_diff_mode=dict(type='bool', default=False),
        ask_extra_vars=dict(type='bool', default=False),
        ask_limit=dict(type='bool', default=False),
        ask_tags=dict(type='bool', default=False),
        ask_skip_tags=dict(type='bool', default=False),
        ask_job_type=dict(type='bool', default=False),
        ask_verbosity=dict(type='bool', default=False),
        ask_inventory=dict(type='bool', default=False),
        ask_credential=dict(type='bool', default=False),
        survey_enabled=dict(type='bool', default=False),
        survey_spec=dict(type='dict', required=False),
        become_enabled=dict(type='bool', default=False),
        diff_mode_enabled=dict(type='bool', default=False),
        concurrent_jobs_enabled=dict(type='bool', default=False),
        state=dict(choices=['present', 'absent'], default='present'),
    )

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

    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)
예제 #31
0
def main():
    module = AnsibleModule(argument_spec=dict(
        username=dict(required=True),
        first_name=dict(),
        last_name=dict(),
        password=dict(no_log=True),
        email=dict(),
        superuser=dict(type='bool', default=False),
        auditor=dict(type='bool', default=False),
        tower_host=dict(),
        tower_username=dict(),
        tower_password=dict(no_log=True),
        tower_verify_ssl=dict(type='bool', default=True),
        tower_config_file=dict(type='path'),
        state=dict(choices=['present', 'absent'], default='present'),
    ),
                           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':
                if email is None:
                    module.fail_json(
                        msg=
                        "email needs to be defined when creating/modifying a new tower user"
                    )
                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)
예제 #32
0
def main():
    argument_spec = 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 = TowerModule(argument_spec=argument_spec, supports_check_mode=True)

    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)

                if scm_credential:
                    try:
                        cred_res = tower_cli.get_resource('credential')
                        try:
                            cred = cred_res.get(name=scm_credential)
                        except (tower_cli.exceptions.MultipleResults
                                ) as multi_res_excinfo:
                            module.warn(
                                'Multiple credentials found for {0}, falling back looking in project organization'
                                .format(scm_credential))
                            cred = cred_res.get(name=scm_credential,
                                                organization=org['id'])
                        scm_credential = cred['id']
                    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=scm_credential,
                    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)
예제 #33
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)
예제 #34
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 = dict(
        name=dict(required=True),
        group=dict(required=True),
        inventory=dict(required=True),
        state=dict(choices=['present', 'absent'], default='present'),
    )

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

    name = module.params.get('name')
    group = module.params.get('group')
    inventory = module.params.get('inventory')
    state = module.params.pop('state')

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

    tower_auth = tower_auth_config(module)
    with settings.runtime_values(**tower_auth):
        tower_check_mode(module)
        try:
            params = module.params.copy()

            # Get existing resources
            inventories = tower_cli.get_resource('inventory')
            hosts = tower_cli.get_resource('host')
            groups = tower_cli.get_resource('group')

            # Find specific inventory
            inv = inventories.get(name=inventory)

            # Find specific host
            host = hosts.get(name=name, inventory=inv['id'])
            params['host'] = host['id']

            # Find specific group
            if group == '*':
                grp = groups.list(inventory=inv['id'], all_pages=True)
            else:
                grp = groups.get(name=group, inventory=inv['id'])
                params['group'] = grp['id']

            if state == "present":
                if group == '*':
                    for g in grp['results']:
                        params['group'] = g['id']
                        result = hosts.associate(**params)
                        if result['changed']:
                            result[
                                'msg'] = 'Successfully associated ' + name + ' with ' + g[
                                    'name']
                        elif not result['changed']:
                            result[
                                'msg'] = name + ' is already associated with ' + g[
                                    'name']
                else:
                    result = hosts.associate(**params)
                    if result['changed']:
                        result[
                            'msg'] = 'Successfully associated ' + name + ' with ' + group
                    elif not result['changed']:
                        result[
                            'msg'] = name + ' is already associated with ' + group
            elif state == "absent":
                if group == '*':
                    for g in grp['results']:
                        params['group'] = g['id']
                        result = hosts.disassociate(**params)
                        if result['changed']:
                            result[
                                'msg'] = 'Successfully disassociated ' + name + ' with ' + g[
                                    'name']
                        elif not result['changed']:
                            result[
                                'msg'] = name + ' is already disassociated with ' + g[
                                    'name']
                else:
                    result = hosts.disassociate(**params)
                    if result['changed']:
                        result[
                            'msg'] = 'Successfully disassociated ' + name + ' with ' + group
                    elif not result['changed']:
                        result[
                            'msg'] = name + ' is already disassociated with ' + group
        except (exc.NotFound) as excinfo:
            module.fail_json(
                msg='Failed to update the host, not found: {0}'.format(
                    excinfo),
                changed=False)
        except (exc.ConnectionError, exc.BadRequest, exc.NotFound) as excinfo:
            module.fail_json(
                msg='Failed to update the host: {0}'.format(excinfo),
                changed=False)

    json_output['changed'] = result['changed']
    json_output['msg'] = result['msg']
    module.exit_json(**json_output)
예제 #36
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),
        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')

        for key in ('allow_simultaneous', 'extra_vars', '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) 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)
예제 #37
0
def main():
    module = AnsibleModule(argument_spec=dict(
        name=dict(required=True),
        state=dict(choices=['present', 'absent', 'disabled'],
                   default='present'),
        description=dict(default=''),
        job_template=dict(),
        project=dict(),
        inventory_source=dict(),
        start=dict(default=datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")),
        frequency=dict(type='int'),
        frequency_unit=dict(choices=['runonce', 'minute', 'hour', 'day'],
                            default='runonce'),
        tower_host=dict(),
        tower_username=dict(),
        tower_password=dict(no_log=True),
        tower_verify_ssl=dict(type='bool', default=True),
        tower_config_file=dict(type='path')),
                           mutually_exclusive=[
                               'job_template', 'project', 'inventory_source'
                           ],
                           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')
    description = module.params.get('description')
    job_template = module.params.get('job_template')
    project = module.params.get('project')
    inventory_source = module.params.get('inventory_source')
    start = module.params.get('start')
    frequency = module.params.get('frequency')
    frequency_unit = module.params.get('frequency_unit')

    json_output = {
        'name': name,
        'description': description,
        'state': state,
        'start': start,
        'frequency_unit': frequency_unit
    }
    if frequency:
        json_output['frequency'] = frequency

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

        params = {
            'name': name,
            'description': description,
        }

        if job_template:
            params['job_template'] = get_resource_id('job_template',
                                                     job_template)
            json_output['job_template'] = job_template
        if project:
            params['project'] = get_resource_id('project', project)
            json_output['project'] = project
        if inventory_source:
            params['inventory_source'] = get_resource_id(
                'inventory_source', inventory_source)
            json_output['inventory_source'] = inventory_source

        dtstart = parse_datetime_string(module, start)
        params['rrule'] = build_rrule(dtstart, frequency, frequency_unit)

        try:
            if state == 'absent':
                result = schedule.delete(**params)
            else:
                params['enabled'] = False if state == 'disabled' else True
                json_output['enabled'] = params['enabled']
                # TODO: Figure out why modify with create_on_missing fails with MethodNotAllowed
                # https://github.com/ansible/tower-cli/issues/578
                result = schedule.create(**params)
                result = schedule.modify(**params)
        except (exc.ConnectionError, exc.BadRequest, exc.NotFound) as excinfo:
            module.fail_json(
                msg='Failed to update schedule: {0}'.format(excinfo),
                changed=False)

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