def test_update_user_password(self): user_name = self.user_prefix + '_password' user_email = '*****@*****.**' user = self._create_user(name=user_name, email=user_email, password='******') self.assertIsNotNone(user) self.assertTrue(user['enabled']) # This should work for both v2 and v3 new_user = self.operator_cloud.update_user( user['id'], password='******') self.assertIsNotNone(new_user) self.assertEqual(user['id'], new_user['id']) self.assertEqual(user_name, new_user['name']) self.assertEqual(user_email, new_user['email']) self.assertTrue(new_user['enabled']) self.assertTrue(self.operator_cloud.grant_role( 'Member', user=user['id'], project='demo', wait=True)) self.addCleanup( self.operator_cloud.revoke_role, 'Member', user=user['id'], project='demo', wait=True) self.assertIsNotNone(operator_cloud( cloud=self._demo_name, username=user_name, password='******').keystone_client)
def verify_password(username, password): global shade_opts app.logger.debug('******************** Checking user {} password {}'.format(username, password)) # No auth aka keystone not configured: service is left unsecured if shade_opts.get('auth_type', None) == "None": # Authorized access return True # Keystone authentication required if shade_opts.get('auth_type', None) == "password": my_auth = _get_shade_auth() my_auth['auth']['username'] = username my_auth['auth']['password'] = password # TODO: see if the following line should be uncommented and add # more security but simple HTTP Auth only supports user:passwd # my_auth['auth']['project_name'] = os.getenv('OS_PROJECT_NAME', "") try: cloud = shade.operator_cloud(**my_auth) machines = cloud.list_machines() except Exception as e: app.logger.error('verify_password Got exception: {}'.format(e)) return False # Authorized access return True # Unauthorized access return False
def setUp(self): super(TestDomain, self).setUp() self.cloud = shade.operator_cloud(cloud='devstack-admin') if self.cloud.cloud_config.get_api_version('identity') in ('2', '2.0'): self.skipTest('Identity service does not support domains') self.domain_prefix = self.getUniqueString('domain') self.addCleanup(self._cleanup_domains)
def test_update_user_password(self): user_name = self.user_prefix + '_password' user_email = '*****@*****.**' user = self._create_user(name=user_name, email=user_email, password='******') self.assertIsNotNone(user) self.assertTrue(user['enabled']) # This should work for both v2 and v3 new_user = self.operator_cloud.update_user(user['id'], password='******') self.assertIsNotNone(new_user) self.assertEqual(user['id'], new_user['id']) self.assertEqual(user_name, new_user['name']) self.assertEqual(user_email, new_user['email']) self.assertTrue(new_user['enabled']) self.assertTrue( self.operator_cloud.grant_role('Member', user=user['id'], project='demo', wait=True)) self.addCleanup(self.operator_cloud.revoke_role, 'Member', user=user['id'], project='demo', wait=True) self.assertIsNotNone( operator_cloud(cloud=self._demo_name, username=user_name, password='******').service_catalog)
def main(): argument_spec = openstack_full_argument_spec( name=dict(required=False, default=None), filters=dict(required=False, type='dict', default=None), ) module_kwargs = openstack_module_kwargs(mutually_exclusive=[ ['name', 'filters'], ]) module = AnsibleModule(argument_spec, **module_kwargs) if not HAS_SHADE: module.fail_json(msg='shade is required for this module') try: name = module.params['name'] filters = module.params['filters'] opcloud = shade.operator_cloud(**module.params) if name: # Let's suppose user is passing domain ID try: domains = opcloud.get_domain(name) except: domains = opcloud.search_domains(filters={'name': name}) else: domains = opcloud.search_domains(filters) module.exit_json(changed=False, ansible_facts=dict(openstack_domains=domains)) except shade.OpenStackCloudException as e: module.fail_json(msg=str(e))
def main(): argument_spec = openstack_full_argument_spec( description=dict(required=True, type='str'), service_name=dict(required=True, type='str'), service_type=dict(required=True, type='str'), url=dict(required=True, type='str'), interface=dict(required=True, type='str'), endpoint_region=dict(required=True, type='str')) module = AnsibleModule(argument_spec) try: description = module.params.pop('description') service_name = module.params.pop('service_name') service_type = module.params.pop('service_type') url = module.params.pop('url') interface = module.params.pop('interface') endpoint_region = module.params.pop('endpoint_region') changed = False service = None endpoint = None cloud = shade.operator_cloud(**module.params) for _service in cloud.keystone_client.services.list(): if _service.type == service_type: service = _service if service.name != service_name or \ service.description != description: changed = True cloud.keystone_client.services.update( service, name=service_name, description=description) break else: changed = True service = cloud.keystone_client.services.create( name=service_name, service_type=service_type, description=description) for _endpoint in cloud.keystone_client.endpoints.list(): if _endpoint.service_id == service.id and \ _endpoint.interface == interface: endpoint = _endpoint if endpoint.url != url: changed = True cloud.keystone_client.endpoints.update(endpoint, url=url) break else: changed = True cloud.keystone_client.endpoints.create(service=service.id, url=url, interface=interface, region=endpoint_region) module.exit_json(changed=changed) except Exception: module.exit_json(failed=True, changed=True, msg=repr(traceback.format_exc()))
def main(): argument_spec = openstack_full_argument_spec(password=dict(required=True, type='str'), project=dict(required=True, type='str'), role=dict(required=True, type='str'), user=dict(required=True, type='str')) module = AnsibleModule(argument_spec) try: password = module.params.pop('password') project_name = module.params.pop('project') role_name = module.params.pop('role') user_name = module.params.pop('user') changed = False project = None role = None user = None cloud = shade.operator_cloud(**module.params) for _project in cloud.keystone_client.projects.list(): if _project.name == project_name: project = _project for _role in cloud.keystone_client.roles.list(): if _role.name == role_name: role = _role for _user in cloud.keystone_client.users.list(): if _user.name == user_name: user = _user if not project: changed = True project = cloud.keystone_client.projects.create(name=project_name, domain='default') if not role: changed = True role = cloud.keystone_client.roles.create(name=role_name) if not user: changed = True user = cloud.keystone_client.users.create(name=user_name, password=password, project=project) cloud.keystone_client.roles.grant(role=role, user=user, project=project) module.exit_json(changed=changed) except Exception: module.exit_json(failed=True, changed=True, msg=repr(traceback.format_exc()))
def get_cloud(self): """ Get shade openstack and operator cloud objects :return: cloud, opcloud are the shade openstack and operator objects """ cloud = shade.openstack_cloud() opcloud = shade.operator_cloud() return cloud, opcloud
def get_shade_operator_client(**os_cloud_config): """Get Shade Operator cloud client :return: ``shade.OperatorCloud`` object. """ params = copy.deepcopy(constants.OS_CLOUD_DEFAULT_CONFIG) params.update(os_cloud_config) return shade.operator_cloud(**params)
def main(): argument_spec = openstack_full_argument_spec( state = dict(required=False, default='present', choices=['absent', 'present']), name = dict(required=True), host = dict(required=True), ) module_kwargs = openstack_module_kwargs() module = AnsibleModule( argument_spec, supports_check_mode=True, **module_kwargs) if not HAS_SHADE: module.fail_json(msg='shade is required for this module') state = module.params['state'] name = module.params['name'] hostname_or_id = module.params['host'] try: cloud = shade.operator_cloud(**module.params) agg = _get_aggregate(cloud, name) host = _get_host(cloud, hostname_or_id) if module.check_mode: module.exit_json(changed=_system_state_change(module, agg, host)) if state == 'present': for resource in ((host, hostname_or_id), (agg, name)): if not resource[0]: module.fail_json(msg="No matches found for %s" % resource[1]) if not _host_exists(agg, host): agg = cloud.nova_client.aggregates.add_host( aggregate=agg, host=host.service['host']) changed=True else: changed=False module.exit_json(changed=changed, agg=agg.to_dict(), hosts=agg.hosts) elif state == 'absent': if not host or not agg: module.exit_json(changed=False) elif _host_exists(agg, host): agg = cloud.nova_client.aggregates.remove_host( aggregate=agg, host=host.service['host']) module.exit_json(changed=True) else: module.exit_json(changed=False) except shade.OpenStackCloudException as e: module.fail_json(msg=str(e))
def _build_client(module): """Create and return an Ironic inspector client.""" cloud = shade.operator_cloud(**module.params) session = cloud.cloud_config.get_session() client = ironic_inspector_client.v1.ClientV1( inspector_url=module.params['inspector_url'], session=session, region_name=module.params['region_name'], api_version=ironic_inspector_client.v1.MAX_API_VERSION) return client
def setUp(self): super(TestFlavor, self).setUp() self.demo_cloud = shade.openstack_cloud(cloud="devstack") self.operator_cloud = shade.operator_cloud(cloud="devstack-admin") # Generate a random name for flavors in this test self.new_item_name = "flavor_" + "".join(random.choice(string.ascii_lowercase) for _ in range(5)) self.addCleanup(self._cleanup_flavors)
def main(): argument_spec = openstack_full_argument_spec( name=dict(required=True), description=dict(required=False, default=None), domain_id=dict(required=False, default=None), state=dict(default='present', choices=['absent', 'present']), ) module_kwargs = openstack_module_kwargs() module = AnsibleModule(argument_spec, supports_check_mode=True, **module_kwargs) if not HAS_SHADE: module.fail_json(msg='shade is required for this module') name = module.params.pop('name') description = module.params.pop('description') domain_id = module.params.pop('domain_id') state = module.params.pop('state') try: cloud = shade.operator_cloud(**module.params) if domain_id: group = cloud.get_group(name, filters={'domain_id': domain_id}) else: group = cloud.get_group(name) if module.check_mode: module.exit_json( changed=_system_state_change(state, description, group)) if state == 'present': if group is None: group = cloud.create_group(name=name, description=description, domain=domain_id) changed = True else: if description is not None and group.description != description: group = cloud.update_group(group.id, description=description) changed = True else: changed = False module.exit_json(changed=changed, group=group) elif state == 'absent': if group is None: changed = False else: cloud.delete_group(group.id) changed = True module.exit_json(changed=changed) except shade.OpenStackCloudException as e: module.fail_json(msg=str(e))
def main(): argument_spec = openstack_full_argument_spec( name=dict(required=True), description=dict(default=None), enabled=dict(default=True, type="bool"), state=dict(default="present", choices=["absent", "present"]), ) module_kwargs = openstack_module_kwargs() module = AnsibleModule(argument_spec, supports_check_mode=True, **module_kwargs) if not HAS_SHADE: module.fail_json(msg="shade is required for this module") name = module.params["name"] description = module.params["description"] enabled = module.params["enabled"] state = module.params["state"] try: cloud = shade.operator_cloud(**module.params) domains = cloud.search_domains(filters=dict(name=name)) if len(domains) > 1: module.fail_json(msg="Domain name %s is not unique" % name) elif len(domains) == 1: domain = domains[0] else: domain = None if module.check_mode: module.exit_json(changed=_system_state_change(module, domain)) if state == "present": if domain is None: domain = cloud.create_domain(name=name, description=description, enabled=enabled) changed = True else: if _needs_update(module, domain): domain = cloud.update_domain(domain.id, name=name, description=description, enabled=enabled) changed = True else: changed = False module.exit_json(changed=changed, domain=domain, id=domain.id) elif state == "absent": if domain is None: changed = False else: cloud.delete_domain(domain.id) changed = True module.exit_json(changed=changed) except shade.OpenStackCloudException as e: module.fail_json(msg=str(e))
def main(): argument_spec = openstack_full_argument_spec( state=dict(required=False, default='present', choices=['absent', 'present']), name=dict(required=True), host=dict(required=True), ) module_kwargs = openstack_module_kwargs() module = AnsibleModule(argument_spec, supports_check_mode=True, **module_kwargs) if not HAS_SHADE: module.fail_json(msg='shade is required for this module') state = module.params['state'] name = module.params['name'] hostname_or_id = module.params['host'] try: cloud = shade.operator_cloud(**module.params) agg = _get_aggregate(cloud, name) host = _get_host(cloud, hostname_or_id) if module.check_mode: module.exit_json(changed=_system_state_change(module, agg, host)) if state == 'present': for resource in ((host, hostname_or_id), (agg, name)): if not resource[0]: module.fail_json(msg="No matches found for %s" % resource[1]) if not _host_exists(agg, host): agg = cloud.nova_client.aggregates.add_host( aggregate=agg, host=host.service['host']) changed = True else: changed = False module.exit_json(changed=changed, agg=agg.to_dict(), hosts=agg.hosts) elif state == 'absent': if not host or not agg: module.exit_json(changed=False) elif _host_exists(agg, host): agg = cloud.nova_client.aggregates.remove_host( aggregate=agg, host=host.service['host']) module.exit_json(changed=True) else: module.exit_json(changed=False) except shade.OpenStackCloudException as e: module.fail_json(msg=str(e))
def setUp(self): super(TestServices, self).setUp() self.operator_cloud = operator_cloud(cloud='devstack-admin') # Generate a random name for services in this test self.new_service_name = 'test_' + ''.join( random.choice(string.ascii_lowercase) for _ in range(5)) self.addCleanup(self._cleanup_services)
def main(): argument_spec = openstack_full_argument_spec( password=dict(required=True, type='str'), project=dict(required=True, type='str'), role=dict(required=True, type='str'), user=dict(required=True, type='str') ) module = AnsibleModule(argument_spec) try: password = module.params.pop('password') project_name = module.params.pop('project') role_name = module.params.pop('role') user_name = module.params.pop('user') changed = False project = None role = None user = None cloud = shade.operator_cloud(**module.params) for _project in cloud.keystone_client.projects.list(): if _project.name == project_name: project = _project for _role in cloud.keystone_client.roles.list(): if _role.name == role_name: role = _role for _user in cloud.keystone_client.users.list(): if _user.name == user_name: user = _user if not project: changed = True project = cloud.keystone_client.projects.create( name=project_name, domain='default') if not role: changed = True role = cloud.keystone_client.roles.create(name=role_name) if not user: changed = True user = cloud.keystone_client.users.create(name=user_name, password=password, project=project) cloud.keystone_client.roles.grant(role=role, user=user, project=project) module.exit_json(changed=changed) except Exception: module.exit_json(failed=True, changed=True, msg=repr(traceback.format_exc()))
def setUp(self): super(TestServices, self).setUp() # Shell should have OS-* envvars from openrc, typically loaded by job self.operator_cloud = operator_cloud() # Generate a random name for services in this test self.new_service_name = 'test_' + ''.join( random.choice(string.ascii_lowercase) for _ in range(5)) self.addCleanup(self._cleanup_services)
def setUp(self): super(TestFlavor, self).setUp() # Shell should have OS-* envvars from openrc, typically loaded by job self.operator_cloud = shade.operator_cloud() # Generate a random name for flavors in this test self.new_item_name = 'flavor_' + ''.join( random.choice(string.ascii_lowercase) for _ in range(5)) self.addCleanup(self._cleanup_flavors)
def setUp(self): super(TestEndpoints, self).setUp() self.operator_cloud = operator_cloud(cloud='devstack-admin') # Generate a random name for services and regions in this test self.new_item_name = 'test_' + ''.join( random.choice(string.ascii_lowercase) for _ in range(5)) self.addCleanup(self._cleanup_services) self.addCleanup(self._cleanup_endpoints)
def setUp(self): super(TestFlavor, self).setUp() self.demo_cloud = shade.openstack_cloud(cloud='devstack') self.operator_cloud = shade.operator_cloud(cloud='devstack-admin') # Generate a random name for flavors in this test self.new_item_name = 'flavor_' + ''.join( random.choice(string.ascii_lowercase) for _ in range(5)) self.addCleanup(self._cleanup_flavors)
def main(): argument_spec = openstack_full_argument_spec( name=dict(required=True), description=dict(required=False, default=None), domain_id=dict(required=False, default=None), state=dict(default='present', choices=['absent', 'present']), ) module_kwargs = openstack_module_kwargs() module = AnsibleModule(argument_spec, supports_check_mode=True, **module_kwargs) if not HAS_SHADE: module.fail_json(msg='shade is required for this module') name = module.params.pop('name') description = module.params.pop('description') domain_id = module.params.pop('domain_id') state = module.params.pop('state') try: cloud = shade.operator_cloud(**module.params) if domain_id: group = cloud.get_group(name, filters={'domain_id': domain_id}) else: group = cloud.get_group(name) if module.check_mode: module.exit_json(changed=_system_state_change(state, description, group)) if state == 'present': if group is None: group = cloud.create_group( name=name, description=description, domain=domain_id) changed = True else: if description is not None and group.description != description: group = cloud.update_group( group.id, description=description) changed = True else: changed = False module.exit_json(changed=changed, group=group) elif state == 'absent': if group is None: changed=False else: cloud.delete_group(group.id) changed=True module.exit_json(changed=changed) except shade.OpenStackCloudException as e: module.fail_json(msg=str(e))
def get_operator_cloud(auth=None): ''' Return an operator_cloud ''' if auth is None: auth = __salt__['config.option']('neutron', {}) if 'shade_opcloud' in __context__: if __context__['shade_opcloud'].auth == auth: return __context__['shade_opcloud'] __context__['shade_opcloud'] = shade.operator_cloud(**auth) return __context__['shade_opcloud']
def setUp(self): """Setup Noauth OperatorCloud tests Setup the test to utilize no authentication and an endpoint URL in the auth data. This is permits testing of the basic mechanism that enables Ironic noauth mode to be utilized with Shade. """ super(TestShadeOperatorNoAuth, self).setUp() self.cloud_noauth = shade.operator_cloud( auth_type='None', auth=dict(endpoint="http://localhost:6385"))
def get_operator_cloud(auth=None): """ Return an operator_cloud """ if auth is None: auth = __salt__["config.option"]("keystone", {}) if "shade_opcloud" in __context__: if __context__["shade_opcloud"].auth == auth: return __context__["shade_opcloud"] __context__["shade_opcloud"] = shade.operator_cloud(**auth) return __context__["shade_opcloud"]
def main(): argument_spec = openstack_full_argument_spec( auth_type=dict(required=False), uuid=dict(required=False), name=dict(required=False), mac=dict(required=False), ironic_url=dict(required=False), timeout=dict(default=1200, type='int', required=False), ) module_kwargs = openstack_module_kwargs() module = AnsibleModule(argument_spec, **module_kwargs) if not HAS_SHADE: module.fail_json(msg='shade is required for this module') if StrictVersion(shade.__version__) < StrictVersion('1.0.0'): module.fail_json(msg="To utilize this module, the installed version of" "the shade library MUST be >=1.0.0") if (module.params['auth_type'] in [None, 'None'] and module.params['ironic_url'] is None): module.fail_json(msg="Authentication appears to be disabled, " "Please define an ironic_url parameter") if (module.params['ironic_url'] and module.params['auth_type'] in [None, 'None']): module.params['auth'] = dict( endpoint=module.params['ironic_url'] ) try: cloud = shade.operator_cloud(**module.params) if module.params['name'] or module.params['uuid']: server = cloud.get_machine(_choose_id_value(module)) elif module.params['mac']: server = cloud.get_machine_by_mac(module.params['mac']) else: module.fail_json(msg="The worlds did not align, " "the host was not found as " "no name, uuid, or mac was " "defined.") if server: cloud.inspect_machine(server['uuid'], module.params['wait']) # TODO(TheJulia): diff properties, ?and ports? and determine # if a change occurred. In theory, the node is always changed # if introspection is able to update the record. module.exit_json(changed=True, ansible_facts=server['properties']) else: module.fail_json(msg="node not found.") except shade.OpenStackCloudException as e: module.fail_json(msg=str(e))
def test_ironic_noauth_none_auth_type(self): """Test noauth selection for Ironic in OperatorCloud The new way of doing this is with the keystoneauth none plugin. """ self.cloud_noauth = shade.operator_cloud( auth_type='none', baremetal_endpoint_override="https://bare-metal.example.com") self.cloud_noauth.list_machines() self.assert_calls()
def main(): module = AnsibleModule(argument_spec=openstack_full_argument_spec( password=dict(required=True, type='str'), project=dict(required=True, type='str'), role=dict(required=True, type='str'), user=dict(required=True, type='str'))) try: password = module.params.pop('password') project_name = module.params.pop('project') role_name = module.params.pop('role') user_name = module.params.pop('user') changed = False project = None role = None user = None cloud = shade.operator_cloud(**module.params) for _project in cloud.keystone_client.tenants.list(): if _project.name == project_name: project = _project for _role in cloud.keystone_client.roles.list(): if _role.name == role_name: role = _role for _user in cloud.keystone_client.users.list(): if _user.name == user_name: user = _user if not project: changed = True project = cloud.keystone_client.tenants.create( tenant_name=project_name) if not role: changed = True role = cloud.keystone_client.roles.create(name=role_name) if not user: changed = True user = cloud.keystone_client.users.create(name=user_name, password=password, tenant_id=project.id) cloud.keystone_client.roles.add_user_role(role=role.id, user=user.id, tenant=project.id) module.exit_json(changed=changed) except Exception as e: module.exit_json(failed=True, changed=True, msg=e)
def main(): argument_spec = openstack_full_argument_spec( description=dict(required=True, type='str'), service_name=dict(required=True, type='str'), service_type=dict(required=True, type='str'), admin_url=dict(required=True, type='str'), internal_url=dict(required=True, type='str'), public_url=dict(required=True, type='str'), endpoint_region=dict(required=True, type='str') ) module = AnsibleModule(argument_spec) try: description = module.params.pop('description') service_name = module.params.pop('service_name') service_type = module.params.pop('service_type') admin_url = module.params.pop('admin_url') internal_url = module.params.pop('internal_url') public_url = module.params.pop('public_url') endpoint_region = module.params.pop('endpoint_region') changed = False service = None endpoint = None cloud = shade.operator_cloud(**module.params) for _service in cloud.keystone_client.services.list(): if _service.type == service_type: service = _service if service is not None: for _endpoint in cloud.keystone_client.endpoints.list(): if _endpoint.service_id == service.id: endpoint = _endpoint else: service = cloud.keystone_client.services.create( name=service_name, service_type=service_type, description=description) if endpoint is None: changed = True cloud.keystone_client.endpoints.create( service_id=service.id, adminurl=admin_url, internalurl=internal_url, publicurl=public_url, region=endpoint_region) module.exit_json(changed=changed) except Exception as e: module.exit_json(failed=True, changed=True, msg=e)
def openstack_cloud_from_module(module, min_version=None): from distutils.version import StrictVersion try: import shade except ImportError: module.fail_json(msg='shade is required for this module') if min_version: if StrictVersion(shade.__version__) < StrictVersion(min_version): module.fail_json( msg="To utilize this module, the installed version of" "the shade library MUST be >={min_version}".format( min_version=min_version)) cloud_config = module.params.pop('cloud', None) if isinstance(cloud_config, dict): fail_message = ( "A cloud config dict was provided to the cloud parameter" " but also a value was provided for {param}. If a cloud" " config dict is provided, {param} should be" " excluded.") for param in ('auth', 'region_name', 'verify', 'cacert', 'key', 'api_timeout', 'interface'): if module.params[param] is not None: module.fail_json(fail_message.format(param=param)) if module.params['auth_type'] != 'password': module.fail_json(fail_message.format(param='auth_type')) return shade, shade.operator_cloud(**cloud_config) else: return shade, shade.operator_cloud( cloud=cloud_config, auth_type=module.params['auth_type'], auth=module.params['auth'], region_name=module.params['region_name'], verify=module.params['verify'], cacert=module.params['cacert'], key=module.params['key'], api_timeout=module.params['api_timeout'], interface=module.params['interface'], )
def main(): argument_spec = openstack_full_argument_spec( description=dict(required=True, type='str'), service_name=dict(required=True, type='str'), service_type=dict(required=True, type='str'), url=dict(required=True, type='str'), interface=dict(required=True, type='str'), endpoint_region=dict(required=True, type='str') ) module = AnsibleModule(argument_spec) try: description = module.params.pop('description') service_name = module.params.pop('service_name') service_type = module.params.pop('service_type') url = module.params.pop('url') interface = module.params.pop('interface') endpoint_region = module.params.pop('endpoint_region') changed = False service = None endpoint = None cloud = shade.operator_cloud(**module.params) for _service in cloud.keystone_client.services.list(): if _service.type == service_type: service = _service if service is not None: for _endpoint in cloud.keystone_client.endpoints.list(): if _endpoint.service_id == service.id and \ _endpoint.interface == interface: endpoint = _endpoint else: service = cloud.keystone_client.services.create( name=service_name, service_type=service_type, description=description) if endpoint is None: changed = True cloud.keystone_client.endpoints.create( service=service.id, url=url, interface=interface, region=endpoint_region) module.exit_json(changed=changed) except Exception: module.exit_json(failed=True, changed=True, msg=repr(traceback.format_exc()))
def setUp(self): """Setup Noauth OperatorCloud tests Setup the test to utilize no authentication and an endpoint URL in the auth data. This is permits testing of the basic mechanism that enables Ironic noauth mode to be utilized with Shade. """ super(TestShadeOperatorNoAuth, self).setUp() self.cloud_noauth = shade.operator_cloud( auth_type='None', auth=dict(endpoint="http://localhost:6385") )
def test_ironic_noauth_admin_token_auth_type(self): """Test noauth selection for Ironic in OperatorCloud The old way of doing this was to abuse admin_token. """ self.cloud_noauth = shade.operator_cloud( auth_type='admin_token', auth=dict(endpoint='https://bare-metal.example.com/v1', token='ignored')) self.cloud_noauth.list_machines() self.assert_calls()
def main(): argument_spec = openstack_full_argument_spec( description=dict(required=True, type='str'), service_name=dict(required=True, type='str'), service_type=dict(required=True, type='str'), admin_url=dict(required=True, type='str'), internal_url=dict(required=True, type='str'), public_url=dict(required=True, type='str'), endpoint_region=dict(required=True, type='str')) module = AnsibleModule(argument_spec) try: description = module.params.pop('description') service_name = module.params.pop('service_name') service_type = module.params.pop('service_type') admin_url = module.params.pop('admin_url') internal_url = module.params.pop('internal_url') public_url = module.params.pop('public_url') endpoint_region = module.params.pop('endpoint_region') changed = False service = None endpoint = None cloud = shade.operator_cloud(**module.params) for _service in cloud.keystone_client.services.list(): if _service.type == service_type: service = _service if service is not None: for _endpoint in cloud.keystone_client.endpoints.list(): if _endpoint.service_id == service.id: endpoint = _endpoint else: service = cloud.keystone_client.services.create( name=service_name, service_type=service_type, description=description) if endpoint is None: changed = True cloud.keystone_client.endpoints.create(service_id=service.id, adminurl=admin_url, internalurl=internal_url, publicurl=public_url, region=endpoint_region) module.exit_json(changed=changed) except Exception as e: module.exit_json(failed=True, changed=True, msg=e)
def main(): module = AnsibleModule( argument_spec = openstack_full_argument_spec( password = dict(required=True, type='str'), project = dict(required=True, type='str'), role = dict(required=True, type='str'), user = dict(required=True, type='str') ) ) try: password = module.params.pop('password') project_name = module.params.pop('project') role_name = module.params.pop('role') user_name = module.params.pop('user') changed = False project = None role = None user = None cloud = shade.operator_cloud(**module.params) for _project in cloud.keystone_client.tenants.list(): if _project.name == project_name: project = _project for _role in cloud.keystone_client.roles.list(): if _role.name == role_name: role = _role for _user in cloud.keystone_client.users.list(): if _user.name == user_name: user = _user if not project: changed = True project = cloud.keystone_client.tenants.create(tenant_name=project_name) if not role: changed = True role = cloud.keystone_client.roles.create(name=role_name) if not user: changed = True user = cloud.keystone_client.users.create(name=user_name, password=password, tenant_id=project.id) cloud.keystone_client.roles.add_user_role(role=role.id, user=user.id, tenant=project.id) module.exit_json(changed=changed) except Exception as e: module.exit_json(failed=True, changed=True, msg=e)
def setUp(self): super(TestIdentity, self).setUp() self.cloud = operator_cloud(cloud='devstack-admin') self.role_prefix = 'test_role' + ''.join( random.choice(string.ascii_lowercase) for _ in range(5)) self.user_prefix = self.getUniqueString('user') self.group_prefix = self.getUniqueString('group') self.addCleanup(self._cleanup_users) self.identity_version = \ self.cloud.cloud_config.get_api_version('identity') if self.identity_version not in ('2', '2.0'): self.addCleanup(self._cleanup_groups) self.addCleanup(self._cleanup_roles)
def _build_client(module): """Create and return an Ironic inspector client.""" cloud = shade.operator_cloud(**module.params) session = cloud.cloud_config.get_session() # Ensure the requested API version is supported. # API 1.14 is the latest API version available in Rocky. api_version = (1, 14) client = ironic_inspector_client.v1.ClientV1( inspector_url=module.params['inspector_url'], interface=module.params['interface'], session=session, region_name=module.params['region_name'], api_version=api_version) return client
def main(): argument_spec = openstack_full_argument_spec( nodes_details=dict(type='list', required=True), ironic_url=dict(required=False), ) module_kwargs = openstack_module_kwargs() module = AnsibleModule(argument_spec, **module_kwargs) if not HAS_SHADE: module.fail_json(msg='shade is required for this module') if (module.params['auth_type'] in [None, 'None'] and module.params['ironic_url'] is None): module.fail_json(msg="Authentication appears to be disabled, " "Please define an ironic_url parameter") if (module.params['ironic_url'] and module.params['auth_type'] in [None, 'None']): module.params['auth'] = dict(endpoint=module.params['ironic_url']) try: cloud = shade.operator_cloud(**module.params) nodes_details = module.params['nodes_details'] provision_pending_list = [] provision_failed_list = [] for node in nodes_details: node_name = node['name'] node_details = cloud.get_machine(node_name) if node_details['provision_state'] in [ 'deploying', 'wait call-back' ]: provision_pending_list.append(node_name) if node_details['provision_state'] in ['deploy failed']: node_provision_state = {} node_provision_state['name'] = node_name node_provision_state['provision_state'] = node_details[ 'provision_state'] provision_failed_list.append(node_provision_state) module.exit_json(changed=False, ansible_facts=dict( provision_pending_list=provision_pending_list, provision_failed_list=provision_failed_list)) except shade.OpenStackCloudException as e: module.fail_json(msg=str(e))
def main(): argument_spec = openstack_full_argument_spec( state = dict(required=False, default='present', choices=['absent', 'present']), name = dict(required=True), az = dict(required=False), ) module_kwargs = openstack_module_kwargs() module = AnsibleModule( argument_spec, supports_check_mode=True, **module_kwargs) if not HAS_SHADE: module.fail_json(msg='shade is required for this module') state = module.params['state'] name = module.params['name'] az = module.params['az'] try: cloud = shade.operator_cloud(**module.params) agg = _get_aggregate(cloud, name) if module.check_mode: module.exit_json(changed=_system_state_change(module, agg)) if state == 'present': if not agg: agg = cloud.nova_client.aggregates.create( name=name, availability_zone=az, ) changed=True else: changed=False module.exit_json(changed=changed, agg=agg.to_dict(), id=agg.id) elif state == 'absent': if agg: cloud.nova_client.aggregates.delete(agg) module.exit_json(changed=True) module.exit_json(changed=False) except shade.OpenStackCloudException as e: module.fail_json(msg=str(e))
def main(): argument_spec = openstack_full_argument_spec( name=dict(required=False, default=None), domain=dict(required=False, default=None), filters=dict(required=False, type='dict', default=None), ) module = AnsibleModule(argument_spec) if not HAS_SHADE: module.fail_json(msg='shade is required for this module') try: name = module.params['name'] domain = module.params['domain'] filters = module.params['filters'] opcloud = shade.operator_cloud(**module.params) # module.exit_json(changed=False, ansible_facts=dict( # openstack_prjects=opcloud.cloud_config.get_auth_args())) if domain: try: # We assume admin is passing domain id dom = opcloud.get_domain(domain)['id'] domain = dom except: # If we fail, maybe admin is passing a domain name. # Note that domains have unique names, just like id. dom = opcloud.search_domains(filters={'name': domain}) if dom: domain = dom[0]['id'] else: module.fail_json(msg='Domain name or ID does not exist') if not filters: filters = {} filters['domain_id'] = domain # projects = opcloud.search_projects(name, filters) projects = opcloud.list_projects(name, filters) module.exit_json(changed=False, ansible_facts=dict(openstack_projects=projects)) except shade.OpenStackCloudException as e: module.fail_json(msg=str(e))
def main(): argument_spec = openstack_full_argument_spec( state=dict(required=False, default='present', choices=['absent', 'present']), name=dict(required=True), az=dict(required=False), ) module_kwargs = openstack_module_kwargs() module = AnsibleModule(argument_spec, supports_check_mode=True, **module_kwargs) if not HAS_SHADE: module.fail_json(msg='shade is required for this module') state = module.params['state'] name = module.params['name'] az = module.params['az'] try: cloud = shade.operator_cloud(**module.params) agg = _get_aggregate(cloud, name) if module.check_mode: module.exit_json(changed=_system_state_change(module, agg)) if state == 'present': if not agg: agg = cloud.nova_client.aggregates.create( name=name, availability_zone=az, ) changed = True else: changed = False module.exit_json(changed=changed, agg=agg.to_dict(), id=agg.id) elif state == 'absent': if agg: cloud.nova_client.aggregates.delete(agg) module.exit_json(changed=True) module.exit_json(changed=False) except shade.OpenStackCloudException as e: module.fail_json(msg=str(e))
def main(): argument_spec = openstack_full_argument_spec( auth_type=dict(required=False), uuid=dict(required=False), name=dict(required=False), mac=dict(required=False), ironic_url=dict(required=False), ) module_kwargs = openstack_module_kwargs() module = AnsibleModule(argument_spec, **module_kwargs) if not HAS_SHADE: module.fail_json(msg="shade is required for this module") if module.params["auth_type"] in [None, "None"] and module.params["ironic_url"] is None: module.fail_json(msg="Authentication appears to be disabled, " "Please define an ironic_url parameter") if module.params["ironic_url"] and module.params["auth_type"] in [None, "None"]: module.params["auth"] = dict(endpoint=module.params["ironic_url"]) try: cloud = shade.operator_cloud(**module.params) if module.params["name"] or module.params["uuid"]: server = cloud.get_machine(_choose_id_value(module)) elif module.params["mac"]: server = cloud.get_machine_by_mac(module.params["mac"]) else: module.fail_json( msg="The worlds did not align, " "the host was not found as " "no name, uuid, or mac was " "defined." ) if server: facts = dict(server) new_driver_info = dict() # Rebuild driver_info to remove any password # fields as they can be masked. for key, value in six.iteritems(facts["driver_info"]): if "password" not in key: new_driver_info[key] = value if new_driver_info: facts["driver_info"] = new_driver_info module.exit_json(changed=False, ansible_facts=facts) else: module.fail_json(msg="node not found.") except shade.OpenStackCloudException as e: module.fail_json(msg=e.message)
def main(): argument_spec = openstack_full_argument_spec( name=dict(required=False, default=None), domain=dict(required=False, default=None), filters=dict(required=False, type='dict', default=None), ) module = AnsibleModule(argument_spec) if not HAS_SHADE: module.fail_json(msg='shade is required for this module') try: name = module.params['name'] domain = module.params['domain'] filters = module.params['filters'] opcloud = shade.operator_cloud(**module.params) if domain: try: # We assume admin is passing domain id dom = opcloud.get_domain(domain)['id'] domain = dom except: # If we fail, maybe admin is passing a domain name. # Note that domains have unique names, just like id. dom = opcloud.search_domains(filters={'name': domain}) if dom: domain = dom[0]['id'] else: module.fail_json(msg='Domain name or ID does not exist') if not filters: filters = {} filters['domain_id'] = domain users = opcloud.search_users(name, filters) module.exit_json(changed=False, ansible_facts=dict( openstack_users=users)) except shade.OpenStackCloudException as e: module.fail_json(msg=str(e))
def test_ironic_noauth_none_auth_type(self): """Test noauth selection for Ironic in OperatorCloud The new way of doing this is with the keystoneauth none plugin. """ # NOTE(TheJulia): When we are using the python-ironicclient # library, the library will automatically prepend the URI path # with 'v1'. As such, since we are overriding the endpoint, # we must explicitly do the same as we move away from the # client library. self.cloud_noauth = shade.operator_cloud( auth_type='none', baremetal_endpoint_override="https://bare-metal.example.com/v1") self.cloud_noauth.list_machines() self.assert_calls()
def _process_shade(groups, hostvars): """Retrieve inventory utilizing Shade""" options = _identify_shade_auth() cloud = shade.operator_cloud(**options) machines = cloud.list_machines() node_names = os.environ.get('BIFROST_NODE_NAMES', None) if node_names: node_names = node_names.split(',') for machine in machines: if 'properties' not in machine: machine = cloud.get_machine(machine['uuid']) if machine['name'] is None: name = machine['uuid'] else: name = machine['name'] if node_names and name not in node_names: continue new_machine = {} for key, value in machine.items(): # NOTE(TheJulia): We don't want to pass infomrational links # nor do we want to pass links about the ports since they # are API endpoint URLs. if key not in ['links', 'ports']: new_machine[key] = value # NOTE(TheJulia): Collect network information, enumerate through # and extract important values, presently MAC address. Once done, # return the network information to the inventory. nics = cloud.list_nics_for_machine(machine['uuid']) new_nics = [] for nic in nics: new_nic = {} if 'address' in nic: new_nic['mac'] = nic['address'] new_nics.append(new_nic) new_machine['nics'] = new_nics new_machine['addressing_mode'] = "dhcp" groups['baremetal']['hosts'].append(name) hostvars.update({name: new_machine}) return (groups, hostvars)
def __init__(self, options: argparse.Namespace) -> None: self.options = options self.revoke_role_after_purge = False self.disable_project_after_purge = False self.cloud = None # type: Optional[shade.OpenStackCloud] self.operator_cloud = None # type: Optional[shade.OperatorCloud] if options.purge_own_project: self.cloud = shade.openstack_cloud(argparse=options) self.user_id = self.cloud.keystone_session.get_user_id() self.project_id = self.cloud.keystone_session.get_project_id() else: self.operator_cloud = shade.operator_cloud(argparse=options) self.user_id = self.operator_cloud.keystone_session.get_user_id() project = self.operator_cloud.get_project(options.purge_project) if not project: raise exceptions.OSProjectNotFound( "Unable to find project '{}'".format(options.purge_project) ) self.project_id = project['id'] # If project is not enabled, we must disable it after purge. self.disable_project_after_purge = not project.enabled # Reuse the information passed to get the `OperatorCloud` but # change the project. This way we bind/re-scope to the project # we want to purge, not the project we authenticated to. self.cloud = shade.openstack_cloud( **utils.replace_project_info( self.operator_cloud.cloud_config.config, self.project_id ) ) auth_args = self.cloud.cloud_config.get_auth_args() logging.warning( "Going to list and/or delete resources from project '%s'", options.purge_project or auth_args.get('project_name') or auth_args.get('project_id') )
def main(): argument_spec = openstack_full_argument_spec( name=dict(required=True), state=dict(default='present', choices=['absent', 'present']), ) module_kwargs = openstack_module_kwargs() module = AnsibleModule(argument_spec, supports_check_mode=True, **module_kwargs) if not HAS_SHADE: module.fail_json(msg='shade is required for this module') name = module.params.pop('name') state = module.params.pop('state') try: cloud = shade.operator_cloud(**module.params) role = cloud.get_role(name) if module.check_mode: module.exit_json(changed=_system_state_change(state, role)) if state == 'present': if role is None: role = cloud.create_role(name) changed = True else: changed = False module.exit_json(changed=changed, role=role) elif state == 'absent': if role is None: changed=False else: cloud.delete_role(name) changed=True module.exit_json(changed=changed) except shade.OpenStackCloudException as e: module.fail_json(msg=str(e))
def main(): argument_spec = openstack_full_argument_spec( user=dict(required=True), group=dict(required=True), state=dict(default='present', choices=['absent', 'present']), ) module_kwargs = openstack_module_kwargs() module = AnsibleModule(argument_spec, supports_check_mode=True, **module_kwargs) if not HAS_SHADE: module.fail_json(msg='shade is required for this module') user = module.params['user'] group = module.params['group'] state = module.params['state'] try: cloud = shade.operator_cloud(**module.params) in_group = cloud.is_user_in_group(user, group) if module.check_mode: module.exit_json(changed=_system_state_change(state, in_group)) changed = False if state == 'present': if not in_group: cloud.add_user_to_group(user, group) changed = True elif state == 'absent': if in_group: cloud.remove_user_from_group(user, group) changed=True module.exit_json(changed=changed) except shade.OpenStackCloudException as e: module.fail_json(msg=str(e), extra_data=e.extra_data)
def main(): module = AnsibleModule( argument_spec=openstack_full_argument_spec( password=dict(required=True, type="str"), project=dict(required=True, type="str"), role=dict(required=True, type="str"), user=dict(required=True, type="str"), service=dict(required=True, type="str"), ) ) try: changed = True cloud = shade.operator_cloud(**module.params) getattr(SanityChecks, module.params.pop("service"))(cloud) module.exit_json(changed=changed) except Exception as e: module.exit_json(failed=True, changed=True, msg=e)
def test_update_user_password(self): user_name = self.user_prefix + '_password' user_email = '*****@*****.**' user = self._create_user(name=user_name, email=user_email, password='******') self.assertIsNotNone(user) self.assertTrue(user['enabled']) # This should work for both v2 and v3 new_user = self.cloud.update_user(user['id'], password='******') self.assertIsNotNone(new_user) self.assertEqual(user['id'], new_user['id']) self.assertEqual(user_name, new_user['name']) self.assertEqual(user_email, new_user['email']) self.assertTrue(new_user['enabled']) self.assertIsNotNone(operator_cloud( username=user_name, password='******', auth_url=self.cloud.auth['auth_url']).keystone_client)
def main(): argument_spec = openstack_full_argument_spec( name=dict(required=False, default=None), filters=dict(required=False, type='dict', default=None), ) module_kwargs = openstack_module_kwargs( mutually_exclusive=[ ['name', 'filters'], ] ) module = AnsibleModule(argument_spec, **module_kwargs) if not HAS_SHADE: module.fail_json(msg='shade is required for this module') try: name = module.params['name'] filters = module.params['filters'] opcloud = shade.operator_cloud(**module.params) if name: # Let's suppose user is passing domain ID try: domains = cloud.get_domain(name) except: domains = opcloud.search_domains(filters={'name': name}) else: domains = opcloud.search_domains(filters) module.exit_json(changed=False, ansible_facts=dict( openstack_domains=domains)) except shade.OpenStackCloudException as e: module.fail_json(msg=str(e))
def setUp(self): super(TestIdentity, self).setUp() self.cloud = operator_cloud(cloud='devstack-admin') self.role_prefix = 'test_role' + ''.join( random.choice(string.ascii_lowercase) for _ in range(5)) self.addCleanup(self._cleanup_roles)
def setUp(self): super(TestUsers, self).setUp() self.cloud = shade.operator_cloud(validate=False)