def test_clean_credential_insights():
    proj = Project(name="myproj", credential=None, scm_type='insights')
    with pytest.raises(ValidationError) as e:
        proj.clean_credential()

    assert json.dumps(str(e.value)) == json.dumps(
        str([u'Insights Credential is required for an Insights Project.']))
Ejemplo n.º 2
0
def _mk_project_update(created=None):
    kwargs = {}
    if created:
        kwargs['created'] = created
    project = Project()
    project.save()
    return ProjectUpdate(project=project, **kwargs)
Ejemplo n.º 3
0
    def handle(self, *args, **kwargs):
        changed = False

        # Create a default organization as the first superuser found.
        try:
            superuser = User.objects.filter(is_superuser=True).order_by('pk')[0]
        except IndexError:
            superuser = None
        with impersonate(superuser):
            with disable_computed_fields():
                if not Organization.objects.exists():
                    o = Organization.objects.create(name='Default')

                    p = Project(
                        name='Demo Project',
                        scm_type='git',
                        scm_url='https://github.com/ansible/ansible-tower-samples',
                        scm_update_on_launch=True,
                        scm_update_cache_timeout=0,
                        organization=o,
                    )
                    p.save(skip_update=True)

                    ssh_type = CredentialType.objects.filter(namespace='ssh').first()
                    c = Credential.objects.create(
                        credential_type=ssh_type, name='Demo Credential', inputs={'username': superuser.username}, created_by=superuser
                    )

                    c.admin_role.members.add(superuser)

                    public_galaxy_credential = Credential(
                        name='Ansible Galaxy',
                        managed_by_tower=True,
                        credential_type=CredentialType.objects.get(kind='galaxy'),
                        inputs={'url': 'https://galaxy.ansible.com/'},
                    )
                    public_galaxy_credential.save()
                    o.galaxy_credentials.add(public_galaxy_credential)

                    i = Inventory.objects.create(name='Demo Inventory', organization=o, created_by=superuser)

                    Host.objects.create(
                        name='localhost',
                        inventory=i,
                        variables="ansible_connection: local\nansible_python_interpreter: '{{ ansible_playbook_python }}'",
                        created_by=superuser,
                    )

                    jt = JobTemplate.objects.create(name='Demo Job Template', playbook='hello_world.yml', project=p, inventory=i)
                    jt.credentials.add(c)

                    print('Default organization added.')
                    print('Demo Credential, Inventory, and Job Template added.')
                    changed = True

        if changed:
            print('(changed: True)')
        else:
            print('(changed: False)')
Ejemplo n.º 4
0
def mk_project(name, organization=None, description=None, persisted=True):
    description = description or '{}-description'.format(name)
    project = Project(name=name, description=description, playbook_files=['helloworld.yml', 'alt-helloworld.yml'])
    if organization is not None:
        project.organization = organization
    if persisted:
        project.save()
    return project
Ejemplo n.º 5
0
def test_team_accessible_objects(team, user, project):
    u = user('team_member', False)

    team.member_role.children.add(project.use_role)
    assert len(Project.accessible_objects(team, 'read_role')) == 1
    assert not Project.accessible_objects(u, 'read_role')

    team.member_role.members.add(u)
    assert len(Project.accessible_objects(u, 'read_role')) == 1
Ejemplo n.º 6
0
def test_project_delete(delete, organization, admin_user):
    proj = Project(name='foo', organization=organization)
    proj.save()
    delete(
        reverse(
            'api:project_detail',
            kwargs={
                'pk': proj.id,
            },
        ),
        admin_user,
    )
Ejemplo n.º 7
0
def job(container_group):
    return Job(pk=1,
               id=1,
               project=Project(),
               instance_group=container_group,
               inventory=Inventory(),
               job_template=JobTemplate(id=1, name='foo'))
Ejemplo n.º 8
0
def job_template_with_ids(job_template_factory):
    # Create non-persisted objects with IDs to send to job_template_factory
    ssh_type = CredentialType(kind='ssh')
    credential = Credential(id=1,
                            pk=1,
                            name='testcred',
                            credential_type=ssh_type)

    net_type = CredentialType(kind='net')
    net_cred = Credential(id=2,
                          pk=2,
                          name='testnetcred',
                          credential_type=net_type)

    cloud_type = CredentialType(kind='aws')
    cloud_cred = Credential(id=3,
                            pk=3,
                            name='testcloudcred',
                            credential_type=cloud_type)

    inv = Inventory(id=11, pk=11, name='testinv')
    proj = Project(id=14, pk=14, name='testproj')

    jt_objects = job_template_factory('testJT',
                                      project=proj,
                                      inventory=inv,
                                      credential=credential,
                                      cloud_credential=cloud_cred,
                                      network_credential=net_cred,
                                      persisted=False)
    return jt_objects.job_template
Ejemplo n.º 9
0
    def get_serializer_context(self, *args, **kwargs):
        full_context = super(OrganizationDetail,
                             self).get_serializer_context(*args, **kwargs)

        if not hasattr(self, 'kwargs') or 'pk' not in self.kwargs:
            return full_context
        org_id = int(self.kwargs['pk'])

        org_counts = {}
        access_kwargs = {
            'accessor': self.request.user,
            'role_field': 'read_role'
        }
        direct_counts = Organization.objects.filter(id=org_id).annotate(
            users=Count('member_role__members', distinct=True),
            admins=Count('admin_role__members',
                         distinct=True)).values('users', 'admins')

        if not direct_counts:
            return full_context

        org_counts = direct_counts[0]
        org_counts['inventories'] = Inventory.accessible_objects(
            **access_kwargs).filter(organization__id=org_id).count()
        org_counts['teams'] = Team.accessible_objects(**access_kwargs).filter(
            organization__id=org_id).count()
        org_counts['projects'] = Project.accessible_objects(
            **access_kwargs).filter(organization__id=org_id).count()
        org_counts['job_templates'] = JobTemplate.accessible_objects(
            **access_kwargs).filter(organization__id=org_id).count()

        full_context['related_field_counts'] = {}
        full_context['related_field_counts'][org_id] = org_counts

        return full_context
Ejemplo n.º 10
0
    def handle(self, *args, **kwargs):
        # Sanity check: Is there already an organization in the system?
        if Organization.objects.count():
            print('An organization is already in the system, exiting.')
            print('(changed: False)')
            return

        # Create a default organization as the first superuser found.
        try:
            superuser = User.objects.filter(
                is_superuser=True).order_by('pk')[0]
        except IndexError:
            superuser = None
        with impersonate(superuser):
            with disable_computed_fields():
                o = Organization.objects.create(name='Default')
                p = Project(
                    name='Demo Project',
                    scm_type='git',
                    scm_url='https://github.com/ansible/ansible-tower-samples',
                    scm_branch='master',
                    scm_update_on_launch=True,
                    scm_update_cache_timeout=0,
                    organization=o)
                p.save(skip_update=True)
                ssh_type = CredentialType.from_v1_kind('ssh')
                c = Credential.objects.create(
                    credential_type=ssh_type,
                    name='Demo Credential',
                    inputs={'username': superuser.username},
                    created_by=superuser)
                c.admin_role.members.add(superuser)
                i = Inventory.objects.create(name='Demo Inventory',
                                             organization=o,
                                             created_by=superuser)
                Host.objects.create(name='localhost',
                                    inventory=i,
                                    variables="ansible_connection: local",
                                    created_by=superuser)
                jt = JobTemplate.objects.create(name='Demo Job Template',
                                                playbook='hello_world.yml',
                                                project=p,
                                                inventory=i)
                jt.credentials.add(c)
        print('Default organization added.')
        print('Demo Credential, Inventory, and Job Template added.')
        print('(changed: True)')
 def jt(self, survey_spec_factory):
     return JobTemplate(
         name='fake-jt',
         survey_enabled=True,
         survey_spec=survey_spec_factory(variables='var1', default_type='password'),
         project=Project('fake-proj'), project_id=42,
         inventory=Inventory('fake-inv'), inventory_id=42
     )
Ejemplo n.º 12
0
def test_org_admin_team_access(organization, team, user, project):
    u = user('team_admin', False)
    organization.admin_role.members.add(u)

    team.organization = organization
    team.save()

    team.member_role.children.add(project.use_role)

    assert len(Project.accessible_objects(u, 'use_role')) == 1
Ejemplo n.º 13
0
    def get(self, request, format=None):
        '''Return various sitewide configuration settings'''

        if request.user.is_superuser or request.user.is_system_auditor:
            license_data = get_license(show_key=True)
        else:
            license_data = get_license(show_key=False)
        if not license_data.get('valid_key', False):
            license_data = {}
        if license_data and 'features' in license_data and 'activity_streams' in license_data[
                'features']:
            # FIXME: Make the final setting value dependent on the feature?
            license_data['features'][
                'activity_streams'] &= settings.ACTIVITY_STREAM_ENABLED

        pendo_state = settings.PENDO_TRACKING_STATE if settings.PENDO_TRACKING_STATE in (
            'off', 'anonymous', 'detailed') else 'off'

        data = dict(
            time_zone=settings.TIME_ZONE,
            license_info=license_data,
            version=get_awx_version(),
            ansible_version=get_ansible_version(),
            eula=render_to_string("eula.md") if
            license_data.get('license_type', 'UNLICENSED') != 'open' else '',
            analytics_status=pendo_state,
            analytics_collectors=all_collectors(),
            become_methods=PRIVILEGE_ESCALATION_METHODS,
        )

        # If LDAP is enabled, user_ldap_fields will return a list of field
        # names that are managed by LDAP and should be read-only for users with
        # a non-empty ldap_dn attribute.
        if getattr(settings, 'AUTH_LDAP_SERVER_URI', None):
            user_ldap_fields = ['username', 'password']
            user_ldap_fields.extend(
                getattr(settings, 'AUTH_LDAP_USER_ATTR_MAP', {}).keys())
            user_ldap_fields.extend(
                getattr(settings, 'AUTH_LDAP_USER_FLAGS_BY_GROUP', {}).keys())
            data['user_ldap_fields'] = user_ldap_fields

        if request.user.is_superuser \
                or request.user.is_system_auditor \
                or Organization.accessible_objects(request.user, 'admin_role').exists() \
                or Organization.accessible_objects(request.user, 'auditor_role').exists() \
                or Organization.accessible_objects(request.user, 'project_admin_role').exists():
            data.update(
                dict(project_base_dir=settings.PROJECTS_ROOT,
                     project_local_paths=Project.get_local_path_choices(),
                     custom_virtualenvs=get_custom_venv_choices()))
        elif JobTemplate.accessible_objects(request.user,
                                            'admin_role').exists():
            data['custom_virtualenvs'] = get_custom_venv_choices()

        return Response(data)
Ejemplo n.º 14
0
 def test_jt_extra_vars_counting(self, provided_vars, valid):
     jt = JobTemplate(name='foo',
                      extra_vars={'tmpl_var': 'bar'},
                      project=Project(),
                      project_id=42,
                      playbook='helloworld.yml',
                      inventory=Inventory(),
                      inventory_id=42)
     prompted_fields, ignored_fields, errors = jt._accept_or_ignore_job_kwargs(
         extra_vars=provided_vars)
     self.process_vars_and_assert(jt, provided_vars, valid)
Ejemplo n.º 15
0
 def test_project_update_metavars(self):
     data = Job(name='fake-job',
                pk=40,
                id=40,
                launch_type='manual',
                project=Project(name='jobs-sync', scm_revision='12345444'),
                job_template=JobTemplate(name='jobs-jt', id=92,
                                         pk=92)).awx_meta_vars()
     assert data['awx_project_revision'] == '12345444'
     assert 'tower_job_template_id' in data
     assert data['tower_job_template_id'] == 92
     assert data['tower_job_template_name'] == 'jobs-jt'
Ejemplo n.º 16
0
def test_multiple(scm_type):
    expected = {
        'manual': 0,
        'git': 0,
        'svn': 0,
        'hg': 0,
        'insights': 0
    }
    for i in range(random.randint(0, 10)):
        Project(scm_type=scm_type).save()
        expected[scm_type or 'manual'] += 1
    assert collectors.projects_by_scm_type(None) == expected
Ejemplo n.º 17
0
 def test_project_update_metavars(self):
     data = Job(
         name='fake-job',
         pk=40,
         id=40,
         launch_type='manual',
         project=Project(name='jobs-sync', scm_revision='12345444'),
         job_template=JobTemplate(name='jobs-jt', id=92, pk=92),
     ).awx_meta_vars()
     for name in JOB_VARIABLE_PREFIXES:
         assert data['{}_project_revision'.format(name)] == '12345444'
         assert '{}_job_template_id'.format(name) in data
         assert data['{}_job_template_id'.format(name)] == 92
         assert data['{}_job_template_name'.format(name)] == 'jobs-jt'
Ejemplo n.º 18
0
    cred = Credential.objects.all()[:1].get()
    assert cred.inputs['username'] == 'joe'
    assert 'password' not in cred.inputs


@pytest.mark.django_db
@pytest.mark.parametrize(
    'relation, related_obj',
    [
        ['ad_hoc_commands', AdHocCommand()],
        ['unifiedjobs', Job()],
        ['unifiedjobtemplates', JobTemplate()],
        ['unifiedjobtemplates',
         InventorySource(source='ec2')],
        ['projects', Project()],
        ['workflowjobnodes', WorkflowJobNode()],
    ],
)
def test_credential_type_mutability(patch, organization, admin,
                                    credentialtype_ssh, credentialtype_aws,
                                    relation, related_obj):
    cred = Credential(credential_type=credentialtype_ssh,
                      name='Best credential ever',
                      organization=organization,
                      inputs={
                          'username': u'jim',
                          'password': u'pass'
                      })
    cred.save()
Ejemplo n.º 19
0
def test_team_admin_member_access(team, user, project):
    u = user('team_admin', False)
    team.member_role.children.add(project.use_role)
    team.admin_role.members.add(u)

    assert len(Project.accessible_objects(u, 'use_role')) == 1
Ejemplo n.º 20
0
def project(organization):
    p = Project(name='unit-test-proj', organization=organization)
    apply_fake_roles(p)
    return p
Ejemplo n.º 21
0
def project_unit():
    return Project(name='example-proj')
Ejemplo n.º 22
0
    def handle(self, *args, **kwargs):
        changed = False

        # Create a default organization as the first superuser found.
        try:
            superuser = User.objects.filter(
                is_superuser=True).order_by('pk')[0]
        except IndexError:
            superuser = None
        with impersonate(superuser):
            with disable_computed_fields():
                if not Organization.objects.exists():
                    o, _ = Organization.objects.get_or_create(name='Default')

                    # Avoid calling directly the get_or_create() to bypass project update
                    p = Project.objects.filter(name='Demo Project',
                                               scm_type='git').first()
                    if not p:
                        p = Project(
                            name='Demo Project',
                            scm_type='git',
                            scm_url=
                            'https://github.com/ansible/ansible-tower-samples',
                            scm_update_cache_timeout=0,
                            status='successful',
                            scm_revision=
                            '347e44fea036c94d5f60e544de006453ee5c71ad',
                            playbook_files=['hello_world.yml'],
                        )

                    p.organization = o
                    p.save(skip_update=True)

                    ssh_type = CredentialType.objects.filter(
                        namespace='ssh').first()
                    c, _ = Credential.objects.get_or_create(
                        credential_type=ssh_type,
                        name='Demo Credential',
                        inputs={'username': superuser.username},
                        created_by=superuser)

                    c.admin_role.members.add(superuser)

                    public_galaxy_credential, _ = Credential.objects.get_or_create(
                        name='Ansible Galaxy',
                        managed=True,
                        credential_type=CredentialType.objects.get(
                            kind='galaxy'),
                        inputs={'url': 'https://galaxy.ansible.com/'},
                    )
                    o.galaxy_credentials.add(public_galaxy_credential)

                    i, _ = Inventory.objects.get_or_create(
                        name='Demo Inventory',
                        organization=o,
                        created_by=superuser)

                    Host.objects.get_or_create(
                        name='localhost',
                        inventory=i,
                        variables=
                        "ansible_connection: local\nansible_python_interpreter: '{{ ansible_playbook_python }}'",
                        created_by=superuser,
                    )

                    jt = JobTemplate.objects.filter(
                        name='Demo Job Template').first()
                    if jt:
                        jt.project = p
                        jt.inventory = i
                        jt.playbook = 'hello_world.yml'
                        jt.save()
                    else:
                        jt, _ = JobTemplate.objects.get_or_create(
                            name='Demo Job Template',
                            playbook='hello_world.yml',
                            project=p,
                            inventory=i)
                    jt.credentials.add(c)

                    print('Default organization added.')
                    print(
                        'Demo Credential, Inventory, and Job Template added.')
                    changed = True

        if changed:
            print('(changed: True)')
        else:
            print('(changed: False)')
Ejemplo n.º 23
0
def test_project_unique_together_with_org(organization):
    proj1 = Project(name='foo', organization=organization)
    proj1.save()
    proj2 = Project(name='foo', organization=organization)
    with pytest.raises(ValidationError):
        proj2.validate_unique()
    proj2 = Project(name='foo', organization=None)
    proj2.validate_unique()
def _mk_project_update():
    project = Project()
    project.save()
    return ProjectUpdate(project=project)