You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

300 lines
7.7 KiB

7 years ago
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. DOCUMENTATION = """
  4. ---
  5. module: kube
  6. short_description: Manage Kubernetes Cluster
  7. description:
  8. - Create, replace, remove, and stop resources within a Kubernetes Cluster
  9. version_added: "2.0"
  10. options:
  11. name:
  12. required: false
  13. default: null
  14. description:
  15. - The name associated with resource
  16. filename:
  17. required: false
  18. default: null
  19. description:
  20. - The path and filename of the resource(s) definition file.
  21. kubectl:
  22. required: false
  23. default: null
  24. description:
  25. - The path to the kubectl bin
  26. namespace:
  27. required: false
  28. default: null
  29. description:
  30. - The namespace associated with the resource(s)
  31. resource:
  32. required: false
  33. default: null
  34. description:
  35. - The resource to perform an action on. pods (po), replicationControllers (rc), services (svc)
  36. label:
  37. required: false
  38. default: null
  39. description:
  40. - The labels used to filter specific resources.
  41. server:
  42. required: false
  43. default: null
  44. description:
  45. - The url for the API server that commands are executed against.
  46. force:
  47. required: false
  48. default: false
  49. description:
  50. - A flag to indicate to force delete, replace, or stop.
  51. all:
  52. required: false
  53. default: false
  54. description:
  55. - A flag to indicate delete all, stop all, or all namespaces when checking exists.
  56. log_level:
  57. required: false
  58. default: 0
  59. description:
  60. - Indicates the level of verbosity of logging by kubectl.
  61. state:
  62. required: false
  63. choices: ['present', 'absent', 'latest', 'reloaded', 'stopped']
  64. default: present
  65. description:
  66. - present handles checking existence or creating if definition file provided,
  67. absent handles deleting resource(s) based on other options,
  68. latest handles creating or updating based on existence,
  69. reloaded handles updating resource(s) definition using definition file,
  70. stopped handles stopping resource(s) based on other options.
  71. requirements:
  72. - kubectl
  73. author: "Kenny Jones (@kenjones-cisco)"
  74. """
  75. EXAMPLES = """
  76. - name: test nginx is present
  77. kube: name=nginx resource=rc state=present
  78. - name: test nginx is stopped
  79. kube: name=nginx resource=rc state=stopped
  80. - name: test nginx is absent
  81. kube: name=nginx resource=rc state=absent
  82. - name: test nginx is present
  83. kube: filename=/tmp/nginx.yml
  84. """
  85. class KubeManager(object):
  86. def __init__(self, module):
  87. self.module = module
  88. self.kubectl = module.params.get('kubectl')
  89. if self.kubectl is None:
  90. self.kubectl = module.get_bin_path('kubectl', True)
  91. self.base_cmd = [self.kubectl]
  92. if module.params.get('server'):
  93. self.base_cmd.append('--server=' + module.params.get('server'))
  94. if module.params.get('log_level'):
  95. self.base_cmd.append('--v=' + str(module.params.get('log_level')))
  96. if module.params.get('namespace'):
  97. self.base_cmd.append('--namespace=' + module.params.get('namespace'))
  98. self.all = module.params.get('all')
  99. self.force = module.params.get('force')
  100. self.name = module.params.get('name')
  101. self.filename = module.params.get('filename')
  102. self.resource = module.params.get('resource')
  103. self.label = module.params.get('label')
  104. def _execute(self, cmd):
  105. args = self.base_cmd + cmd
  106. try:
  107. rc, out, err = self.module.run_command(args)
  108. if rc != 0:
  109. self.module.fail_json(
  110. msg='error running kubectl (%s) command (rc=%d): %s' % (' '.join(args), rc, out or err))
  111. except Exception as exc:
  112. self.module.fail_json(
  113. msg='error running kubectl (%s) command: %s' % (' '.join(args), str(exc)))
  114. return out.splitlines()
  115. def _execute_nofail(self, cmd):
  116. args = self.base_cmd + cmd
  117. rc, out, err = self.module.run_command(args)
  118. if rc != 0:
  119. return None
  120. return out.splitlines()
  121. def create(self, check=True, force=True):
  122. if check and self.exists():
  123. return []
  124. cmd = ['apply']
  125. if force:
  126. cmd.append('--force')
  127. if not self.filename:
  128. self.module.fail_json(msg='filename required to create')
  129. cmd.append('--filename=' + self.filename)
  130. return self._execute(cmd)
  131. def replace(self, force=True):
  132. cmd = ['apply']
  133. if force:
  134. cmd.append('--force')
  135. if not self.filename:
  136. self.module.fail_json(msg='filename required to reload')
  137. cmd.append('--filename=' + self.filename)
  138. return self._execute(cmd)
  139. def delete(self):
  140. if not self.force and not self.exists():
  141. return []
  142. cmd = ['delete']
  143. if self.filename:
  144. cmd.append('--filename=' + self.filename)
  145. else:
  146. if not self.resource:
  147. self.module.fail_json(msg='resource required to delete without filename')
  148. cmd.append(self.resource)
  149. if self.name:
  150. cmd.append(self.name)
  151. if self.label:
  152. cmd.append('--selector=' + self.label)
  153. if self.all:
  154. cmd.append('--all')
  155. if self.force:
  156. cmd.append('--ignore-not-found')
  157. return self._execute(cmd)
  158. def exists(self):
  159. cmd = ['get']
  160. if not self.resource:
  161. return False
  162. cmd.append(self.resource)
  163. if self.name:
  164. cmd.append(self.name)
  165. cmd.append('--no-headers')
  166. if self.label:
  167. cmd.append('--selector=' + self.label)
  168. if self.all:
  169. cmd.append('--all-namespaces')
  170. result = self._execute_nofail(cmd)
  171. if not result:
  172. return False
  173. return True
  174. def stop(self):
  175. if not self.force and not self.exists():
  176. return []
  177. cmd = ['stop']
  178. if self.filename:
  179. cmd.append('--filename=' + self.filename)
  180. else:
  181. if not self.resource:
  182. self.module.fail_json(msg='resource required to stop without filename')
  183. cmd.append(self.resource)
  184. if self.name:
  185. cmd.append(self.name)
  186. if self.label:
  187. cmd.append('--selector=' + self.label)
  188. if self.all:
  189. cmd.append('--all')
  190. if self.force:
  191. cmd.append('--ignore-not-found')
  192. return self._execute(cmd)
  193. def main():
  194. module = AnsibleModule(
  195. argument_spec=dict(
  196. name=dict(),
  197. filename=dict(),
  198. namespace=dict(),
  199. resource=dict(),
  200. label=dict(),
  201. server=dict(),
  202. kubectl=dict(),
  203. force=dict(default=False, type='bool'),
  204. all=dict(default=False, type='bool'),
  205. log_level=dict(default=0, type='int'),
  206. state=dict(default='present', choices=['present', 'absent', 'latest', 'reloaded', 'stopped']),
  207. )
  208. )
  209. changed = False
  210. manager = KubeManager(module)
  211. state = module.params.get('state')
  212. if state == 'present':
  213. result = manager.create(check=False)
  214. elif state == 'absent':
  215. result = manager.delete()
  216. elif state == 'reloaded':
  217. result = manager.replace()
  218. elif state == 'stopped':
  219. result = manager.stop()
  220. elif state == 'latest':
  221. result = manager.replace()
  222. else:
  223. module.fail_json(msg='Unrecognized state %s.' % state)
  224. if result:
  225. changed = True
  226. module.exit_json(changed=changed,
  227. msg='success: %s' % (' '.join(result))
  228. )
  229. from ansible.module_utils.basic import * # noqa
  230. if __name__ == '__main__':
  231. main()