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.

314 lines
8.5 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(s).
  21. - To operate on several files this can accept a comma separated list of files or a list of files.
  22. aliases: [ 'files', 'file', 'filenames' ]
  23. kubectl:
  24. required: false
  25. default: null
  26. description:
  27. - The path to the kubectl bin
  28. namespace:
  29. required: false
  30. default: null
  31. description:
  32. - The namespace associated with the resource(s)
  33. resource:
  34. required: false
  35. default: null
  36. description:
  37. - The resource to perform an action on. pods (po), replicationControllers (rc), services (svc)
  38. label:
  39. required: false
  40. default: null
  41. description:
  42. - The labels used to filter specific resources.
  43. server:
  44. required: false
  45. default: null
  46. description:
  47. - The url for the API server that commands are executed against.
  48. force:
  49. required: false
  50. default: false
  51. description:
  52. - A flag to indicate to force delete, replace, or stop.
  53. all:
  54. required: false
  55. default: false
  56. description:
  57. - A flag to indicate delete all, stop all, or all namespaces when checking exists.
  58. log_level:
  59. required: false
  60. default: 0
  61. description:
  62. - Indicates the level of verbosity of logging by kubectl.
  63. state:
  64. required: false
  65. choices: ['present', 'absent', 'latest', 'reloaded', 'stopped']
  66. default: present
  67. description:
  68. - present handles checking existence or creating if definition file provided,
  69. absent handles deleting resource(s) based on other options,
  70. latest handles creating or updating based on existence,
  71. reloaded handles updating resource(s) definition using definition file,
  72. stopped handles stopping resource(s) based on other options.
  73. requirements:
  74. - kubectl
  75. author: "Kenny Jones (@kenjones-cisco)"
  76. """
  77. EXAMPLES = """
  78. - name: test nginx is present
  79. kube: name=nginx resource=rc state=present
  80. - name: test nginx is stopped
  81. kube: name=nginx resource=rc state=stopped
  82. - name: test nginx is absent
  83. kube: name=nginx resource=rc state=absent
  84. - name: test nginx is present
  85. kube: filename=/tmp/nginx.yml
  86. - name: test nginx and postgresql are present
  87. kube: files=/tmp/nginx.yml,/tmp/postgresql.yml
  88. - name: test nginx and postgresql are present
  89. kube:
  90. files:
  91. - /tmp/nginx.yml
  92. - /tmp/postgresql.yml
  93. """
  94. class KubeManager(object):
  95. def __init__(self, module):
  96. self.module = module
  97. self.kubectl = module.params.get('kubectl')
  98. if self.kubectl is None:
  99. self.kubectl = module.get_bin_path('kubectl', True)
  100. self.base_cmd = [self.kubectl]
  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 = [f.strip() for f in module.params.get('filename') or []]
  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), out=\'%s\', err=\'%s\'' % (' '.join(args), rc, out, 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, force=True):
  131. if check and self.exists():
  132. return []
  133. cmd = ['apply']
  134. if force:
  135. cmd.append('--force')
  136. if not self.filename:
  137. self.module.fail_json(msg='filename required to create')
  138. cmd.append('--filename=' + ','.join(self.filename))
  139. return self._execute(cmd)
  140. def replace(self, force=True):
  141. cmd = ['apply']
  142. if force:
  143. cmd.append('--force')
  144. if not self.filename:
  145. self.module.fail_json(msg='filename required to reload')
  146. cmd.append('--filename=' + ','.join(self.filename))
  147. return self._execute(cmd)
  148. def delete(self):
  149. if not self.force and not self.exists():
  150. return []
  151. cmd = ['delete']
  152. if self.filename:
  153. cmd.append('--filename=' + ','.join(self.filename))
  154. else:
  155. if not self.resource:
  156. self.module.fail_json(msg='resource required to delete without filename')
  157. cmd.append(self.resource)
  158. if self.name:
  159. cmd.append(self.name)
  160. if self.label:
  161. cmd.append('--selector=' + self.label)
  162. if self.all:
  163. cmd.append('--all')
  164. if self.force:
  165. cmd.append('--ignore-not-found')
  166. return self._execute(cmd)
  167. def exists(self):
  168. cmd = ['get']
  169. if self.filename:
  170. cmd.append('--filename=' + ','.join(self.filename))
  171. else:
  172. if not self.resource:
  173. self.module.fail_json(msg='resource required without filename')
  174. cmd.append(self.resource)
  175. if self.name:
  176. cmd.append(self.name)
  177. if self.label:
  178. cmd.append('--selector=' + self.label)
  179. if self.all:
  180. cmd.append('--all-namespaces')
  181. cmd.append('--no-headers')
  182. result = self._execute_nofail(cmd)
  183. if not result:
  184. return False
  185. return True
  186. # TODO: This is currently unused, perhaps convert to 'scale' with a replicas param?
  187. def stop(self):
  188. if not self.force and not self.exists():
  189. return []
  190. cmd = ['stop']
  191. if self.filename:
  192. cmd.append('--filename=' + ','.join(self.filename))
  193. else:
  194. if not self.resource:
  195. self.module.fail_json(msg='resource required to stop without filename')
  196. cmd.append(self.resource)
  197. if self.name:
  198. cmd.append(self.name)
  199. if self.label:
  200. cmd.append('--selector=' + self.label)
  201. if self.all:
  202. cmd.append('--all')
  203. if self.force:
  204. cmd.append('--ignore-not-found')
  205. return self._execute(cmd)
  206. def main():
  207. module = AnsibleModule(
  208. argument_spec=dict(
  209. name=dict(),
  210. filename=dict(type='list', aliases=['files', 'file', 'filenames']),
  211. namespace=dict(),
  212. resource=dict(),
  213. label=dict(),
  214. server=dict(),
  215. kubectl=dict(),
  216. force=dict(default=False, type='bool'),
  217. all=dict(default=False, type='bool'),
  218. log_level=dict(default=0, type='int'),
  219. state=dict(default='present', choices=['present', 'absent', 'latest', 'reloaded', 'stopped']),
  220. ),
  221. mutually_exclusive=[['filename', 'list']]
  222. )
  223. changed = False
  224. manager = KubeManager(module)
  225. state = module.params.get('state')
  226. if state == 'present':
  227. result = manager.create(check=False)
  228. elif state == 'absent':
  229. result = manager.delete()
  230. elif state == 'reloaded':
  231. result = manager.replace()
  232. elif state == 'stopped':
  233. result = manager.stop()
  234. elif state == 'latest':
  235. result = manager.replace()
  236. else:
  237. module.fail_json(msg='Unrecognized state %s.' % state)
  238. module.exit_json(changed=changed,
  239. msg='success: %s' % (' '.join(result))
  240. )
  241. from ansible.module_utils.basic import * # noqa
  242. if __name__ == '__main__':
  243. main()