Repository: ansible/ansible

Issue:
os_user_role module fails in multidomain environment
<!---
Verify first that your issue/request is not already reported on GitHub.
THIS FORM WILL BE READ BY A MACHINE, COMPLETE ALL SECTIONS AS DESCRIBED.
Also test if the latest release, and devel branch are affected too.
ALWAYS add information AFTER (OUTSIDE) these html comments.
Otherwise it may end up being automatically closed by our bot. -->

##### SUMMARY
In an OpenStack environment with multiple domains and when using keystone (identity) API v3, os_user_role module fails with HTTP 401 "The request you have made requires authentication"

This is essentially a spin-off off #42901 but for a different module.

##### ISSUE TYPE
 - Bug Report

##### COMPONENT NAME
<!--- Insert, BELOW THIS COMMENT, the name of the module, plugin, task or feature.
Do not include extra details here, e.g. "vyos_command" not "the network module vyos_command" or the full path-->
os_user_role

##### ANSIBLE VERSION
<!--- Paste, BELOW THIS COMMENT, verbatim output from "ansible --version" between quotes below -->
```
ansible 2.6.1
  config file = /workspace/ckoester/180715_192801/0001-02040/ansible.cfg
  configured module search path = [u'/home/ckoester/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  ansible python module location = /home/ckoester/ansible26/local/lib/python2.7/site-packages/ansible
  executable location = /home/ckoester/ansible26/bin/ansible
  python version = 2.7.12 (default, Nov 20 2017, 18:23:56) [GCC 5.4.0 20160609]
```

##### CONFIGURATION
<!--- If using Ansible 2.4 or above, paste, BELOW THIS COMMENT, the results of "ansible-config dump --only-changed"
Otherwise, mention any settings you have changed/added/removed in ansible.cfg
(or using the ANSIBLE_* environment variables).-->
N/A

##### OS / ENVIRONMENT
<!--- Mention, BELOW THIS COMMENT, the OS you are running Ansible from, and the OS you are
managing, or say "N/A" for anything that is not platform-specific.
Also mention the specific version of what you are trying to control,
e.g. if this is a network bug the version of firmware on the network device.-->
On Ansible and control host side, no specific platform dependencies.

In order to reproduce this issue, on the OpenStack side (which the os_user module is utilized against):

 - must be using Identity API v3
 - must be a multidomain environment (ie. multiple domains must actually exist)

(Even then, the issue may be reproducible on one openstack environment but not on another, depending on the specific configuration on that environment.)

##### STEPS TO REPRODUCE
<!--- For bugs, show exactly how to reproduce the problem, using a minimal test-case.
For new features, show how the feature would be used. -->

<!--- Paste example playbooks or commands between quotes below -->
```yaml
---
- hosts: inception
  gather_facts: no
  any_errors_fatal: yes
  tasks:
    - name: For debug and illustration, set cloud config here
      set_fact:
        cloud_config:
          auth:
            auth_url: "https://openstack.api.endpoint.url:5000/v3"
            password: "<existing user password>"
            project_name: "<existing user project>"
            username: "<existing username>"
            user_domain_name: "default"
            project_domain_name: "default"
          identity_api_version: 3
          verify: False

    - name: Make user a project admin
      os_user_role:
        cloud: "{{ cloud_config }}"
        state: present
        user: "testuser"
        domain: "default"
        project: "testproject"
        role: admin
```

<!--- You can also paste gist.github.com links for larger files -->

##### EXPECTED RESULTS
<!--- What did you expect to happen when running the steps above? -->
User role is modified

##### ACTUAL RESULTS
<!--- What actually happened? If possible run with extra verbosity (-vvvv) -->

<!--- Paste verbatim command output between quotes below -->
```
TASK [Make user a project admin] ********************************************************************************************************************************************************************************************************************
fatal: [ngena3-inception]: FAILED! => {"changed": false, "extra_data": null, "msg": "HttpException: 401: Client Error for url: https://api-ngena3.client.metacloud.net:5000/v3/users, {\"error\": {\"message\": \"The request you have made requires authentication.\", \"code\": 401, \"title\": \"Unauthorized\"}}"}
```

As described in #42901, the error message is misleading. This is not a simple authentication failure (and the credentials copied in the sample above are not real credentials, naturally). The issue stems from the fact that the user lookup (happening as pre-check for the os_user_role module) does not take into account the domain parameter, and hence fails as per https://bugs.launchpad.net/horizon/+bug/1415588 and similar OpenStack issue reports:

```
   139          if user:
   140              u = cloud.get_user(user)
   141              if u is None:
   142                  module.fail_json(msg="User %s is not valid" % user)
   143              filters['user'] = u['id']
```

Line 140 would need to take the `domain` parameter into account if one has been provided.


Discussion:
Files identified in the description:
* [lib/ansible/modules/cloud/openstack/os_user_role.py](https://github.com/ansible/ansible/blob/devel/lib/ansible/modules/cloud/openstack/os_user_role.py)

If these files are inaccurate, please update the `component name` section of the description or use the `!component` bot command.

[click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md)
<!--- boilerplate: components_banner --->
cc @Shrews @dagnello @emonty @juliakreger @omgjlk @rcarrillocruz @shrews @thingee
[click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md)
<!--- boilerplate: notify --->

Resolving patch:
diff --git a/lib/ansible/modules/cloud/openstack/os_user_role.py b/lib/ansible/modules/cloud/openstack/os_user_role.py
--- a/lib/ansible/modules/cloud/openstack/os_user_role.py
+++ b/lib/ansible/modules/cloud/openstack/os_user_role.py
@@ -136,8 +136,17 @@ def main():
             module.fail_json(msg="Role %s is not valid" % role)
         filters['role'] = r['id']
 
+        if domain:
+            d = cloud.get_domain(domain)
+            if d is None:
+                module.fail_json(msg="Domain %s is not valid" % domain)
+            filters['domain'] = d['id']
         if user:
-            u = cloud.get_user(user)
+            if domain:
+                u = cloud.get_user(user, domain_id=filters['domain'])
+            else:
+                u = cloud.get_user(user)
+
             if u is None:
                 module.fail_json(msg="User %s is not valid" % user)
             filters['user'] = u['id']
@@ -146,14 +155,14 @@ def main():
             if g is None:
                 module.fail_json(msg="Group %s is not valid" % group)
             filters['group'] = g['id']
-        if domain:
-            d = cloud.get_domain(domain)
-            if d is None:
-                module.fail_json(msg="Domain %s is not valid" % domain)
-            filters['domain'] = d['id']
         if project:
             if domain:
                 p = cloud.get_project(project, domain_id=filters['domain'])
+                # OpenStack won't allow us to use both a domain and project as
+                # filter. Once we identified the project (using the domain as
+                # a filter criteria), we need to remove the domain itself from
+                # the filters list.
+                filters.pop('domain')
             else:
                 p = cloud.get_project(project)
 


Test patch: