PageRenderTime 54ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/ansible/modules/cloud/google/gcp_compute_http_health_check.py

https://bitbucket.org/bcoca/ansible
Python | 402 lines | 331 code | 45 blank | 26 comment | 25 complexity | 54ae0f911e179aa1c10d40dd2d81544c MD5 | raw file
Possible License(s): GPL-3.0
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. #
  4. # Copyright (C) 2017 Google
  5. # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
  6. # ----------------------------------------------------------------------------
  7. #
  8. # *** AUTO GENERATED CODE *** AUTO GENERATED CODE ***
  9. #
  10. # ----------------------------------------------------------------------------
  11. #
  12. # This file is automatically generated by Magic Modules and manual
  13. # changes will be clobbered when the file is regenerated.
  14. #
  15. # Please read more about how to change this file at
  16. # https://www.github.com/GoogleCloudPlatform/magic-modules
  17. #
  18. # ----------------------------------------------------------------------------
  19. from __future__ import absolute_import, division, print_function
  20. __metaclass__ = type
  21. ################################################################################
  22. # Documentation
  23. ################################################################################
  24. ANSIBLE_METADATA = {'metadata_version': '1.1',
  25. 'status': ["preview"],
  26. 'supported_by': 'community'}
  27. DOCUMENTATION = '''
  28. ---
  29. module: gcp_compute_http_health_check
  30. description:
  31. - An HttpHealthCheck resource. This resource defines a template for how
  32. individual VMs should be checked for health, via HTTP.
  33. short_description: Creates a GCP HttpHealthCheck
  34. version_added: 2.6
  35. author: Google Inc. (@googlecloudplatform)
  36. requirements:
  37. - python >= 2.6
  38. - requests >= 2.18.4
  39. - google-auth >= 1.3.0
  40. options:
  41. state:
  42. description:
  43. - Whether the given object should exist in GCP
  44. required: true
  45. choices: ['present', 'absent']
  46. default: 'present'
  47. check_interval_sec:
  48. description:
  49. - How often (in seconds) to send a health check. The default value
  50. is 5 seconds.
  51. required: false
  52. aliases: [check_interval_seconds]
  53. description:
  54. description:
  55. - An optional description of this resource. Provide this property
  56. when you create the resource.
  57. required: false
  58. healthy_threshold:
  59. description:
  60. - A so-far unhealthy instance will be marked healthy after this many
  61. consecutive successes. The default value is 2.
  62. required: false
  63. host:
  64. description:
  65. - The value of the host header in the HTTP health check request. If
  66. left empty (default value), the public IP on behalf of which this
  67. health check is performed will be used.
  68. required: false
  69. name:
  70. description:
  71. - Name of the resource. Provided by the client when the resource is
  72. created. The name must be 1-63 characters long, and comply with
  73. RFC1035. Specifically, the name must be 1-63 characters long and
  74. match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which
  75. means the first character must be a lowercase letter, and all
  76. following characters must be a dash, lowercase letter, or digit,
  77. except the last character, which cannot be a dash.
  78. required: true
  79. port:
  80. description:
  81. - The TCP port number for the HTTP health check request.
  82. - The default value is 80.
  83. required: false
  84. request_path:
  85. description:
  86. - The request path of the HTTP health check request.
  87. - The default value is /.
  88. required: false
  89. timeout_sec:
  90. description:
  91. - How long (in seconds) to wait before claiming failure.
  92. - The default value is 5 seconds. It is invalid for timeoutSec to
  93. have greater value than checkIntervalSec.
  94. required: false
  95. aliases: [timeout_seconds]
  96. unhealthy_threshold:
  97. description:
  98. - A so-far healthy instance will be marked unhealthy after this many
  99. consecutive failures. The default value is 2.
  100. required: false
  101. extends_documentation_fragment: gcp
  102. '''
  103. EXAMPLES = '''
  104. - name: create a http health check
  105. gcp_compute_http_health_check:
  106. name: testObject
  107. healthy_threshold: 10
  108. port: 8080
  109. timeout_sec: 2
  110. unhealthy_threshold: 5
  111. project: testProject
  112. auth_kind: service_account
  113. service_account_file: /tmp/auth.pem
  114. scopes:
  115. - https://www.googleapis.com/auth/compute
  116. state: present
  117. '''
  118. RETURN = '''
  119. check_interval_sec:
  120. description:
  121. - How often (in seconds) to send a health check. The default value
  122. is 5 seconds.
  123. returned: success
  124. type: int
  125. creation_timestamp:
  126. description:
  127. - Creation timestamp in RFC3339 text format.
  128. returned: success
  129. type: str
  130. description:
  131. description:
  132. - An optional description of this resource. Provide this property
  133. when you create the resource.
  134. returned: success
  135. type: str
  136. healthy_threshold:
  137. description:
  138. - A so-far unhealthy instance will be marked healthy after this many
  139. consecutive successes. The default value is 2.
  140. returned: success
  141. type: int
  142. host:
  143. description:
  144. - The value of the host header in the HTTP health check request. If
  145. left empty (default value), the public IP on behalf of which this
  146. health check is performed will be used.
  147. returned: success
  148. type: str
  149. id:
  150. description:
  151. - The unique identifier for the resource. This identifier is defined
  152. by the server.
  153. returned: success
  154. type: int
  155. name:
  156. description:
  157. - Name of the resource. Provided by the client when the resource is
  158. created. The name must be 1-63 characters long, and comply with
  159. RFC1035. Specifically, the name must be 1-63 characters long and
  160. match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which
  161. means the first character must be a lowercase letter, and all
  162. following characters must be a dash, lowercase letter, or digit,
  163. except the last character, which cannot be a dash.
  164. returned: success
  165. type: str
  166. port:
  167. description:
  168. - The TCP port number for the HTTP health check request.
  169. - The default value is 80.
  170. returned: success
  171. type: int
  172. request_path:
  173. description:
  174. - The request path of the HTTP health check request.
  175. - The default value is /.
  176. returned: success
  177. type: str
  178. timeout_sec:
  179. description:
  180. - How long (in seconds) to wait before claiming failure.
  181. - The default value is 5 seconds. It is invalid for timeoutSec to
  182. have greater value than checkIntervalSec.
  183. returned: success
  184. type: int
  185. unhealthy_threshold:
  186. description:
  187. - A so-far healthy instance will be marked unhealthy after this many
  188. consecutive failures. The default value is 2.
  189. returned: success
  190. type: int
  191. '''
  192. ################################################################################
  193. # Imports
  194. ################################################################################
  195. from ansible.module_utils.gcp_utils import navigate_hash, GcpSession, GcpModule, GcpRequest, replace_resource_dict
  196. import json
  197. import time
  198. ################################################################################
  199. # Main
  200. ################################################################################
  201. def main():
  202. """Main function"""
  203. module = GcpModule(
  204. argument_spec=dict(
  205. state=dict(default='present', choices=['present', 'absent'], type='str'),
  206. check_interval_sec=dict(type='int', aliases=['check_interval_seconds']),
  207. description=dict(type='str'),
  208. healthy_threshold=dict(type='int'),
  209. host=dict(type='str'),
  210. name=dict(required=True, type='str'),
  211. port=dict(type='int'),
  212. request_path=dict(type='str'),
  213. timeout_sec=dict(type='int', aliases=['timeout_seconds']),
  214. unhealthy_threshold=dict(type='int')
  215. )
  216. )
  217. state = module.params['state']
  218. kind = 'compute#httpHealthCheck'
  219. fetch = fetch_resource(module, self_link(module), kind)
  220. changed = False
  221. if fetch:
  222. if state == 'present':
  223. if is_different(module, fetch):
  224. fetch = update(module, self_link(module), kind, fetch)
  225. changed = True
  226. else:
  227. delete(module, self_link(module), kind, fetch)
  228. fetch = {}
  229. changed = True
  230. else:
  231. if state == 'present':
  232. fetch = create(module, collection(module), kind)
  233. changed = True
  234. else:
  235. fetch = {}
  236. fetch.update({'changed': changed})
  237. module.exit_json(**fetch)
  238. def create(module, link, kind):
  239. auth = GcpSession(module, 'compute')
  240. return wait_for_operation(module, auth.post(link, resource_to_request(module)))
  241. def update(module, link, kind, fetch):
  242. auth = GcpSession(module, 'compute')
  243. return wait_for_operation(module, auth.put(link, resource_to_request(module)))
  244. def delete(module, link, kind, fetch):
  245. auth = GcpSession(module, 'compute')
  246. return wait_for_operation(module, auth.delete(link))
  247. def resource_to_request(module):
  248. request = {
  249. u'kind': 'compute#httpHealthCheck',
  250. u'checkIntervalSec': module.params.get('check_interval_sec'),
  251. u'description': module.params.get('description'),
  252. u'healthyThreshold': module.params.get('healthy_threshold'),
  253. u'host': module.params.get('host'),
  254. u'name': module.params.get('name'),
  255. u'port': module.params.get('port'),
  256. u'requestPath': module.params.get('request_path'),
  257. u'timeoutSec': module.params.get('timeout_sec'),
  258. u'unhealthyThreshold': module.params.get('unhealthy_threshold')
  259. }
  260. return_vals = {}
  261. for k, v in request.items():
  262. if v:
  263. return_vals[k] = v
  264. return return_vals
  265. def fetch_resource(module, link, kind):
  266. auth = GcpSession(module, 'compute')
  267. return return_if_object(module, auth.get(link), kind)
  268. def self_link(module):
  269. return "https://www.googleapis.com/compute/v1/projects/{project}/global/httpHealthChecks/{name}".format(**module.params)
  270. def collection(module):
  271. return "https://www.googleapis.com/compute/v1/projects/{project}/global/httpHealthChecks".format(**module.params)
  272. def return_if_object(module, response, kind):
  273. # If not found, return nothing.
  274. if response.status_code == 404:
  275. return None
  276. # If no content, return nothing.
  277. if response.status_code == 204:
  278. return None
  279. try:
  280. module.raise_for_status(response)
  281. result = response.json()
  282. except getattr(json.decoder, 'JSONDecodeError', ValueError) as inst:
  283. module.fail_json(msg="Invalid JSON response with error: %s" % inst)
  284. if navigate_hash(result, ['error', 'errors']):
  285. module.fail_json(msg=navigate_hash(result, ['error', 'errors']))
  286. if result['kind'] != kind:
  287. module.fail_json(msg="Incorrect result: {kind}".format(**result))
  288. return result
  289. def is_different(module, response):
  290. request = resource_to_request(module)
  291. response = response_to_hash(module, response)
  292. # Remove all output-only from response.
  293. response_vals = {}
  294. for k, v in response.items():
  295. if k in request:
  296. response_vals[k] = v
  297. request_vals = {}
  298. for k, v in request.items():
  299. if k in response:
  300. request_vals[k] = v
  301. return GcpRequest(request_vals) != GcpRequest(response_vals)
  302. # Remove unnecessary properties from the response.
  303. # This is for doing comparisons with Ansible's current parameters.
  304. def response_to_hash(module, response):
  305. return {
  306. u'checkIntervalSec': response.get(u'checkIntervalSec'),
  307. u'creationTimestamp': response.get(u'creationTimestamp'),
  308. u'description': response.get(u'description'),
  309. u'healthyThreshold': response.get(u'healthyThreshold'),
  310. u'host': response.get(u'host'),
  311. u'id': response.get(u'id'),
  312. u'name': module.params.get('name'),
  313. u'port': response.get(u'port'),
  314. u'requestPath': response.get(u'requestPath'),
  315. u'timeoutSec': response.get(u'timeoutSec'),
  316. u'unhealthyThreshold': response.get(u'unhealthyThreshold')
  317. }
  318. def async_op_url(module, extra_data=None):
  319. if extra_data is None:
  320. extra_data = {}
  321. url = "https://www.googleapis.com/compute/v1/projects/{project}/global/operations/{op_id}"
  322. combined = extra_data.copy()
  323. combined.update(module.params)
  324. return url.format(**combined)
  325. def wait_for_operation(module, response):
  326. op_result = return_if_object(module, response, 'compute#operation')
  327. if op_result is None:
  328. return None
  329. status = navigate_hash(op_result, ['status'])
  330. wait_done = wait_for_completion(status, op_result, module)
  331. return fetch_resource(module, navigate_hash(wait_done, ['targetLink']), 'compute#httpHealthCheck')
  332. def wait_for_completion(status, op_result, module):
  333. op_id = navigate_hash(op_result, ['name'])
  334. op_uri = async_op_url(module, {'op_id': op_id})
  335. while status != 'DONE':
  336. raise_if_errors(op_result, ['error', 'errors'], 'message')
  337. time.sleep(1.0)
  338. if status not in ['PENDING', 'RUNNING', 'DONE']:
  339. module.fail_json(msg="Invalid result %s" % status)
  340. op_result = fetch_resource(module, op_uri, 'compute#operation')
  341. status = navigate_hash(op_result, ['status'])
  342. return op_result
  343. def raise_if_errors(response, err_path, module):
  344. errors = navigate_hash(response, err_path)
  345. if errors is not None:
  346. module.fail_json(msg=errors)
  347. if __name__ == '__main__':
  348. main()