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.

318 lines
8.3 KiB

  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. api_version:
  47. required: false
  48. choices: ['v1', 'v1beta3']
  49. default: v1
  50. description:
  51. - The API version associated with cluster.
  52. force:
  53. required: false
  54. default: false
  55. description:
  56. - A flag to indicate to force delete, replace, or stop.
  57. all:
  58. required: false
  59. default: false
  60. description:
  61. - A flag to indicate delete all, stop all, or all namespaces when checking exists.
  62. log_level:
  63. required: false
  64. default: 0
  65. description:
  66. - Indicates the level of verbosity of logging by kubectl.
  67. state:
  68. required: false
  69. choices: ['present', 'absent', 'latest', 'reloaded', 'stopped']
  70. default: present
  71. description:
  72. - present handles checking existence or creating if definition file provided,
  73. absent handles deleting resource(s) based on other options,
  74. latest handles creating ore updating based on existence,
  75. reloaded handles updating resource(s) definition using definition file,
  76. stopped handles stopping resource(s) based on other options.
  77. requirements:
  78. - kubectl
  79. author: "Kenny Jones (@kenjones-cisco)"
  80. """
  81. EXAMPLES = """
  82. - name: test nginx is present
  83. kube: name=nginx resource=rc state=present
  84. - name: test nginx is stopped
  85. kube: name=nginx resource=rc state=stopped
  86. - name: test nginx is absent
  87. kube: name=nginx resource=rc state=absent
  88. - name: test nginx is present
  89. kube: filename=/tmp/nginx.yml
  90. """
  91. class KubeManager(object):
  92. def __init__(self, module):
  93. self.module = module
  94. self.kubectl = module.params.get('kubectl')
  95. if self.kubectl is None:
  96. self.kubectl = module.get_bin_path('kubectl', True)
  97. self.base_cmd = [self.kubectl]
  98. self.api_version = module.params.get('api_version')
  99. if self.api_version:
  100. self.base_cmd.append('--api-version=' + self.api_version)
  101. if module.params.get('server'):
  102. self.base_cmd.append('--server=' + module.params.get('server'))
  103. if module.params.get('log_level'):
  104. self.base_cmd.append('--v=' + str(module.params.get('log_level')))
  105. if module.params.get('namespace'):
  106. self.base_cmd.append('--namespace=' + module.params.get('namespace'))
  107. self.all = module.params.get('all')
  108. self.force = module.params.get('force')
  109. self.name = module.params.get('name')
  110. self.filename = module.params.get('filename')
  111. self.resource = module.params.get('resource')
  112. self.label = module.params.get('label')
  113. def _execute(self, cmd):
  114. args = self.base_cmd + cmd
  115. try:
  116. rc, out, err = self.module.run_command(args)
  117. if rc != 0:
  118. self.module.fail_json(
  119. msg='error running kubectl (%s) command (rc=%d): %s' % (' '.join(args), rc, out or err))
  120. except Exception as exc:
  121. self.module.fail_json(
  122. msg='error running kubectl (%s) command: %s' % (' '.join(args), str(exc)))
  123. return out.splitlines()
  124. def _execute_nofail(self, cmd):
  125. args = self.base_cmd + cmd
  126. rc, out, err = self.module.run_command(args)
  127. if rc != 0:
  128. return None
  129. return out.splitlines()
  130. def create(self, check=True):
  131. if check and self.exists():
  132. return []
  133. cmd = ['create']
  134. if not self.filename:
  135. self.module.fail_json(msg='filename required to create')
  136. cmd.append('--filename=' + self.filename)
  137. return self._execute(cmd)
  138. def replace(self):
  139. if not self.force and not self.exists():
  140. return []
  141. cmd = ['replace']
  142. if self.api_version != 'v1':
  143. cmd = ['update']
  144. if self.force:
  145. cmd.append('--force')
  146. if not self.filename:
  147. self.module.fail_json(msg='filename required to reload')
  148. cmd.append('--filename=' + self.filename)
  149. return self._execute(cmd)
  150. def delete(self):
  151. if not self.force and not self.exists():
  152. return []
  153. cmd = ['delete']
  154. if self.filename:
  155. cmd.append('--filename=' + self.filename)
  156. else:
  157. if not self.resource:
  158. self.module.fail_json(msg='resource required to delete without filename')
  159. cmd.append(self.resource)
  160. if self.name:
  161. cmd.append(self.name)
  162. if self.label:
  163. cmd.append('--selector=' + self.label)
  164. if self.all:
  165. cmd.append('--all')
  166. if self.force:
  167. cmd.append('--ignore-not-found')
  168. return self._execute(cmd)
  169. def exists(self):
  170. cmd = ['get']
  171. if not self.resource:
  172. return False
  173. cmd.append(self.resource)
  174. if self.name:
  175. cmd.append(self.name)
  176. cmd.append('--no-headers')
  177. if self.label:
  178. cmd.append('--selector=' + self.label)
  179. if self.all:
  180. cmd.append('--all-namespaces')
  181. result = self._execute_nofail(cmd)
  182. if not result:
  183. return False
  184. return True
  185. def stop(self):
  186. if not self.force and not self.exists():
  187. return []
  188. cmd = ['stop']
  189. if self.filename:
  190. cmd.append('--filename=' + self.filename)
  191. else:
  192. if not self.resource:
  193. self.module.fail_json(msg='resource required to stop without filename')
  194. cmd.append(self.resource)
  195. if self.name:
  196. cmd.append(self.name)
  197. if self.label:
  198. cmd.append('--selector=' + self.label)
  199. if self.all:
  200. cmd.append('--all')
  201. if self.force:
  202. cmd.append('--ignore-not-found')
  203. return self._execute(cmd)
  204. def main():
  205. module = AnsibleModule(
  206. argument_spec=dict(
  207. name=dict(),
  208. filename=dict(),
  209. namespace=dict(),
  210. resource=dict(),
  211. label=dict(),
  212. server=dict(),
  213. kubectl=dict(),
  214. api_version=dict(default='v1', choices=['v1', 'v1beta3']),
  215. force=dict(default=False, type='bool'),
  216. all=dict(default=False, type='bool'),
  217. log_level=dict(default=0, type='int'),
  218. state=dict(default='present', choices=['present', 'absent', 'latest', 'reloaded', 'stopped']),
  219. )
  220. )
  221. changed = False
  222. manager = KubeManager(module)
  223. state = module.params.get('state')
  224. if state == 'present':
  225. result = manager.create()
  226. elif state == 'absent':
  227. result = manager.delete()
  228. elif state == 'reloaded':
  229. result = manager.replace()
  230. elif state == 'stopped':
  231. result = manager.stop()
  232. elif state == 'latest':
  233. if manager.exists():
  234. manager.force = True
  235. result = manager.replace()
  236. else:
  237. result = manager.create(check=False)
  238. else:
  239. module.fail_json(msg='Unrecognized state %s.' % state)
  240. if result:
  241. changed = True
  242. module.exit_json(changed=changed,
  243. msg='success: %s' % (' '.join(result))
  244. )
  245. from ansible.module_utils.basic import * # noqa
  246. if __name__ == '__main__':
  247. main()