Repository: ansible/ansible

Issue:
[k8s] Can't create Projects with low-permissioned users 
<!---
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
<!--- Explain the problem briefly -->

Users can create projects using the `oc new-project` command, which creates a `ProjectRequest` object. The old Ansible module (`openshift_raw`) would automatically translate Project creation into ProjectRequest creation. 

Even if you specify the ProjectRequest instead of Project kind, the request will still fail because the `get` will 403 (the user is not allowed to get a specific ProjectRequest).
##### 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-->
k8s
##### ANSIBLE VERSION
<!--- Paste, BELOW THIS COMMENT, verbatim output from "ansible --version" between quotes below -->
```
ansible 2.6.0
  config file = /home/fabian/tmp/reproducer/forklift/containers/ansible.cfg
  configured module search path = [u'/home/fabian/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  ansible python module location = /home/fabian/Envs/system/lib/python2.7/site-packages/ansible
  executable location = /home/fabian/Envs/system/bin/ansible
  python version = 2.7.15 (default, May 15 2018, 15:37:31) [GCC 7.3.1 20180303 (Red Hat 7.3.1-5)]

```

`##### 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).-->
```
ANSIBLE_NOCOWS(env: ANSIBLE_NOCOWS) = True
DEFAULT_HOST_LIST(/home/fabian/tmp/reproducer/forklift/containers/ansible.cfg) = [u'/home/fabian/tmp/reproducer/forklift/inventories']
DEFAULT_ROLES_PATH(/home/fabian/tmp/reproducer/forklift/containers/ansible.cfg) = [u'/home/fabian/tmp/reproducer/forklift/containers/deploy', u'/home/fabian/tmp/reproducer/forklift/roles']
DEFAULT_STDOUT_CALLBACK(/home/fabian/tmp/reproducer/forklift/containers/ansible.cfg) = debug
DEFAULT_VERBOSITY(/home/fabian/tmp/reproducer/forklift/containers/ansible.cfg) = 1
HOST_KEY_CHECKING(/home/fabian/tmp/reproducer/forklift/containers/ansible.cfg) = False
RETRY_FILES_ENABLED(/home/fabian/tmp/reproducer/forklift/containers/ansible.cfg) = False
```

##### 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.-->
`
fedora 27
OpenShift 3.10

##### 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: localhost
  tasks:
  - name: project foreman
    k8s:
      state: present
      definition:
        apiVersion: project.openshift.io/v1
        kind: Project
        metadata:
          name: test
```

<!--- You can also paste gist.github.com links for larger files -->

##### EXPECTED RESULTS
<!--- What did you expect to happen when running the steps above? -->
Project creation success
##### ACTUAL RESULTS
<!--- What actually happened? If possible run with extra verbosity (-vvvv) -->
403 failure
<!--- Paste verbatim command output between quotes below -->
```
PLAY [localhost] *************************************************************************************************************************************************************************************************************************************************************************

TASK [Gathering Facts] *******************************************************************************************************************************************************************************************************************************************************************
ok: [localhost]

TASK [project foreman] *******************************************************************************************************************************************************************************************************************************************************************
fatal: [localhost]: FAILED! => {
    "changed": false, 
    "error": 403, 
    "reason": "Forbidden", 
    "status": 403
}

MSG:

Failed to retrieve requested object: {"kind":"Status","apiVersion":"v1","metadata":{},"status":"Failure","message":"projects.project.openshift.io \"test\" is forbidden: User \"developer\" cannot get projects.project.openshift.io in the namespace \"test\": User \"developer\" cannot get project \"test\"","reason":"Forbidden","details":{"name":"test","group":"project.openshift.io","kind":"projects"},"code":403}



PLAY RECAP *******************************************************************************************************************************************************************************************************************************************************************************
localhost                  : ok=1    changed=0    unreachable=0    failed=1   

```



Discussion:
Files identified in the description:
* [lib/ansible/modules/clustering/k8s/k8s.py](https://github.com/ansible/ansible/blob/devel/lib/ansible/modules/clustering/k8s/k8s.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 @chouseknecht @flaper87 @maxamillion
[click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md)
<!--- boilerplate: notify --->

Resolving patch:
diff --git a/lib/ansible/module_utils/k8s/raw.py b/lib/ansible/module_utils/k8s/raw.py
--- a/lib/ansible/module_utils/k8s/raw.py
+++ b/lib/ansible/module_utils/k8s/raw.py
@@ -26,7 +26,7 @@
 
 try:
     import yaml
-    from openshift.dynamic.exceptions import DynamicApiError, NotFoundError, ConflictError
+    from openshift.dynamic.exceptions import DynamicApiError, NotFoundError, ConflictError, ForbiddenError
 except ImportError:
     # Exceptions handled in common
     pass
@@ -112,7 +112,7 @@ def perform_action(self, resource, definition):
 
         self.remove_aliases()
 
-        if definition['kind'].endswith('list'):
+        if definition['kind'].endswith('List'):
             result['result'] = resource.get(namespace=namespace).to_dict()
             result['changed'] = False
             result['method'] = 'get'
@@ -122,6 +122,11 @@ def perform_action(self, resource, definition):
             existing = resource.get(name=name, namespace=namespace)
         except NotFoundError:
             pass
+        except ForbiddenError as exc:
+            if definition['kind'] in ['Project', 'ProjectRequest'] and state != 'absent':
+                return self.create_project_request(definition)
+            self.fail_json(msg='Failed to retrieve requested object: {0}'.format(exc.body),
+                           error=exc.status, status=exc.status, reason=exc.reason)
         except DynamicApiError as exc:
             self.fail_json(msg='Failed to retrieve requested object: {0}'.format(exc.body),
                            error=exc.status, status=exc.status, reason=exc.reason)
@@ -156,6 +161,9 @@ def perform_action(self, resource, definition):
                         self.warn("{0} was not found, but creating it returned a 409 Conflict error. This can happen \
                                   if the resource you are creating does not directly create a resource of the same kind.".format(name))
                         return result
+                    except DynamicApiError as exc:
+                        self.fail_json(msg="Failed to create object: {0}".format(exc.body),
+                                       error=exc.status, status=exc.status, reason=exc.reason)
                 result['result'] = k8s_obj
                 result['changed'] = True
                 result['method'] = 'create'
@@ -195,3 +203,18 @@ def perform_action(self, resource, definition):
             result['method'] = 'patch'
             result['diff'] = diffs
             return result
+
+    def create_project_request(self, definition):
+        definition['kind'] = 'ProjectRequest'
+        result = {'changed': False, 'result': {}}
+        resource = self.find_resource('ProjectRequest', definition['apiVersion'], fail=True)
+        if not self.check_mode:
+            try:
+                k8s_obj = resource.create(definition)
+                result['result'] = k8s_obj.to_dict()
+            except DynamicApiError as exc:
+                self.fail_json(msg="Failed to create object: {0}".format(exc.body),
+                               error=exc.status, status=exc.status, reason=exc.reason)
+        result['changed'] = True
+        result['method'] = 'create'
+        return result


Test patch: