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.

339 lines
9.4 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. recursive:
  74. required: false
  75. default: false
  76. description:
  77. - Process the directory used in -f, --filename recursively.
  78. Useful when you want to manage related manifests organized
  79. within the same directory.
  80. requirements:
  81. - kubectl
  82. author: "Kenny Jones (@kenjones-cisco)"
  83. """
  84. EXAMPLES = """
  85. - name: test nginx is present
  86. kube: name=nginx resource=rc state=present
  87. - name: test nginx is stopped
  88. kube: name=nginx resource=rc state=stopped
  89. - name: test nginx is absent
  90. kube: name=nginx resource=rc state=absent
  91. - name: test nginx is present
  92. kube: filename=/tmp/nginx.yml
  93. - name: test nginx and postgresql are present
  94. kube: files=/tmp/nginx.yml,/tmp/postgresql.yml
  95. - name: test nginx and postgresql are present
  96. kube:
  97. files:
  98. - /tmp/nginx.yml
  99. - /tmp/postgresql.yml
  100. """
  101. class KubeManager(object):
  102. def __init__(self, module):
  103. self.module = module
  104. self.kubectl = module.params.get('kubectl')
  105. if self.kubectl is None:
  106. self.kubectl = module.get_bin_path('kubectl', True)
  107. self.base_cmd = [self.kubectl]
  108. if module.params.get('server'):
  109. self.base_cmd.append('--server=' + module.params.get('server'))
  110. if module.params.get('log_level'):
  111. self.base_cmd.append('--v=' + str(module.params.get('log_level')))
  112. if module.params.get('namespace'):
  113. self.base_cmd.append('--namespace=' + module.params.get('namespace'))
  114. self.all = module.params.get('all')
  115. self.force = module.params.get('force')
  116. self.name = module.params.get('name')
  117. self.filename = [f.strip() for f in module.params.get('filename') or []]
  118. self.resource = module.params.get('resource')
  119. self.label = module.params.get('label')
  120. self.recursive = module.params.get('recursive')
  121. def _execute(self, cmd):
  122. args = self.base_cmd + cmd
  123. try:
  124. rc, out, err = self.module.run_command(args)
  125. if rc != 0:
  126. self.module.fail_json(
  127. msg='error running kubectl (%s) command (rc=%d), out=\'%s\', err=\'%s\'' % (' '.join(args), rc, out, err))
  128. except Exception as exc:
  129. self.module.fail_json(
  130. msg='error running kubectl (%s) command: %s' % (' '.join(args), str(exc)))
  131. return out.splitlines()
  132. def _execute_nofail(self, cmd):
  133. args = self.base_cmd + cmd
  134. rc, out, err = self.module.run_command(args)
  135. if rc != 0:
  136. return None
  137. return out.splitlines()
  138. def create(self, check=True, force=True):
  139. if check and self.exists():
  140. return []
  141. cmd = ['apply']
  142. if force:
  143. cmd.append('--force')
  144. if self.recursive:
  145. cmd.append('--recursive={}'.format(self.recursive))
  146. if not self.filename:
  147. self.module.fail_json(msg='filename required to create')
  148. cmd.append('--filename=' + ','.join(self.filename))
  149. return self._execute(cmd)
  150. def replace(self, force=True):
  151. cmd = ['apply']
  152. if force:
  153. cmd.append('--force')
  154. if self.recursive:
  155. cmd.append('--recursive={}'.format(self.recursive))
  156. if not self.filename:
  157. self.module.fail_json(msg='filename required to reload')
  158. cmd.append('--filename=' + ','.join(self.filename))
  159. return self._execute(cmd)
  160. def delete(self):
  161. if not self.force and not self.exists():
  162. return []
  163. cmd = ['delete']
  164. if self.filename:
  165. cmd.append('--filename=' + ','.join(self.filename))
  166. if self.recursive:
  167. cmd.append('--recursive={}'.format(self.recursive))
  168. else:
  169. if not self.resource:
  170. self.module.fail_json(msg='resource required to delete without filename')
  171. cmd.append(self.resource)
  172. if self.name:
  173. cmd.append(self.name)
  174. if self.label:
  175. cmd.append('--selector=' + self.label)
  176. if self.all:
  177. cmd.append('--all')
  178. if self.force:
  179. cmd.append('--ignore-not-found')
  180. if self.recursive:
  181. cmd.append('--recursive={}'.format(self.recursive))
  182. return self._execute(cmd)
  183. def exists(self):
  184. cmd = ['get']
  185. if self.filename:
  186. cmd.append('--filename=' + ','.join(self.filename))
  187. if self.recursive:
  188. cmd.append('--recursive={}'.format(self.recursive))
  189. else:
  190. if not self.resource:
  191. self.module.fail_json(msg='resource required without filename')
  192. cmd.append(self.resource)
  193. if self.name:
  194. cmd.append(self.name)
  195. if self.label:
  196. cmd.append('--selector=' + self.label)
  197. if self.all:
  198. cmd.append('--all-namespaces')
  199. cmd.append('--no-headers')
  200. result = self._execute_nofail(cmd)
  201. if not result:
  202. return False
  203. return True
  204. # TODO: This is currently unused, perhaps convert to 'scale' with a replicas param?
  205. def stop(self):
  206. if not self.force and not self.exists():
  207. return []
  208. cmd = ['stop']
  209. if self.filename:
  210. cmd.append('--filename=' + ','.join(self.filename))
  211. if self.recursive:
  212. cmd.append('--recursive={}'.format(self.recursive))
  213. else:
  214. if not self.resource:
  215. self.module.fail_json(msg='resource required to stop without filename')
  216. cmd.append(self.resource)
  217. if self.name:
  218. cmd.append(self.name)
  219. if self.label:
  220. cmd.append('--selector=' + self.label)
  221. if self.all:
  222. cmd.append('--all')
  223. if self.force:
  224. cmd.append('--ignore-not-found')
  225. return self._execute(cmd)
  226. def main():
  227. module = AnsibleModule(
  228. argument_spec=dict(
  229. name=dict(),
  230. filename=dict(type='list', aliases=['files', 'file', 'filenames']),
  231. namespace=dict(),
  232. resource=dict(),
  233. label=dict(),
  234. server=dict(),
  235. kubectl=dict(),
  236. force=dict(default=False, type='bool'),
  237. all=dict(default=False, type='bool'),
  238. log_level=dict(default=0, type='int'),
  239. state=dict(default='present', choices=['present', 'absent', 'latest', 'reloaded', 'stopped']),
  240. recursive=dict(default=False, type='bool'),
  241. ),
  242. mutually_exclusive=[['filename', 'list']]
  243. )
  244. changed = False
  245. manager = KubeManager(module)
  246. state = module.params.get('state')
  247. if state == 'present':
  248. result = manager.create(check=False)
  249. elif state == 'absent':
  250. result = manager.delete()
  251. elif state == 'reloaded':
  252. result = manager.replace()
  253. elif state == 'stopped':
  254. result = manager.stop()
  255. elif state == 'latest':
  256. result = manager.replace()
  257. else:
  258. module.fail_json(msg='Unrecognized state %s.' % state)
  259. module.exit_json(changed=changed,
  260. msg='success: %s' % (' '.join(result))
  261. )
  262. from ansible.module_utils.basic import * # noqa
  263. if __name__ == '__main__':
  264. main()