Repository: ansible/ansible
Pull request: Set defaults from params after loading files, allowing params to override


##### SUMMARY
<!--- Describe the change, including rationale and design decisions -->
I think this should give parameters to the module priority over incluster/kubeconfig-based authentication.

<!--- If you are fixing an existing issue, please include "Fixes #nnn" in your
commit message and your description; but you should still explain what
the change does.-->

Fixes #43845 

##### ISSUE TYPE
<!--- Pick one below and delete the rest: -->
- Bugfix Pull Request


##### COMPONENT NAME
<!--- Name of the module, plugin, task or feature -->
k8s
##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes below -->
```
ansible 2.7.0.dev0 (k8s-reorder-auth fd7b1b14ce) last updated 2018/08/14 16:29:11 (GMT -400)
  config file = /home/fabian/tmp/reproducer/ansible/ansible.cfg
  configured module search path = [u'/home/fabian/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  ansible python module location = /home/fabian/tmp/reproducer/ansible/lib/ansible
  executable location = /home/fabian/tmp/reproducer/ansible/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)]

```

Problem statement:
k8s verify_ssl=no still verifies certificate.

##### COMPONENT NAME
k8s

##### ANSIBLE VERSION

2.6

##### ACTUAL RESULTS


With ansible 2.6 and kubernetes host that is using invalid ssl with
```
k8s:
    host: "{{ api_host }}"
    state: "present"
    verify_ssl: no
    api_key: "{{ api_key }}"
    resource_definition: "{{ rawDefinition }}"
```
I see
```
fatal: [k8s-deployment-host]: FAILED! => {
    "changed": false,
    "module_stderr": "2018-08-08 23:54:26,597 WARNING Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, u'[SSL: EXCESSIVE_MESSAGE_SIZE] excessive message size (_ssl.c:726)'),)': /version\n2018-08-08 23:54:26,597 WARNING Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, u'[SSL: EXCESSIVE_MESSAGE_SIZE] excessive message size (_ssl.c:726)'),)': /version\n2018-08-08 23:54:27,372 WARNING Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, u'[SSL: EXCESSIVE_MESSAGE_SIZE] excessive message size (_ssl.c:726)'),)': /version\n2018-08-08 23:54:27,372 WARNING Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, u'[SSL: EXCESSIVE_MESSAGE_SIZE] excessive message size (_ssl.c:726)'),)': /version\n2018-08-08 23:54:28,297 WARNING Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, u'[SSL: EXCESSIVE_MESSAGE_SIZE] excessive message size (_ssl.c:726)'),)': /version\n2018-08-08 23:54:28,297 WARNING Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, u'[SSL: EXCESSIVE_MESSAGE_SIZE] excessive message size (_ssl.c:726)'),)': /version\nTraceback (most recent call last):\n  File \"/var/folders/y9/f9hhc4r13mbdk6g9z2fqjxw40000gp/T/ansible_kcvrAN/ansible_module_k8s.py\", line 165, in <module>\n    main()\n  File \"/var/folders/y9/f9hhc4r13mbdk6g9z2fqjxw40000gp/T/ansible_kcvrAN/ansible_module_k8s.py\", line 161, in main\n    KubernetesRawModule().execute_module()\n  File \"/var/folders/y9/f9hhc4r13mbdk6g9z2fqjxw40000gp/T/ansible_kcvrAN/ansible_modlib.zip/ansible/module_utils/k8s/raw.py\", line 70, in execute_module\n  File \"/var/folders/y9/f9hhc4r13mbdk6g9z2fqjxw40000gp/T/ansible_kcvrAN/ansible_modlib.zip/ansible/module_utils/k8s/common.py\", line 164, in get_api_client\n  File \"/usr/local/Cellar/ansible/2.6.2/libexec/lib/python2.7/site-packages/openshift/dynamic/client.py\", line 58, in __init__\n    self._load_server_info()\n  File \"/usr/local/Cellar/ansible/2.6.2/libexec/lib/python2.7/site-packages/openshift/dynamic/client.py\", line 62, in _load_server_info\n    self.__version = {'kubernetes': load_json(self.request('get', '/version'))}\n  File \"/usr/local/Cellar/ansible/2.6.2/libexec/lib/python2.7/site-packages/openshift/dynamic/client.py\", line 255, in request\n    _return_http_data_only=params.get('_return_http_data_only', True)\n  File \"/usr/local/Cellar/ansible/2.6.2/libexec/lib/python2.7/site-packages/kubernetes/client/api_client.py\", line 321, in call_api\n    _return_http_data_only, collection_formats, _preload_content, _request_timeout)\n  File \"/usr/local/Cellar/ansible/2.6.2/libexec/lib/python2.7/site-packages/kubernetes/client/api_client.py\", line 155, in __call_api\n    _request_timeout=_request_timeout)\n  File \"/usr/local/Cellar/ansible/2.6.2/libexec/lib/python2.7/site-packages/kubernetes/client/api_client.py\", line 342, in request\n    headers=headers)\n  File \"/usr/local/Cellar/ansible/2.6.2/libexec/lib/python2.7/site-packages/kubernetes/client/rest.py\", line 231, in GET\n    query_params=query_params)\n  File \"/usr/local/Cellar/ansible/2.6.2/libexec/lib/python2.7/site-packages/kubernetes/client/rest.py\", line 205, in request\n    headers=headers)\n  File \"/usr/local/Cellar/ansible/2.6.2/libexec/lib/python2.7/site-packages/urllib3/request.py\", line 68, in request\n    **urlopen_kw)\n  File \"/usr/local/Cellar/ansible/2.6.2/libexec/lib/python2.7/site-packages/urllib3/request.py\", line 89, in request_encode_url\n    return self.urlopen(method, url, **extra_kw)\n  File \"/usr/local/Cellar/ansible/2.6.2/libexec/lib/python2.7/site-packages/urllib3/poolmanager.py\", line 322, in urlopen\n    response = conn.urlopen(method, u.request_uri, **kw)\n  File \"/usr/local/Cellar/ansible/2.6.2/libexec/lib/python2.7/site-packages/urllib3/connectionpool.py\", line 667, in urlopen\n    **response_kw)\n  File \"/usr/local/Cellar/ansible/2.6.2/libexec/lib/python2.7/site-packages/urllib3/connectionpool.py\", line 667, in urlopen\n    **response_kw)\n  File \"/usr/local/Cellar/ansible/2.6.2/libexec/lib/python2.7/site-packages/urllib3/connectionpool.py\", line 667, in urlopen\n    **response_kw)\n  File \"/usr/local/Cellar/ansible/2.6.2/libexec/lib/python2.7/site-packages/urllib3/connectionpool.py\", line 638, in urlopen\n    _stacktrace=sys.exc_info()[2])\n  File \"/usr/local/Cellar/ansible/2.6.2/libexec/lib/python2.7/site-packages/urllib3/util/retry.py\", line 398, in increment\n    raise MaxRetryError(_pool, url, error or ResponseError(cause))\nurllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='k8s.aureacentral.com', port=6443): Max retries exceeded with url: /version (Caused by SSLError(SSLError(1, u'[SSL: EXCESSIVE_MESSAGE_SIZE] excessive message size (_ssl.c:726)'),))\n",
    "module_stdout": "",
    "msg": "MODULE FAILURE",
    "rc": 1
}
```

Hints from issue discussion:
@sahkaa Greetings! Thanks for taking the time to open this issue. In order for the community to handle your issue effectively, we need a bit more information. 

Here are the items we could not find in your description:
- ansible version
- component name

Please set the description of this issue with this template:
https://raw.githubusercontent.com/ansible/ansible/devel/.github/ISSUE_TEMPLATE.md

[click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md)
<!--- boilerplate: issue_missing_data --->
This is not an issue with validating certs, the issue is that the remote host is violating SSL protocols.  If SSL isn't functioning correctly, communication cannot even begin to happen.

The error being reported is:

```
[SSL: EXCESSIVE_MESSAGE_SIZE] excessive message size (_ssl.c:726)
```
Hi @sivel 
kubectl and raw rest template and even browsers work fine.
cc @chouseknecht @fabianvf @flaper87 @maxamillion @willthames
[click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md)
<!--- boilerplate: notify --->
@sahkaa as far as I know none of those things rule out an openssl issue

What operating system are you using? What openssl version? What pyopenssl version?

What is the result of running openssl s_client -connect $YOUR_KUBE_API:443 (where the kube api host can be seen in kubectl config view clusters)
I get an actual `CERTIFICATE_VERIFY_FAILED` when I'm trying with an self-signed cert and `verify_ssl: no`

```yaml
---
- hosts: cluster
  connection: local

  tasks:
  - name: Create project
    k8s:
      host: "https://{{ ansible_host }}:8443"
      state: present
      verify_ssl: no
      kind: Project
      name: "{{ pd_project }}"
```

```
fatal: [openshift.pd.labs.***]: FAILED! => {"changed": false, "module_stderr": "2018-08-14 13:42:06,190 WARNING Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, u'[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:579)'),)': /version
2018-08-14 13:42:06,190 WARNING Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, u'[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:579)'),)': /version
2018-08-14 13:42:06,377 WARNING Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, u'[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:579)'),)': /version
2018-08-14 13:42:06,377 WARNING Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, u'[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:579)'),)': /version
2018-08-14 13:42:06,541 WARNING Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, u'[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:579)'),)': /version
2018-08-14 13:42:06,541 WARNING Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, u'[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:579)'),)': /version
Traceback (most recent call last):
  File \"/tmp/ansible_2WDT6V/ansible_module_k8s.py\", line 165, in <module>
    main()
  File \"/tmp/ansible_2WDT6V/ansible_module_k8s.py\", line 161, in main
    KubernetesRawModule().execute_module()
  File \"/tmp/ansible_2WDT6V/ansible_modlib.zip/ansible/module_utils/k8s/raw.py\", line 70, in execute_module
  File \"/tmp/ansible_2WDT6V/ansible_modlib.zip/ansible/module_utils/k8s/common.py\", line 164, in get_api_client
  File \"/usr/lib/python2.7/site-packages/openshift/dynamic/client.py\", line 58, in __init__
    self._load_server_info()
  File \"/usr/lib/python2.7/site-packages/openshift/dynamic/client.py\", line 62, in _load_server_info
    self.__version = {'kubernetes': load_json(self.request('get', '/version'))}
  File \"/usr/lib/python2.7/site-packages/openshift/dynamic/client.py\", line 255, in request
    _return_http_data_only=params.get('_return_http_data_only', True)
  File \"/usr/lib/python2.7/site-packages/kubernetes/client/api_client.py\", line 321, in call_api
    _return_http_data_only, collection_formats, _preload_content, _request_timeout)
  File \"/usr/lib/python2.7/site-packages/kubernetes/client/api_client.py\", line 155, in __call_api
    _request_timeout=_request_timeout)
  File \"/usr/lib/python2.7/site-packages/kubernetes/client/api_client.py\", line 342, in request
    headers=headers)
  File \"/usr/lib/python2.7/site-packages/kubernetes/client/rest.py\", line 231, in GET
    query_params=query_params)
  File \"/usr/lib/python2.7/site-packages/kubernetes/client/rest.py\", line 205, in request
    headers=headers)
  File \"/usr/lib/python2.7/site-packages/urllib3/request.py\", line 68, in request
    **urlopen_kw)
  File \"/usr/lib/python2.7/site-packages/urllib3/request.py\", line 89, in request_encode_url
    return self.urlopen(method, url, **extra_kw)
  File \"/usr/lib/python2.7/site-packages/urllib3/poolmanager.py\", line 322, in urlopen
    response = conn.urlopen(method, u.request_uri, **kw)
  File \"/usr/lib/python2.7/site-packages/urllib3/connectionpool.py\", line 667, in urlopen
    **response_kw)
  File \"/usr/lib/python2.7/site-packages/urllib3/connectionpool.py\", line 667, in urlopen
    **response_kw)
  File \"/usr/lib/python2.7/site-packages/urllib3/connectionpool.py\", line 667, in urlopen
    **response_kw)
  File \"/usr/lib/python2.7/site-packages/urllib3/connectionpool.py\", line 638, in urlopen
    _stacktrace=sys.exc_info()[2])
  File \"/usr/lib/python2.7/site-packages/urllib3/util/retry.py\", line 398, in increment
    raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='openshift.pd.labs.***', port=8443): Max retries exceeded with url: /version (Caused by SSLError(SSLError(1, u'[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:579)'),))
", "module_stdout": "", "msg": "MODULE FAILURE", "rc": 1}
```

This is using Ansible 2.6.2 on CentOS 7 and the latest pip openshift (0.6.2)

And openssl output:

```CONNECTED(00000003)
depth=1 CN = openshift-signer@1527268293
verify error:num=19:self signed certificate in certificate chain
---
Certificate chain
 0 s:/CN=128.29.35.7
   i:/CN=openshift-signer@1527268293
 1 s:/CN=openshift-signer@1527268293
   i:/CN=openshift-signer@1527268293
---
Server certificate
-----BEGIN CERTIFICATE-----
MIIEJTCCAw2gAwIBAgIBBjANBgkqhkiG9w0BAQsFADAmMSQwIgYDVQQDDBtvcGVu
c2hpZnQtc2lnbmVyQDE1MjcyNjgyOTMwHhcNMTgwNTI1MTcxMTMzWhcNMjAwNTI0
MTcxMTM0WjAWMRQwEgYDVQQDEwsxMjguMjkuMzUuNzCCASIwDQYJKoZIhvcNAQEB
BQADggEPADCCAQoCggEBALYMdYySA7f81MOB9/VgZMhT0d4akf5WAmmwXzbySN2N
ZBLTIhLzds3eK5KoMx312z7pEk7i/j3+F1UVfHaxea4GSF4VjoAWuqVgHrowppYr
77/vACEpre2D3VGvwmP5QAiObV4rgzMjOuDhSBVK/i8K3DKkxmc54m81EzJSeY8M
bA6Qu1QKZ/UBzrJ4LVBd87ie6DkkMQC8lvp3POEQb8pEFOsWMvDmoCXoaMaMX3g6
fYYxRu6kAL6uMVbCGxI6Ip3n4hBsuN89qv4ymLbM9lUB76FBvMqKmiOvvlzAwIat
EMdc7oSWKq5XPfm99p0EPo/0qrr/dAisg6NRCNeXVxECAwEAAaOCAWwwggFoMA4G
A1UdDwEB/wQEAwIFoDATBgNVHSUEDDAKBggrBgEFBQcDATAMBgNVHRMBAf8EAjAA
MIIBMQYDVR0RBIIBKDCCASSCCmt1YmVybmV0ZXOCEmt1YmVybmV0ZXMuZGVmYXVs
dIIWa3ViZXJuZXRlcy5kZWZhdWx0LnN2Y4Ika3ViZXJuZXRlcy5kZWZhdWx0LnN2
Yy5jbHVzdGVyLmxvY2FsgglvcGVuc2hpZnSCEW9wZW5zaGlmdC5kZWZhdWx0ghVv
cGVuc2hpZnQuZGVmYXVsdC5zdmOCI29wZW5zaGlmdC5kZWZhdWx0LnN2Yy5jbHVz
dGVyLmxvY2FsghtvcGVuc2hpZnQucGQubGFicy5taXRyZS5vcmeCCm9wZW5zaGlm
dDGCHG9wZW5zaGlmdDEucGQubGFicy5taXRyZS5vcmeCCzEyOC4yOS4zNS43ggox
NzIuMzAuMC4xhwSAHSMHhwSsHgABMA0GCSqGSIb3DQEBCwUAA4IBAQC6uyETEcaP
JbkBjX2+GE/rIVcGby8aE/f+oRhHgMUguNZd/7hHW7kpwIyqfTRJejklsxkB5TH6
lQs5KmZ+YI3Xf4fVfPopNUuJrHK6796VKuKCcmStcLP30tDIY3Stb5ZklKG+uYy5
jJcNKQtY6aWgqWkdj/FxpOFqZi47b2KxSBdtzOqizCif7rWjvrhjJyh+aioi+6R7
y3gTtjugWZT54KxhxJiWWKvBtYHGal149P7fXTbM/xggE1MVcs+NAB0yYLgvxCK0
D2dc/lxFlY3NOHvZr61f8j4sgh30p7jBAMfnjiFBZre91lxa2dIWNMN+kB2hh9vG
C5vlD4ZBUjhR
-----END CERTIFICATE-----
subject=/CN=128.29.35.7
issuer=/CN=openshift-signer@1527268293
---
Acceptable client certificate CA names
/CN=openshift-signer@1527268293
/CN=openshift-signer@1527268426
Client Certificate Types: RSA sign, ECDSA sign
Requested Signature Algorithms: RSA+SHA256:ECDSA+SHA256:RSA+SHA384:ECDSA+SHA384:RSA+SHA1:ECDSA+SHA1
Shared Requested Signature Algorithms: RSA+SHA256:ECDSA+SHA256:RSA+SHA384:ECDSA+SHA384:RSA+SHA1:ECDSA+SHA1
Peer signing digest: SHA384
Server Temp Key: ECDH, P-256, 256 bits
---
SSL handshake has read 2536 bytes and written 427 bytes
---
New, TLSv1/SSLv3, Cipher is ECDHE-RSA-AES128-GCM-SHA256
Server public key is 2048 bit
Secure Renegotiation IS supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
SSL-Session:
    Protocol  : TLSv1.2
    Cipher    : ECDHE-RSA-AES128-GCM-SHA256
    Session-ID: ABFD0C94915CB4D984C1998FB8CE5CE73999600A4B556EA9EEE58ADF2AA1C178
    Session-ID-ctx:
    Master-Key: 3C6799A646C1FB3D700E7CE6FD212A48C2D47DF28F110C6BD46295F58F8CF351B08174C3B2DD79AC7F381C7018786513
    Key-Arg   : None
    Krb5 Principal: None
    PSK identity: None
    PSK identity hint: None
    TLS session ticket:
    0000 - 12 5d c5 95 ff 60 6d 5c-bf df f8 5d e6 24 09 8b   .]...`m\...].$..
    0010 - 93 ce 78 b0 50 b9 cd 5d-b8 15 9c c6 a4 57 5a ea   ..x.P..].....WZ.
    0020 - e0 e7 1e db bb 0c d5 d7-00 19 39 83 15 11 96 ab   ..........9.....
    0030 - 7e 91 e1 77 59 c4 99 92-e6 91 81 d2 c2 dc 4d d5   ~..wY.........M.
    0040 - 14 95 d0 d4 c2 00 f1 16-2a 37 61 40 ea cc 57 3d   ........*7a@..W=
    0050 - 54 6a 95 6f fb c5 75 34-6b 20 47 3a 33 37 2b 9a   Tj.o..u4k G:37+.
    0060 - 57 58 17 89 c3 8e 12 6f-a4 26 d2 fa f1 a8 be 5b   WX.....o.&.....[
    0070 - 89 96 0e 13 da 32 81 da-                          .....2..

    Start Time: 1534255398
    Timeout   : 300 (sec)
    Verify return code: 19 (self signed certificate in certificate chain)
---
```
If I comment out [this line](https://github.com/kubernetes-client/python/blob/master/kubernetes/client/rest.py#L106) in the kubernetes client it works. I'm guessing providing a ca bundle forces it to match that bundle even if `verify_ssl` is disabled.
It could also be the order in which we're building the configuration, if there's something in the kubeconfig (or wherever it's pulling the auth from) it could be overriding the verify_ssl argument...
You're right, @fabianvf, if I put a print statement in before [this line](https://github.com/kubernetes-client/python/blob/master/kubernetes/client/rest.py#L68) I can see it in `module_stdout` regardless of whether `verify_ssl` is true or false in my playbook.

Edit: And if I add a manual set of `verify_ssl` to be untruthy prior to that statement it works. So it definitely has to do with propagation of `verify_ssl`. I'll keep digging.
Looks like the kubernetes python module isn't respecting the default configuration. 

`test.py`:
```python
import yaml
import kubernetes
from kubernetes import client, config
from openshift.dynamic import DynamicClient

configuration = kubernetes.client.Configuration()
setattr(configuration, 'verify_ssl', False)
kubernetes.client.Configuration.set_default(configuration)

k8s_client = config.new_client_from_config()
dyn_client = DynamicClient(k8s_client)
v1_services = dyn_client.resources.get(api_version='v1', kind='Service')

service = """
kind: Project
apiVersion: v1
metadata:
  name: testssl
"""

service_data = yaml.load(service)
resp = v1_services.create(body=service_data, namespace='default')

# resp is a ResourceInstance object
print(resp.metadata)
```

Debug logging added in `kube_config.py`:
```python
...
def new_client_from_config(
        config_file=None,
        context=None,
        persist_config=True):
    """Loads configuration the same as load_kube_config but returns an ApiClient
    to be used with any API object. This will allow the caller to concurrently
    talk with multiple clusters."""
    client_config = type.__call__(Configuration)
    print('kube_config.new_client_from_config Configuration._default: ' + str(Configuration._default.verify_ssl))
    print('kube_config.new_client_from_config client_config:: ' + str(client_config.verify_ssl))
    load_kube_config(config_file=config_file, context=context,
                     client_configuration=client_config,
                     persist_config=persist_config)
    return ApiClient(configuration=client_config)
```
Result:
```$ python test.py
kube_config.new_client_from_config Configuration._default: False
kube_config.new_client_from_config client_config:: True
verify_ssl true
2018-08-14 19:01:38,955 WARNING Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, u'[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:579)'),)': /version
```

I filed [this issue](https://github.com/kubernetes-client/python/issues/597) over there.

Commit message: Set defaults from params after loading files, allowing params to override

Patch to review:
diff --git a/lib/ansible/module_utils/k8s/common.py b/lib/ansible/module_utils/k8s/common.py
index edb8fa3aab424b..2954c66fb0edcf 100644
--- a/lib/ansible/module_utils/k8s/common.py
+++ b/lib/ansible/module_utils/k8s/common.py
@@ -139,46 +139,37 @@ def get_api_client(self, **auth_params):
         auth_params = auth_params or getattr(self, 'params', {})
         auth = copy.deepcopy(auth_params)
 
-        configuration = kubernetes.client.Configuration()
+        # Pull authorization settings from environment variables
         for key, value in iteritems(auth_params):
-            if key in auth_args and value is not None:
-                if key == 'api_key':
-                    setattr(configuration, key, {'authorization': "Bearer {0}".format(value)})
-                else:
-                    setattr(configuration, key, value)
-            elif key in auth_args and value is None:
+            if key in auth_args and value is None:
                 env_value = os.getenv('K8S_AUTH_{0}'.format(key.upper()), None)
                 if env_value is not None:
-                    if key == 'api_key':
-                        setattr(configuration, key, {'authorization': "Bearer {0}".format(env_value)})
-                    else:
-                        setattr(configuration, key, env_value)
-                        auth[key] = env_value
-
-        kubernetes.client.Configuration.set_default(configuration)
+                    auth[key] = env_value
 
-        if auth.get('username') and auth.get('password') and auth.get('host'):
-            auth_method = 'params'
-        elif auth.get('api_key') and auth.get('host'):
-            auth_method = 'params'
+        if ((auth.get('username') and auth.get('password') and auth.get('host')) or
+            (auth.get('api_key') and auth.get('host'))):
+            pass
         elif auth.get('kubeconfig') or auth.get('context'):
-            auth_method = 'file'
+            kubernetes.config.load_kube_config(auth.get('kubeconfig'), auth.get('context'))
         else:
-            auth_method = 'default'
-
-        # First try to do incluster config, then kubeconfig
-        if auth_method == 'default':
+            # First try to do incluster config, then kubeconfig
             try:
                 kubernetes.config.load_incluster_config()
-                return DynamicClient(kubernetes.client.ApiClient())
             except kubernetes.config.ConfigException:
-                return DynamicClient(self.client_from_kubeconfig(auth.get('kubeconfig'), auth.get('context')))
+                kubernetes.config.load_kube_config(auth.get('kubeconfig'), auth.get('context'))
 
-        if auth_method == 'file':
-            return DynamicClient(self.client_from_kubeconfig(auth.get('kubeconfig'), auth.get('context')))
 
-        if auth_method == 'params':
-            return DynamicClient(kubernetes.client.ApiClient(configuration))
+        configuration = kubernetes.client.Configuration()
+        for key, value in iteritems(auth):
+            if key in auth_args and value is not None:
+                if key == 'api_key':
+                    setattr(configuration, key, {'authorization': "Bearer {0}".format(value)})
+                else:
+                    setattr(configuration, key, value)
+
+        kubernetes.client.Configuration.set_default(configuration)
+        return DynamicClient(kubernetes.client.ApiClient(configuration))
+
 
     def client_from_kubeconfig(self, config_file, context):
         try:


Code review comments:
diff_hunk: @@ -139,46 +139,37 @@ def get_api_client(self, **auth_params):
         auth_params = auth_params or getattr(self, 'params', {})
         auth = copy.deepcopy(auth_params)
 
-        configuration = kubernetes.client.Configuration()
+        # Pull authorization settings from environment variables
         for key, value in iteritems(auth_params):
-            if key in auth_args and value is not None:
-                if key == 'api_key':
-                    setattr(configuration, key, {'authorization': "Bearer {0}".format(value)})
-                else:
-                    setattr(configuration, key, value)
-            elif key in auth_args and value is None:
+            if key in auth_args and value is None:
                 env_value = os.getenv('K8S_AUTH_{0}'.format(key.upper()), None)
                 if env_value is not None:
-                    if key == 'api_key':
-                        setattr(configuration, key, {'authorization': "Bearer {0}".format(env_value)})
-                    else:
-                        setattr(configuration, key, env_value)
-                        auth[key] = env_value
-
-        kubernetes.client.Configuration.set_default(configuration)
+                    auth[key] = env_value
 
-        if auth.get('username') and auth.get('password') and auth.get('host'):
-            auth_method = 'params'
-        elif auth.get('api_key') and auth.get('host'):
-            auth_method = 'params'
+        if ((auth.get('username') and auth.get('password') and auth.get('host')) or
+            (auth.get('api_key') and auth.get('host'))):
+            pass
         elif auth.get('kubeconfig') or auth.get('context'):
-            auth_method = 'file'
+            kubernetes.config.load_kube_config(auth.get('kubeconfig'), auth.get('context'))
         else:
-            auth_method = 'default'
-
-        # First try to do incluster config, then kubeconfig
-        if auth_method == 'default':
+            # First try to do incluster config, then kubeconfig
             try:
                 kubernetes.config.load_incluster_config()
-                return DynamicClient(kubernetes.client.ApiClient())
             except kubernetes.config.ConfigException:
-                return DynamicClient(self.client_from_kubeconfig(auth.get('kubeconfig'), auth.get('context')))
+                kubernetes.config.load_kube_config(auth.get('kubeconfig'), auth.get('context'))
 
-        if auth_method == 'file':
-            return DynamicClient(self.client_from_kubeconfig(auth.get('kubeconfig'), auth.get('context')))
 
-        if auth_method == 'params':
-            return DynamicClient(kubernetes.client.ApiClient(configuration))
+        configuration = kubernetes.client.Configuration()
+        for key, value in iteritems(auth):
+            if key in auth_args and value is not None:
+                if key == 'api_key':
+                    setattr(configuration, key, {'authorization': "Bearer {0}".format(value)})
+                else:
+                    setattr(configuration, key, value)
+
+        kubernetes.client.Configuration.set_default(configuration)
+        return DynamicClient(kubernetes.client.ApiClient(configuration))
+
 
     def client_from_kubeconfig(self, config_file, context):
path: lib/ansible/module_utils/k8s/common.py
text: @user1:
After this refactor this method is no longer referenced, probably safe to remove?

@author:
Yeah, definitely