Пример #1
0
    def test_get_client_kwargs(self):
        """Test :meth:`nailgun.config.ServerConfig.get_client_kwargs`.

        Assert that:

        * ``get_client_kwargs`` returns all of the instance attributes from its
          object except the "url" attribute, and
        * no instance attributes from the object are removed.

        """
        for config in CONFIGS2.values():
            target = config.copy()
            target.pop("url")
            target.pop("version", None)
            server_config = ServerConfig(**config)
            self.assertDictEqual(target, server_config.get_client_kwargs())
            self.assertDictEqual(vars(ServerConfig(**config)), vars(server_config))
Пример #2
0
def main():
    """Create an identical user account on a pair of satellites."""
    server_configs = ServerConfig.get('sat1'), ServerConfig.get('sat2')
    for server_config in server_configs:
        org = Organization(server_config).search(
            query={'search': 'name="Default_Organization"'}
        )[0]
        # The LDAP authentication source with an ID of 1 is internal. It is
        # nearly guaranteed to exist and be functioning.
        user = User(
            server_config,
            auth_source=1,  # or: AuthSourceLDAP(server_config, id=1),
            login='******',
            mail='*****@*****.**',
            organization=[org],
            password='******',
        ).create()
        pprint(user.get_values())  # e.g. {'login': '******', …}
Пример #3
0
    def test_init(self):
        """Test instantiating :class:`nailgun.config.ServerConfig`.

        Assert that only provided values become object attributes.

        """
        for config in CONFIGS2.values():
            self.assertEqual(
                _convert_bsc_attrs(config),
                vars(ServerConfig(**config)),
            )
Пример #4
0
    def test_positive_access_entities_from_ldap_org_admin(self, create_ldap):
        """LDAP User can access resources within its taxonomies if assigned
        role has permission for same taxonomies

        :id: 522063ad-8d39-4f05-bfd3-dfa0fa73f4e1

        :steps:

            1. Create Org Admin and assign taxonomies to it
            2. Create LDAP user with same taxonomies as role above
            3. Assign Org Admin role to user above
            4. Login with LDAP user and attempt to access resources

        :expectedresults: LDAP User should be able to access all the resources
            and permissions in taxonomies selected in Org Admin role

        :CaseLevel: System
        """
        role_name = gen_string('alpha')
        default_org_admin = entities.Role().search(
            query={'search': 'name="Organization admin"'})
        org_admin = entities.Role(id=default_org_admin[0].id).clone(
            data={
                'role': {
                    'name': role_name,
                    'organization': create_ldap['org'].name,
                    'location': create_ldap['loc'].name,
                }
            })
        sc = ServerConfig(
            auth=(create_ldap['ldap_user_name'],
                  create_ldap['ldap_user_passwd']),
            url=create_ldap['sat_url'],
            verify=False,
        )
        with pytest.raises(HTTPError):
            entities.Architecture(sc).search()
        user = entities.User().search(
            query={'search': 'login={}'.format(create_ldap['ldap_user_name'])
                   })[0]
        user.role = [entities.Role(id=org_admin['id']).read()]
        user.update(['role'])
        for entity in [
                entities.Architecture,
                entities.Audit,
                entities.Bookmark,
                entities.CommonParameter,
                entities.LibvirtComputeResource,
                entities.OVirtComputeResource,
                entities.VMWareComputeResource,
                entities.Errata,
                entities.OperatingSystem,
        ]:
            entity(sc).search()
def main():
    module = AnsibleModule(
        argument_spec=dict(
            server_url=dict(required=True),
            username=dict(required=True, no_log=True),
            password=dict(required=True, no_log=True),
            verify_ssl=dict(type='bool', default=True),
            name=dict(required=True),
            organization=dict(required=True),
            lifecycle_environment=dict(),
            content_view=dict(),
            subscriptions=dict(type='list'),
            auto_attach=dict(type='bool', default=True),
        ),
        supports_check_mode=True,
    )

    if has_import_error:
        module.fail_json(msg=import_error_msg)

    server_url = module.params['server_url']
    username = module.params['username']
    password = module.params['password']
    verify_ssl = module.params['verify_ssl']
    name = module.params['name']
    organization = module.params['organization']
    lifecycle_environment = module.params['lifecycle_environment']
    content_view = module.params['content_view']
    subscriptions = module.params['subscriptions']
    auto_attach = module.params['auto_attach']

    server = ServerConfig(url=server_url,
                          auth=(username, password),
                          verify=verify_ssl)
    ng = NailGun(server, entities, module)

    # Lets make an connection to the server with username and password
    try:
        org = entities.Organization(server)
        org.search()
    except Exception as e:
        module.fail_json(msg="Failed to connect to Foreman server: %s " % e)

    try:
        changed = ng.activation_key(
            name,
            organization,
            lifecycle_environment=lifecycle_environment,
            content_view=content_view,
            subscriptions=subscriptions,
            auto_attach=auto_attach)
        module.exit_json(changed=changed)
    except Exception as e:
        module.fail_json(msg=e)
Пример #6
0
    def test_positive_delete_manifest_as_another_user(self):
        """Verify that uploaded manifest if visible and deletable
            by a different user than the one who uploaded it

        :id: 4861bdbc-785a-436d-98cf-13cfef7d6907

        :expectedresults: manifest is refreshed

        :BZ: 1669241

        :CaseImportance: Medium
        """
        org = entities.Organization().create()
        user1_password = gen_string('alphanumeric')
        user1 = entities.User(
            admin=True, password=user1_password, organization=[org], default_organization=org
        ).create()
        sc1 = ServerConfig(
            auth=(user1.login, user1_password),
            url=f'https://{settings.server.hostname}',
            verify=False,
        )
        user2_password = gen_string('alphanumeric')
        user2 = entities.User(
            admin=True, password=user2_password, organization=[org], default_organization=org
        ).create()
        sc2 = ServerConfig(
            auth=(user2.login, user2_password),
            url=f'https://{settings.server.hostname}',
            verify=False,
        )
        # use the first admin to upload a manifest
        with manifests.clone() as manifest:
            entities.Subscription(sc1, organization=org).upload(
                data={'organization_id': org.id}, files={'content': manifest.content}
            )
        # try to search and delete the manifest with another admin
        entities.Subscription(sc2, organization=org).delete_manifest(
            data={'organization_id': org.id}
        )
        assert len(Subscription.list({'organization-id': org.id})) == 0
Пример #7
0
def get_nailgun_config():
    """Return a NailGun configuration file constructed from default values.

    :return: A ``nailgun.config.ServerConfig`` object, populated with values
        from ``robottelo.config.settings``.

    """
    return ServerConfig(
        settings.server.get_url(),
        settings.server.get_credentials(),
        verify=False,
    )
Пример #8
0
    def test_sc_v3(self):
        """Test :class:`nailgun.config.ServerConfig`.

        Assert that ``__repr__`` works correctly when ``url`` and ``version``
        are specified.

        """
        targets = (
            "nailgun.config.ServerConfig(url='flim', version='1')",
            "nailgun.config.ServerConfig(version='1', url='flim')",
        )
        self.assertIn(repr(ServerConfig('flim', version='1')), targets)
Пример #9
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            server_url=dict(required=True),
            username=dict(required=True, no_log=True),
            password=dict(required=True, no_log=True),
            verify_ssl=dict(type='bool', default=True),
            product=dict(required=True),
            organization=dict(required=True),
            name=dict(required=True),
            content_type=dict(required=True),
            url=dict(),
            download_policy=dict(
                choices=['background', 'immediate', 'on_demand']),
        ),
        supports_check_mode=True,
    )

    handle_no_nailgun(module, HAS_NAILGUN_PACKAGE)

    server_url = module.params['server_url']
    verify_ssl = module.params['verify_ssl']
    username = module.params['username']
    password = module.params['password']
    product = module.params['product']
    organization = module.params['organization']
    name = module.params['name']
    content_type = module.params['content_type']
    url = module.params['url']
    download_policy = module.params['download_policy']

    server = ServerConfig(url=server_url,
                          auth=(username, password),
                          verify=verify_ssl)
    ng = NailGun(server, entities, module)

    # Lets make an connection to the server with username and password
    try:
        org = entities.Organization(server)
        org.search()
    except Exception as e:
        module.fail_json(msg="Failed to connect to Foreman server: %s " % e)

    try:
        changed = ng.repository(name,
                                content_type,
                                product,
                                organization,
                                url=url,
                                download_policy=download_policy)
        module.exit_json(changed=changed)
    except Exception as e:
        module.fail_json(msg=e)
Пример #10
0
    def _configure_entities(self):
        """Configure NailGun's entity classes.

        Do the following:

        * Set ``entity_mixins.CREATE_MISSING`` to ``True``. This causes method
        ``EntityCreateMixin.create_raw`` to generate values for empty and
        required fields.
        * Set ``nailgun.entity_mixins.DEFAULT_SERVER_CONFIG`` to whatever is
        returned by :meth:`robottelo.helpers.get_nailgun_config`. See
        ``robottelo.entity_mixins.Entity`` for more information on the effects
        of this.
        * Set a default value for ``nailgun.entities.GPGKey.content``.
        * Set the default value for
          ``nailgun.entities.DockerComputeResource.url``
        if either ``docker.internal_url`` or ``docker.external_url`` is set in
        the configuration file.
        """
        entity_mixins.CREATE_MISSING = True
        entity_mixins.DEFAULT_SERVER_CONFIG = ServerConfig(
            self.server.get_url(),
            self.server.get_credentials(),
            verify=False,
        )

        gpgkey_init = entities.GPGKey.__init__

        def patched_gpgkey_init(self, server_config=None, **kwargs):
            """Set a default value on the ``content`` field."""
            gpgkey_init(self, server_config, **kwargs)
            self._fields['content'].default = os.path.join(
                get_project_root(), 'tests', 'foreman', 'data',
                'valid_gpg_key.txt')

        entities.GPGKey.__init__ = patched_gpgkey_init

        # NailGun provides a default value for ComputeResource.url. We override
        # that value if `docker.internal_url` or `docker.external_url` is set.
        docker_url = None
        # Try getting internal url
        docker_url = self.docker.get_unix_socket_url()
        # Try getting external url
        if docker_url is None:
            docker_url = self.docker.external_url
        if docker_url is not None:
            dockercr_init = entities.DockerComputeResource.__init__

            def patched_dockercr_init(self, server_config=None, **kwargs):
                """Set a default value on the ``docker_url`` field."""
                dockercr_init(self, server_config, **kwargs)
                self._fields['url'].default = docker_url

            entities.DockerComputeResource.__init__ = patched_dockercr_init
Пример #11
0
    def test_get(self):
        """Test :meth:`nailgun.config.ServerConfig.get`.

        Assert that the ``auth`` attribute is a tuple.

        """
        for label in CONFIGS.keys():
            open_ = mock_open(read_data=json.dumps(CONFIGS))
            with patch.object(builtins, 'open', open_):
                server_config = ServerConfig.get(label, FILE_PATH)
            if hasattr(server_config, 'auth'):
                self.assertIsInstance(server_config.auth, tuple)
Пример #12
0
def get_nailgun_config(user=None):
    """Return a NailGun configuration file constructed from default values.

    :param user: The ```nailgun.entities.User``` object of an user with additional passwd
        property/attribute

    :return: ``nailgun.config.ServerConfig`` object, populated from user parameter object else
        with values from ``robottelo.config.settings``

    """
    creds = (user.login, user.passwd) if user else settings.server.get_credentials()
    return ServerConfig(settings.server.get_url(), creds, verify=False)
def main():
    module = AnsibleModule(argument_spec=dict(
        server_url=dict(required=True),
        username=dict(required=True, no_log=True),
        password=dict(required=True, no_log=True),
        verify_ssl=dict(type='bool', default=True),
        name=dict(required=True),
        organization=dict(required=True),
        interval=dict(required=True),
        enabled=dict(required=True),
        sync_date=dict(required=True),
        products=dict(type='list', default=[]),
    ),
                           supports_check_mode=True)

    if has_import_error:
        module.fail_json(msg=import_error_msg)

    server_url = module.params['server_url']
    username = module.params['username']
    password = module.params['password']
    verify_ssl = module.params['verify_ssl']
    name = module.params['name']
    organization = module.params['organization']
    interval = module.params['interval']
    enabled = module.params['enabled']
    sync_date = datetime.strptime(module.params['sync_date'],
                                  '%Y-%m-%d %H:%M:%S').replace(tzinfo=pytz.UTC)
    products = module.params['products']

    server = ServerConfig(url=server_url,
                          auth=(username, password),
                          verify=verify_ssl)
    ng = NailGun(server, entities, module)

    # Lets make an connection to the server with username and password
    try:
        org = entities.Organization(server)
        org.search()
    except Exception as e:
        module.fail_json(msg="Failed to connect to Foreman server: %s " % e)

    try:
        changed = ng.sync_plan(name,
                               organization,
                               interval=interval,
                               enabled=enabled,
                               sync_date=sync_date,
                               products=products)
        module.exit_json(changed=changed)
    except Exception as e:
        module.fail_json(msg=e)
Пример #14
0
    def test_get(self):
        """Test :meth:`nailgun.config.ServerConfig.get`.

        Assert that the ``auth`` attribute is a tuple.

        """
        for label in CONFIGS.keys():
            open_ = mock_open(read_data=json.dumps(CONFIGS))
            with patch.object(builtins, 'open', open_):
                server_config = ServerConfig.get(label, FILE_PATH)
            self.assertEqual(type(server_config), ServerConfig)
            if hasattr(server_config, 'auth'):
                self.assertIsInstance(server_config.auth, tuple)
Пример #15
0
def main():
    module = AnsibleModule(argument_spec=dict(
        server_url=dict(required=True),
        username=dict(required=True, no_log=True),
        password=dict(required=True, no_log=True),
        verify_ssl=dict(required=False, type='bool', default=False),
        product=dict(required=True, no_log=False),
        organization=dict(required=True, no_log=False),
        name=dict(required=True, no_log=False),
        content_type=dict(required=True, no_log=False),
        url=dict(required=False, no_log=False),
    ),
                           supports_check_mode=True)

    if not HAS_NAILGUN_PACKAGE:
        module.fail_json(
            msg=
            "Missing required nailgun module (check docs or install with: pip install nailgun"
        )

    server_url = module.params['server_url']
    verify_ssl = module.params['verify_ssl']
    username = module.params['username']
    password = module.params['password']
    product = module.params['product']
    organization = module.params['organization']
    name = module.params['name']
    content_type = module.params['content_type']
    url = module.params['url']

    server = ServerConfig(url=server_url,
                          auth=(username, password),
                          verify=verify_ssl)
    ng = NailGun(server, entities, module)

    # Lets make an connection to the server with username and password
    try:
        org = entities.Organization(server)
        org.search()
    except Exception as e:
        module.fail_json(msg="Failed to connect to Foreman server: %s " % e)

    try:
        changed = ng.repository(name,
                                content_type,
                                product,
                                organization,
                                url=url)
        module.exit_json(changed=changed)
    except Exception as e:
        module.fail_json(msg=e)
Пример #16
0
    def test_positive_access_entities_from_ipa_org_admin(self):
        """LDAP FreeIPA User can access resources within its taxonomies if assigned
        role has permission for same taxonomies

        :id: acc48330-fc84-4970-b722-9b45a3116eed

        :steps:

            1. Create Org Admin and assign taxonomies to it
            2. Create FreeIPA user with same taxonomies as role above
            3. Assign Org Admin role to user above
            4. Login with FreeIPA user and attempt to access resources

        :expectedresults: FreeIPA User should be able to access all the resources
            and permissions in taxonomies selected in Org Admin role

        :CaseLevel: System
        """
        role_name = gen_string('alpha')
        default_org_admin = entities.Role().search(query={'search': 'name="Organization admin"'})
        org_admin = entities.Role(id=default_org_admin[0].id).clone(
            data={
                'role': {
                    'name': role_name,
                    'organization': self.org.name,
                    'location': self.loc.name,
                }
            }
        )
        sc = ServerConfig(
            auth=(self.username, self.ldap_user_passwd), url=self.sat_url, verify=False
        )
        with self.assertRaises(HTTPError):
            entities.Architecture(sc).search()
        user = entities.User().search(query={'search': 'login={}'.format(self.username)})[0]
        user.role = [entities.Role(id=org_admin['id']).read()]
        user.update(['role'])
        with self.assertNotRaises(HTTPError):
            for entity in [
                entities.Architecture,
                entities.Audit,
                entities.Bookmark,
                entities.CommonParameter,
                entities.LibvirtComputeResource,
                entities.OVirtComputeResource,
                entities.VMWareComputeResource,
                entities.ConfigGroup,
                entities.Errata,
                entities.OperatingSystem,
            ]:
                entity(sc).search()
Пример #17
0
def set_api_server_config(sat_host=None, user=None, passwd=None, verify=None):
    """Sets ServerConfig configuration required by nailgun to read entities

    :param str user: The web username of satellite user
        'admin' by default if not provided
    :param str passwd: The web password of satellite user
        'changeme' by default if not provided
    :param bool verify: The ssl verification to connect to satellite host
        False by default if not provided
    """
    sat_host = sat_host or get_setup_data()['sat_host']
    auth = (user or 'admin', passwd or 'changeme')
    url = f'https://{sat_host}'
    verify = verify or False
    ServerConfig(auth=auth, url=url, verify=verify).save()
Пример #18
0
def set_api_server_config(user=None, passwd=None, verify=None):
    """Sets ServerConfig configuration required by nailgun to read entities

    :param str user: The web username of satellite user
        'admin' by default if not provided
    :param str passwd: The web password of satellite user
        'changeme' by default if not provided
    :param bool verify: The ssl verification to connect to satellite host
        False by default if not provided
    """
    sat_host = get_setup_data()['sat_host']
    auth = ('admin' if not user else user,
            'changeme' if not passwd else passwd)
    url = 'https://{}'.format(sat_host)
    verify = False if not verify else verify
    ServerConfig(auth=auth, url=url, verify=verify).save()
def main():
    module = AnsibleModule(
        argument_spec=dict(
            server_url=dict(required=True),
            username=dict(required=True, no_log=True),
            password=dict(required=True, no_log=True),
            verify_ssl=dict(type='bool', default=True),
            src=dict(required=True, type='path', aliases=['file']),
            repository=dict(required=True),
            product=dict(required=True),
            organization=dict(required=True),
        ),
        supports_check_mode=True,
    )

    handle_no_nailgun(module, HAS_NAILGUN_PACKAGE)

    server_url = module.params['server_url']
    username = module.params['username']
    password = module.params['password']
    src = module.params['src']
    repository = module.params['repository']
    product = module.params['product']
    organization = module.params['organization']
    verify_ssl = module.params['verify_ssl']

    server = ServerConfig(url=server_url,
                          auth=(username, password),
                          verify=verify_ssl)
    ng = NailGun(server, entities, module)

    # Lets make an connection to the server with username and password
    try:
        org = entities.Organization(server)
        org.search()
    except Exception as e:
        module.fail_json(msg="Failed to connect to Foreman server: %s " % e)

    try:
        if not module.check_mode:
            ng.upload(src, repository, product, organization)
    except Exception as e:
        module.fail_json(msg=to_native(e))

    module.exit_json(changed=True,
                     result="File successfully uploaded to %s" % repository)
Пример #20
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            server_url=dict(required=True),
            username=dict(required=True, no_log=True),
            password=dict(required=True, no_log=True),
            verify_ssl=dict(type='bool', default=True),
            name=dict(required=True),
            organization=dict(required=True),
            repositories=dict(type='list'),
        ),
        supports_check_mode=True,
    )

    if has_import_error:
        module.fail_json(msg=import_error_msg)

    server_url = module.params['server_url']
    username = module.params['username']
    password = module.params['password']
    verify_ssl = module.params['verify_ssl']
    name = module.params['name']
    organization = module.params['organization']
    repositories = module.params['repositories']

    server = ServerConfig(url=server_url,
                          auth=(username, password),
                          verify=verify_ssl)
    ng = NailGun(server, entities, module)

    # Lets make an connection to the server with username and password
    try:
        org = entities.Organization(server)
        org.search()
    except Exception as e:
        module.fail_json(msg="Failed to connect to Foreman server: %s " % e)

    kwargs = {}
    if repositories:
        kwargs['repositories'] = repositories

    try:
        changed = ng.content_view(name, organization, **kwargs)
        module.exit_json(changed=changed)
    except Exception as e:
        module.fail_json(msg=e)
Пример #21
0
 def _load_nailgun(self, path=None):
     """Check if there is an auto-loadable json config."""
     try:
         server_config = ServerConfig(url='').get(path=path)
     except:
         try:
             server_config = ServerConfig(url='').get(
                 path='config/server_configs.json')
             server_config.save()
         except Exception as e:
             logger.error(e)
     self.nailgun_config(conf=server_config)
Пример #22
0
    def test_positive_create_user_by_org_admin(self):
        """Org Admin can create new users

        :id: f4edbe25-3ee6-46d6-8fca-a04f6ddc8eed

        :steps:

            1. Create Org Admin role and assign any taxonomies to it
            2. Create user and assign above Org Admin role to it
            3. Login with above Org Admin user
            4. Attempt to create new users

        :expectedresults:

            1. Org Admin should be able to create new users
            2. Only Org Admin role should be available to assign to its users
            3. Org Admin should be able to assign Org Admin role to its users

        :BZ: 1538316

        :CaseLevel: Integration
        """
        org_admin = self.create_org_admin_role(orgs=[self.role_org.id],
                                               locs=[self.role_loc.id])
        user_login = gen_string('alpha')
        user_pass = gen_string('alphanumeric')
        user = entities.User(login=user_login,
                             password=user_pass,
                             role=[org_admin.id],
                             organization=[self.role_org],
                             location=[self.role_loc]).create()
        self.assertEqual(user_login, user.login)
        sc_user = ServerConfig(auth=(user_login, user_pass),
                               url=self.sat_url,
                               verify=False)
        user_login = gen_string('alpha')
        user_pass = gen_string('alphanumeric')
        user = entities.User(sc_user,
                             login=user_login,
                             password=user_pass,
                             role=[org_admin.id],
                             organization=[self.role_org],
                             location=[self.role_loc]).create()
        self.assertEqual(user_login, user.login)
        self.assertEqual(org_admin.id, user.role[0].id)
Пример #23
0
    def test_negative_assign_taxonomies_by_org_admin(self):
        """Org Admin doesn't have permissions to assign org to any of
        its entities

        :id: d8586573-70df-4438-937f-4869583a3d58

        :steps:

            1. Create Org Admin role by cloning 'Organization admin' role
            2. Assign an organization A,B and Location A,B to the Org Admin
                role
            3. Create user and assign above Org Admin role
            4. Assign Organization A,B and Location A,B to the user
            5. Login from the new user and attempt to assign organization(s)
                to any resource

        :expectedresults: Org Admin should not be able to assign the
            organizations to any of its resources

        :CaseLevel: Integration
        """
        org_admin = self.create_org_admin_role(orgs=[self.role_org.id],
                                               locs=[self.role_loc.id])
        # Creating resource
        dom_name = gen_string('alpha')
        dom = entities.Domain(name=dom_name,
                              organization=[self.role_org],
                              location=[self.role_loc]).create()
        self.assertEqual(dom_name, dom.name)
        user_login = gen_string('alpha')
        user_pass = gen_string('alphanumeric')
        user = entities.User(login=user_login,
                             password=user_pass,
                             role=[org_admin.id],
                             organization=[self.role_org],
                             location=[self.role_loc]).create()
        self.assertEqual(user_login, user.login)
        sc = ServerConfig(auth=(user_login, user_pass),
                          url=self.sat_url,
                          verify=False)
        # Getting the domain from user1
        dom = entities.Domain(sc, id=dom.id).read()
        dom.organization = [self.filter_org]
        with self.assertRaises(HTTPError):
            dom.update(['organization'])
def main():
    module = AnsibleModule(
        argument_spec=dict(
            server_url=dict(required=True),
            username=dict(required=True, no_log=True),
            password=dict(required=True, no_log=True),
            verify_ssl=dict(type='bool', default=True),
            product=dict(required=True),
            synchronous=dict(type='bool', default=True),
            organization=dict(required=True),
            repository=dict(),
        ),
        supports_check_mode=False,
    )

    handle_no_nailgun(module, HAS_NAILGUN_PACKAGE)

    server_url = module.params['server_url']
    verify_ssl = module.params['verify_ssl']
    username = module.params['username']
    password = module.params['password']
    repository = module.params['repository']
    product = module.params['product']
    synchronous = module.params['synchronous']
    organization = module.params['organization']

    server = ServerConfig(
        url=server_url,
        auth=(username, password),
        verify=verify_ssl
    )
    ng = NailGun(server, entities, module)

    # Lets make an connection to the server with username and password
    try:
        org = entities.Organization(server)
        org.search()
    except Exception as e:
        module.fail_json(msg="Failed to connect to Foreman server: %s " % e)

    try:
        changed = ng.sync(product, organization, synchronous, repository)
        module.exit_json(changed=changed)
    except Exception as e:
        module.fail_json(msg=e)
Пример #25
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            server_url=dict(type='str', required=True),
            username=dict(type='str', required=True, no_log=True),
            password=dict(type='str', required=True, no_log=True),
            entity=dict(type='str', required=True),
            verify_ssl=dict(type='bool', default=False),
            params=dict(type='dict', required=True, no_log=True),
        ),
        supports_check_mode=True,
    )

    if not HAS_NAILGUN_PACKAGE:
        module.fail_json(
            msg=
            "Missing required nailgun module (check docs or install with: pip install nailgun"
        )

    server_url = module.params['server_url']
    username = module.params['username']
    password = module.params['password']
    entity = module.params['entity']
    params = module.params['params']
    verify_ssl = module.params['verify_ssl']

    server = ServerConfig(url=server_url,
                          auth=(username, password),
                          verify=verify_ssl)
    ng = NailGun(server, entities, module)

    # Lets make an connection to the server with username and password
    try:
        org = entities.Organization(server)
        org.search()
    except Exception as e:
        module.fail_json(msg="Failed to connect to Foreman server: %s " %
                         to_native(e),
                         exception=traceback.format_exc())

    if entity == 'organization':
        ng.organization(params)
        module.exit_json(changed=True, result="%s updated" % entity)
    else:
        module.fail_json(changed=False, result="Unsupported entity supplied")
Пример #26
0
    def test_positive_ad_basic_no_roles(self):
        """Login with LDAP Auth- AD for user with no roles/rights

        :id: 3910c6eb-6eff-4ab7-a50d-ba40f5c24c08

        :setup: assure properly functioning AD server for authentication

        :steps: Login to server with an AD user.

        :expectedresults: Log in to foreman successfully but cannot access entities.

        :CaseLevel: System
        """
        sc = ServerConfig(auth=(self.ldap_user_name, self.ldap_user_passwd),
                          url=self.sat_url,
                          verify=False)
        with self.assertRaises(HTTPError):
            entities.Architecture(sc).search()
Пример #27
0
    def test_positive_ipa_basic_no_roles(self):
        """Login with LDAP Auth- FreeIPA for user with no roles/rights

        :id: 901a241d-aa76-4562-ab1a-a752e6fb7ed5

        :setup: assure properly functioning FreeIPA server for authentication

        :steps: Login to server with an FreeIPA user.

        :expectedresults: Log in to foreman successfully but cannot access entities.

        :CaseLevel: System
        """
        sc = ServerConfig(auth=(self.username, self.ldap_user_passwd),
                          url=self.sat_url,
                          verify=False)
        with self.assertRaises(HTTPError):
            entities.Architecture(sc).search()
Пример #28
0
    def test_pre_create_usergroup_with_ldap_user(self, request, default_sat):
        """Create Usergroup in preupgrade version.

        :id: preupgrade-4b11d883-f523-4f38-b65a-650ecd90335c

        :steps:
            1. Create ldap auth pre upgrade.
            2. Login with ldap User in satellite and logout.
            3. Create usergroup and assign ldap user to it.

        :expectedresults: The usergroup, with ldap user as member, should be created successfully.
        """
        authsource = default_sat.api.AuthSourceLDAP(
            onthefly_register=True,
            account=settings.ldap.username,
            account_password=settings.ldap.password,
            base_dn=settings.ldap.basedn,
            groups_base=settings.ldap.grpbasedn,
            attr_firstname=LDAP_ATTR['firstname'],
            attr_lastname=LDAP_ATTR['surname'],
            attr_login=LDAP_ATTR['login_ad'],
            server_type=LDAP_SERVER_TYPE['API']['ad'],
            attr_mail=LDAP_ATTR['mail'],
            name=request.node.name + "_server",
            host=settings.ldap.hostname,
            tls=False,
            port='389',
        ).create()
        assert authsource.name == request.node.name + "_server"
        sc = ServerConfig(
            auth=(settings.ldap.username, settings.ldap.password),
            url=default_sat.url,
            verify=False,
        )

        with pytest.raises(HTTPError):
            entities.User(sc).search()
        user_group = default_sat.api.UserGroup(name=request.node.name +
                                               "_user_group").create()
        user = default_sat.api.User().search(
            query={'search': f'login={settings.ldap.username}'})[0]
        user_group.user = [user]
        user_group = user_group.update(['user'])
        assert user.login == user_group.user[0].read().login
Пример #29
0
    def test_pre_create_usergroup_with_ldap_user(self):
        """Create Usergroup in preupgrade version.

        :steps:
            1. Create ldap auth pre upgrade.
            2. Login with ldap User in satellite and logout.
            3. Create usergroup and assign ldap user to it.

        :expectedresults: The usergroup, with ldap user as member, should be created successfully.
        """
        authsource = entities.AuthSourceLDAP(
            onthefly_register=True,
            account=self.ldap_user_name,
            account_password=self.ldap_user_passwd,
            base_dn=self.base_dn,
            groups_base=self.group_base_dn,
            attr_firstname=LDAP_ATTR['firstname'],
            attr_lastname=LDAP_ATTR['surname'],
            attr_login=LDAP_ATTR['login_ad'],
            server_type=LDAP_SERVER_TYPE['API']['ad'],
            attr_mail=LDAP_ATTR['mail'],
            name=self.server_name,
            host=self.ldap_hostname,
            tls=False,
            port='389',
        ).create()
        self.assertEqual(authsource.name, self.server_name)
        sc = ServerConfig(auth=(self.ldap_user_name, self.ldap_user_passwd),
                          url=self.sat_url,
                          verify=False)
        with self.assertRaises(HTTPError):
            entities.User(sc).search()
        user_group = entities.UserGroup(
            name=self.preupgrade_usergroup).create()
        user = entities.User().search(
            query={'search': 'login={}'.format(self.ldap_user_name)})[0]
        user_group.user = [user]
        user_group = user_group.update(['user'])
        self.assertEqual(user.login, user_group.user[0].read().login)
Пример #30
0
 def nailgun_config(self, conf=None, label='default'):
     """Return the current nailgun config.
     If a new one is passed in, save it and parse the pieces.
     If one isn't passed in and doesn't currently exist, create it.
     """
     if conf:
         # Load the passed in configuration file
         self.NAILGUN['CONFIG'] = conf
         self.NAILGUN['SATHOST'] = conf.url or os.uname()[1]
         self.NAILGUN['SATUSER'], self.NAILGUN['SATPASS'] = (
             conf.auth or ('admin', 'changeme'))
         self.NAILGUN['VERIFY'] = conf.verify or False
         self.NAILGUN['LABEL'] = label
     if not self.NAILGUN.get('CONFIG', None):
         server_conf = ServerConfig(url='')
         server_conf.url = self.NAILGUN.get('SATHOST', 'https://localhost')
         server_conf.auth = (self.NAILGUN.get('SATUSER', 'admin'),
                             self.NAILGUN.get('SATPASS', 'changeme'))
         server_conf.verify = self.NAILGUN.get('VERIFY', False)
         server_conf.save(label=self.NAILGUN.get('LABEL', label))
         self.NAILGUN['CONFIG'] = server_conf
     return self.NAILGUN['CONFIG']
Пример #31
0
    def test_negative_create_taxonomies_by_org_admin(self):
        """Org Admin cannot define/create organizations but can create
            locations

        :id: 56d9e204-395c-4d6a-b821-43c2f4fe8822

        :steps:

            1. Create Org Admin role and assign any taxonomies to it
            2. Create user and assign above Org Admin role to it
            3. Login with above Org Admin user
            4. Attempt to create Organizations and locations

        :expectedresults:

            1. Org Admin should not have access to create organizations
            2. Org Admin should have access to create locations
        """
        org_admin = self.create_org_admin_role(orgs=[self.role_org.id])
        user_login = gen_string('alpha')
        user_pass = gen_string('alphanumeric')
        user = entities.User(login=user_login,
                             password=user_pass,
                             role=[org_admin.id],
                             organization=[self.role_org],
                             location=[self.role_loc]).create()
        self.assertEqual(user_login, user.login)
        sc = ServerConfig(auth=(user_login, user_pass),
                          url=self.sat_url,
                          verify=False)
        with self.assertRaises(HTTPError):
            entities.Organization(sc, name=gen_string('alpha')).create()
        with self.assertNotRaises(HTTPError):
            loc_name = gen_string('alpha')
            loc = entities.Location(sc, name=loc_name).create()
        self.assertEqual(loc_name, loc.name)
Пример #32
0
def create_server(server_url, auth, verify_ssl):
    entity_mixins.DEFAULT_SERVER_CONFIG = ServerConfig(
        url=server_url,
        auth=auth,
        verify=verify_ssl,
    )
Пример #33
0
import os

from dynaconf import Dynaconf
from nailgun.config import ServerConfig
"""
Save the satellite host details in the nailgun server config, that helps to execute
all the nailgun API's
"""

sat_url = f"https://{os.environ.get('satellite_hostname')}"
nailgun_conf = ServerConfig(url=sat_url,
                            auth=('admin', 'changeme'),
                            verify=False)
"""
The dynaconf object use to access the environment variable
"""
settings = Dynaconf(
    envvar_prefix="UPGRADE",
    core_loaders=["YAML"],
    preload=["conf/*.yaml"],
    envless_mode=True,
    lowercase_read=True,
    load_dotenv=True,
)

# Use to create the variant based on the supported satellite version list
# If the to_version is not available then append that version and popped up one older version
# from the list to maintain the variants matrix support
# (supported only 3 released and 1 downstream version)

supported_sat_versions = settings.upgrade.supported_sat_versions