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.

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