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.

297 lines
7.6 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):
  122. if check and self.exists():
  123. return []
  124. cmd = ['apply']
  125. if not self.filename:
  126. self.module.fail_json(msg='filename required to create')
  127. cmd.append('--filename=' + self.filename)
  128. return self._execute(cmd)
  129. def replace(self):
  130. cmd = ['apply']
  131. if self.force:
  132. cmd.append('--force')
  133. if not self.filename:
  134. self.module.fail_json(msg='filename required to reload')
  135. cmd.append('--filename=' + self.filename)
  136. return self._execute(cmd)
  137. def delete(self):
  138. if not self.force and not self.exists():
  139. return []
  140. cmd = ['delete']
  141. if self.filename:
  142. cmd.append('--filename=' + self.filename)
  143. else:
  144. if not self.resource:
  145. self.module.fail_json(msg='resource required to delete without filename')
  146. cmd.append(self.resource)
  147. if self.name:
  148. cmd.append(self.name)
  149. if self.label:
  150. cmd.append('--selector=' + self.label)
  151. if self.all:
  152. cmd.append('--all')
  153. if self.force:
  154. cmd.append('--ignore-not-found')
  155. return self._execute(cmd)
  156. def exists(self):
  157. cmd = ['get']
  158. if not self.resource:
  159. return False
  160. cmd.append(self.resource)
  161. if self.name:
  162. cmd.append(self.name)
  163. cmd.append('--no-headers')
  164. if self.label:
  165. cmd.append('--selector=' + self.label)
  166. if self.all:
  167. cmd.append('--all-namespaces')
  168. result = self._execute_nofail(cmd)
  169. if not result:
  170. return False
  171. return True
  172. def stop(self):
  173. if not self.force and not self.exists():
  174. return []
  175. cmd = ['stop']
  176. if self.filename:
  177. cmd.append('--filename=' + self.filename)
  178. else:
  179. if not self.resource:
  180. self.module.fail_json(msg='resource required to stop without filename')
  181. cmd.append(self.resource)
  182. if self.name:
  183. cmd.append(self.name)
  184. if self.label:
  185. cmd.append('--selector=' + self.label)
  186. if self.all:
  187. cmd.append('--all')
  188. if self.force:
  189. cmd.append('--ignore-not-found')
  190. return self._execute(cmd)
  191. def main():
  192. module = AnsibleModule(
  193. argument_spec=dict(
  194. name=dict(),
  195. filename=dict(),
  196. namespace=dict(),
  197. resource=dict(),
  198. label=dict(),
  199. server=dict(),
  200. kubectl=dict(),
  201. force=dict(default=False, type='bool'),
  202. all=dict(default=False, type='bool'),
  203. log_level=dict(default=0, type='int'),
  204. state=dict(default='present', choices=['present', 'absent', 'latest', 'reloaded', 'stopped']),
  205. )
  206. )
  207. changed = False
  208. manager = KubeManager(module)
  209. state = module.params.get('state')
  210. if state == 'present':
  211. result = manager.create(check=False)
  212. elif state == 'absent':
  213. result = manager.delete()
  214. elif state == 'reloaded':
  215. result = manager.replace()
  216. elif state == 'stopped':
  217. result = manager.stop()
  218. elif state == 'latest':
  219. result = manager.replace()
  220. else:
  221. module.fail_json(msg='Unrecognized state %s.' % state)
  222. if result:
  223. changed = True
  224. module.exit_json(changed=changed,
  225. msg='success: %s' % (' '.join(result))
  226. )
  227. from ansible.module_utils.basic import * # noqa
  228. if __name__ == '__main__':
  229. main()