kubeclient_ca.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. ''' kubeclient_ca ansible module '''
  4. import base64
  5. import yaml
  6. from ansible.module_utils.basic import AnsibleModule
  7. DOCUMENTATION = '''
  8. ---
  9. module: kubeclient_ca
  10. short_description: Modify kubeclient certificate-authority-data
  11. author: Andrew Butcher
  12. requirements: [ ]
  13. '''
  14. EXAMPLES = '''
  15. - kubeclient_ca:
  16. client_path: /etc/origin/master/admin.kubeconfig
  17. ca_path: /etc/origin/master/ca-bundle.crt
  18. - slurp:
  19. src: /etc/origin/master/ca-bundle.crt
  20. register: ca_data
  21. - kubeclient_ca:
  22. client_path: /etc/origin/master/admin.kubeconfig
  23. ca_data: "{{ ca_data.content }}"
  24. '''
  25. def main():
  26. ''' Modify kubeconfig located at `client_path`, setting the
  27. certificate authority data to specified `ca_data` or contents of
  28. `ca_path`.
  29. '''
  30. module = AnsibleModule( # noqa: F405
  31. argument_spec=dict(
  32. client_path=dict(required=True),
  33. ca_data=dict(required=False, default=None),
  34. ca_path=dict(required=False, default=None),
  35. backup=dict(required=False, default=True, type='bool'),
  36. ),
  37. supports_check_mode=True,
  38. mutually_exclusive=[['ca_data', 'ca_path']],
  39. required_one_of=[['ca_data', 'ca_path']]
  40. )
  41. client_path = module.params['client_path']
  42. ca_data = module.params['ca_data']
  43. ca_path = module.params['ca_path']
  44. backup = module.params['backup']
  45. try:
  46. with open(client_path) as client_config_file:
  47. client_config_data = yaml.safe_load(client_config_file.read())
  48. if ca_data is None:
  49. with open(ca_path) as ca_file:
  50. ca_data = base64.standard_b64encode(ca_file.read())
  51. changes = []
  52. # Naively update the CA information for each cluster in the
  53. # kubeconfig.
  54. for cluster in client_config_data['clusters']:
  55. if cluster['cluster']['certificate-authority-data'] != ca_data:
  56. cluster['cluster']['certificate-authority-data'] = ca_data
  57. changes.append(cluster['name'])
  58. if not module.check_mode:
  59. if len(changes) > 0 and backup:
  60. module.backup_local(client_path)
  61. with open(client_path, 'w') as client_config_file:
  62. client_config_string = yaml.dump(client_config_data, default_flow_style=False)
  63. client_config_string = client_config_string.replace('\'\'', '""')
  64. client_config_file.write(client_config_string)
  65. return module.exit_json(changed=(len(changes) > 0))
  66. # ignore broad-except error to avoid stack trace to ansible user
  67. # pylint: disable=broad-except
  68. except Exception as error:
  69. return module.fail_json(msg=str(error))
  70. if __name__ == '__main__':
  71. main()