oc_route.py 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535
  1. #!/usr/bin/env python
  2. # pylint: disable=missing-docstring
  3. # flake8: noqa: T001
  4. # ___ ___ _ _ ___ ___ _ _____ ___ ___
  5. # / __| __| \| | __| _ \ /_\_ _| __| \
  6. # | (_ | _|| .` | _|| / / _ \| | | _|| |) |
  7. # \___|___|_|\_|___|_|_\/_/_\_\_|_|___|___/_ _____
  8. # | \ / _ \ | \| |/ _ \_ _| | __| \_ _|_ _|
  9. # | |) | (_) | | .` | (_) || | | _|| |) | | | |
  10. # |___/ \___/ |_|\_|\___/ |_| |___|___/___| |_|
  11. #
  12. # Copyright 2016 Red Hat, Inc. and/or its affiliates
  13. # and other contributors as indicated by the @author tags.
  14. #
  15. # Licensed under the Apache License, Version 2.0 (the "License");
  16. # you may not use this file except in compliance with the License.
  17. # You may obtain a copy of the License at
  18. #
  19. # http://www.apache.org/licenses/LICENSE-2.0
  20. #
  21. # Unless required by applicable law or agreed to in writing, software
  22. # distributed under the License is distributed on an "AS IS" BASIS,
  23. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  24. # See the License for the specific language governing permissions and
  25. # limitations under the License.
  26. #
  27. '''
  28. OpenShiftCLI class that wraps the oc commands in a subprocess
  29. '''
  30. # pylint: disable=too-many-lines
  31. from __future__ import print_function
  32. import atexit
  33. import json
  34. import os
  35. import re
  36. import shutil
  37. import subprocess
  38. # pylint: disable=import-error
  39. import ruamel.yaml as yaml
  40. from ansible.module_utils.basic import AnsibleModule
  41. DOCUMENTATION = '''
  42. ---
  43. module: oc_route
  44. short_description: Create, modify, and idempotently manage openshift routes.
  45. description:
  46. - Manage openshift route objects programmatically.
  47. options:
  48. state:
  49. description:
  50. - State represents whether to create, modify, delete, or list
  51. required: true
  52. default: present
  53. choices: ["present", "absent", "list"]
  54. aliases: []
  55. kubeconfig:
  56. description:
  57. - The path for the kubeconfig file to use for authentication
  58. required: false
  59. default: /etc/origin/master/admin.kubeconfig
  60. aliases: []
  61. debug:
  62. description:
  63. - Turn on debug output.
  64. required: false
  65. default: False
  66. aliases: []
  67. name:
  68. description:
  69. - Name of the object that is being queried.
  70. required: false
  71. default: None
  72. aliases: []
  73. namespace:
  74. description:
  75. - The namespace where the object lives.
  76. required: false
  77. default: str
  78. aliases: []
  79. tls_termination:
  80. description:
  81. - The options for termination. e.g. reencrypt
  82. required: false
  83. default: None
  84. aliases: []
  85. dest_cacert_path:
  86. description:
  87. - The path to the dest_cacert
  88. required: false
  89. default: None
  90. aliases: []
  91. cacert_path:
  92. description:
  93. - The path to the cacert
  94. required: false
  95. default: None
  96. aliases: []
  97. cert_path:
  98. description:
  99. - The path to the cert
  100. required: false
  101. default: None
  102. aliases: []
  103. key_path:
  104. description:
  105. - The path to the key
  106. required: false
  107. default: None
  108. aliases: []
  109. dest_cacert_content:
  110. description:
  111. - The dest_cacert content
  112. required: false
  113. default: None
  114. aliases: []
  115. cacert_content:
  116. description:
  117. - The cacert content
  118. required: false
  119. default: None
  120. aliases: []
  121. cert_content:
  122. description:
  123. - The cert content
  124. required: false
  125. default: None
  126. aliases: []
  127. service_name:
  128. description:
  129. - The name of the service that this route points to.
  130. required: false
  131. default: None
  132. aliases: []
  133. host:
  134. description:
  135. - The host that the route will use. e.g. myapp.x.y.z
  136. required: false
  137. default: None
  138. aliases: []
  139. author:
  140. - "Kenny Woodson <kwoodson@redhat.com>"
  141. extends_documentation_fragment: []
  142. '''
  143. EXAMPLES = '''
  144. - name: Configure certificates for reencrypt route
  145. oc_route:
  146. name: myapproute
  147. namespace: awesomeapp
  148. cert_path: "/etc/origin/master/named_certificates/myapp_cert
  149. key_path: "/etc/origin/master/named_certificates/myapp_key
  150. cacert_path: "/etc/origin/master/named_certificates/myapp_cacert
  151. dest_cacert_content: "{{ dest_cacert_content }}"
  152. service_name: myapp_php
  153. host: myapp.awesomeapp.openshift.com
  154. tls_termination: reencrypt
  155. run_once: true
  156. '''
  157. # noqa: E301,E302
  158. class YeditException(Exception):
  159. ''' Exception class for Yedit '''
  160. pass
  161. # pylint: disable=too-many-public-methods
  162. class Yedit(object):
  163. ''' Class to modify yaml files '''
  164. re_valid_key = r"(((\[-?\d+\])|([0-9a-zA-Z%s/_-]+)).?)+$"
  165. re_key = r"(?:\[(-?\d+)\])|([0-9a-zA-Z%s/_-]+)"
  166. com_sep = set(['.', '#', '|', ':'])
  167. # pylint: disable=too-many-arguments
  168. def __init__(self,
  169. filename=None,
  170. content=None,
  171. content_type='yaml',
  172. separator='.',
  173. backup=False):
  174. self.content = content
  175. self._separator = separator
  176. self.filename = filename
  177. self.__yaml_dict = content
  178. self.content_type = content_type
  179. self.backup = backup
  180. self.load(content_type=self.content_type)
  181. if self.__yaml_dict is None:
  182. self.__yaml_dict = {}
  183. @property
  184. def separator(self):
  185. ''' getter method for yaml_dict '''
  186. return self._separator
  187. @separator.setter
  188. def separator(self):
  189. ''' getter method for yaml_dict '''
  190. return self._separator
  191. @property
  192. def yaml_dict(self):
  193. ''' getter method for yaml_dict '''
  194. return self.__yaml_dict
  195. @yaml_dict.setter
  196. def yaml_dict(self, value):
  197. ''' setter method for yaml_dict '''
  198. self.__yaml_dict = value
  199. @staticmethod
  200. def parse_key(key, sep='.'):
  201. '''parse the key allowing the appropriate separator'''
  202. common_separators = list(Yedit.com_sep - set([sep]))
  203. return re.findall(Yedit.re_key % ''.join(common_separators), key)
  204. @staticmethod
  205. def valid_key(key, sep='.'):
  206. '''validate the incoming key'''
  207. common_separators = list(Yedit.com_sep - set([sep]))
  208. if not re.match(Yedit.re_valid_key % ''.join(common_separators), key):
  209. return False
  210. return True
  211. @staticmethod
  212. def remove_entry(data, key, sep='.'):
  213. ''' remove data at location key '''
  214. if key == '' and isinstance(data, dict):
  215. data.clear()
  216. return True
  217. elif key == '' and isinstance(data, list):
  218. del data[:]
  219. return True
  220. if not (key and Yedit.valid_key(key, sep)) and \
  221. isinstance(data, (list, dict)):
  222. return None
  223. key_indexes = Yedit.parse_key(key, sep)
  224. for arr_ind, dict_key in key_indexes[:-1]:
  225. if dict_key and isinstance(data, dict):
  226. data = data.get(dict_key, None)
  227. elif (arr_ind and isinstance(data, list) and
  228. int(arr_ind) <= len(data) - 1):
  229. data = data[int(arr_ind)]
  230. else:
  231. return None
  232. # process last index for remove
  233. # expected list entry
  234. if key_indexes[-1][0]:
  235. if isinstance(data, list) and int(key_indexes[-1][0]) <= len(data) - 1: # noqa: E501
  236. del data[int(key_indexes[-1][0])]
  237. return True
  238. # expected dict entry
  239. elif key_indexes[-1][1]:
  240. if isinstance(data, dict):
  241. del data[key_indexes[-1][1]]
  242. return True
  243. @staticmethod
  244. def add_entry(data, key, item=None, sep='.'):
  245. ''' Get an item from a dictionary with key notation a.b.c
  246. d = {'a': {'b': 'c'}}}
  247. key = a#b
  248. return c
  249. '''
  250. if key == '':
  251. pass
  252. elif (not (key and Yedit.valid_key(key, sep)) and
  253. isinstance(data, (list, dict))):
  254. return None
  255. key_indexes = Yedit.parse_key(key, sep)
  256. for arr_ind, dict_key in key_indexes[:-1]:
  257. if dict_key:
  258. if isinstance(data, dict) and dict_key in data and data[dict_key]: # noqa: E501
  259. data = data[dict_key]
  260. continue
  261. elif data and not isinstance(data, dict):
  262. return None
  263. data[dict_key] = {}
  264. data = data[dict_key]
  265. elif (arr_ind and isinstance(data, list) and
  266. int(arr_ind) <= len(data) - 1):
  267. data = data[int(arr_ind)]
  268. else:
  269. return None
  270. if key == '':
  271. data = item
  272. # process last index for add
  273. # expected list entry
  274. elif key_indexes[-1][0] and isinstance(data, list) and int(key_indexes[-1][0]) <= len(data) - 1: # noqa: E501
  275. data[int(key_indexes[-1][0])] = item
  276. # expected dict entry
  277. elif key_indexes[-1][1] and isinstance(data, dict):
  278. data[key_indexes[-1][1]] = item
  279. return data
  280. @staticmethod
  281. def get_entry(data, key, sep='.'):
  282. ''' Get an item from a dictionary with key notation a.b.c
  283. d = {'a': {'b': 'c'}}}
  284. key = a.b
  285. return c
  286. '''
  287. if key == '':
  288. pass
  289. elif (not (key and Yedit.valid_key(key, sep)) and
  290. isinstance(data, (list, dict))):
  291. return None
  292. key_indexes = Yedit.parse_key(key, sep)
  293. for arr_ind, dict_key in key_indexes:
  294. if dict_key and isinstance(data, dict):
  295. data = data.get(dict_key, None)
  296. elif (arr_ind and isinstance(data, list) and
  297. int(arr_ind) <= len(data) - 1):
  298. data = data[int(arr_ind)]
  299. else:
  300. return None
  301. return data
  302. def write(self):
  303. ''' write to file '''
  304. if not self.filename:
  305. raise YeditException('Please specify a filename.')
  306. if self.backup and self.file_exists():
  307. shutil.copy(self.filename, self.filename + '.orig')
  308. tmp_filename = self.filename + '.yedit'
  309. with open(tmp_filename, 'w') as yfd:
  310. # pylint: disable=no-member
  311. if hasattr(self.yaml_dict, 'fa'):
  312. self.yaml_dict.fa.set_block_style()
  313. yfd.write(yaml.dump(self.yaml_dict, Dumper=yaml.RoundTripDumper))
  314. os.rename(tmp_filename, self.filename)
  315. return (True, self.yaml_dict)
  316. def read(self):
  317. ''' read from file '''
  318. # check if it exists
  319. if self.filename is None or not self.file_exists():
  320. return None
  321. contents = None
  322. with open(self.filename) as yfd:
  323. contents = yfd.read()
  324. return contents
  325. def file_exists(self):
  326. ''' return whether file exists '''
  327. if os.path.exists(self.filename):
  328. return True
  329. return False
  330. def load(self, content_type='yaml'):
  331. ''' return yaml file '''
  332. contents = self.read()
  333. if not contents and not self.content:
  334. return None
  335. if self.content:
  336. if isinstance(self.content, dict):
  337. self.yaml_dict = self.content
  338. return self.yaml_dict
  339. elif isinstance(self.content, str):
  340. contents = self.content
  341. # check if it is yaml
  342. try:
  343. if content_type == 'yaml' and contents:
  344. self.yaml_dict = yaml.load(contents, yaml.RoundTripLoader)
  345. # pylint: disable=no-member
  346. if hasattr(self.yaml_dict, 'fa'):
  347. self.yaml_dict.fa.set_block_style()
  348. elif content_type == 'json' and contents:
  349. self.yaml_dict = json.loads(contents)
  350. except yaml.YAMLError as err:
  351. # Error loading yaml or json
  352. raise YeditException('Problem with loading yaml file. %s' % err)
  353. return self.yaml_dict
  354. def get(self, key):
  355. ''' get a specified key'''
  356. try:
  357. entry = Yedit.get_entry(self.yaml_dict, key, self.separator)
  358. except KeyError:
  359. entry = None
  360. return entry
  361. def pop(self, path, key_or_item):
  362. ''' remove a key, value pair from a dict or an item for a list'''
  363. try:
  364. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  365. except KeyError:
  366. entry = None
  367. if entry is None:
  368. return (False, self.yaml_dict)
  369. if isinstance(entry, dict):
  370. # pylint: disable=no-member,maybe-no-member
  371. if key_or_item in entry:
  372. entry.pop(key_or_item)
  373. return (True, self.yaml_dict)
  374. return (False, self.yaml_dict)
  375. elif isinstance(entry, list):
  376. # pylint: disable=no-member,maybe-no-member
  377. ind = None
  378. try:
  379. ind = entry.index(key_or_item)
  380. except ValueError:
  381. return (False, self.yaml_dict)
  382. entry.pop(ind)
  383. return (True, self.yaml_dict)
  384. return (False, self.yaml_dict)
  385. def delete(self, path):
  386. ''' remove path from a dict'''
  387. try:
  388. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  389. except KeyError:
  390. entry = None
  391. if entry is None:
  392. return (False, self.yaml_dict)
  393. result = Yedit.remove_entry(self.yaml_dict, path, self.separator)
  394. if not result:
  395. return (False, self.yaml_dict)
  396. return (True, self.yaml_dict)
  397. def exists(self, path, value):
  398. ''' check if value exists at path'''
  399. try:
  400. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  401. except KeyError:
  402. entry = None
  403. if isinstance(entry, list):
  404. if value in entry:
  405. return True
  406. return False
  407. elif isinstance(entry, dict):
  408. if isinstance(value, dict):
  409. rval = False
  410. for key, val in value.items():
  411. if entry[key] != val:
  412. rval = False
  413. break
  414. else:
  415. rval = True
  416. return rval
  417. return value in entry
  418. return entry == value
  419. def append(self, path, value):
  420. '''append value to a list'''
  421. try:
  422. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  423. except KeyError:
  424. entry = None
  425. if entry is None:
  426. self.put(path, [])
  427. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  428. if not isinstance(entry, list):
  429. return (False, self.yaml_dict)
  430. # pylint: disable=no-member,maybe-no-member
  431. entry.append(value)
  432. return (True, self.yaml_dict)
  433. # pylint: disable=too-many-arguments
  434. def update(self, path, value, index=None, curr_value=None):
  435. ''' put path, value into a dict '''
  436. try:
  437. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  438. except KeyError:
  439. entry = None
  440. if isinstance(entry, dict):
  441. # pylint: disable=no-member,maybe-no-member
  442. if not isinstance(value, dict):
  443. raise YeditException('Cannot replace key, value entry in ' +
  444. 'dict with non-dict type. value=[%s] [%s]' % (value, type(value))) # noqa: E501
  445. entry.update(value)
  446. return (True, self.yaml_dict)
  447. elif isinstance(entry, list):
  448. # pylint: disable=no-member,maybe-no-member
  449. ind = None
  450. if curr_value:
  451. try:
  452. ind = entry.index(curr_value)
  453. except ValueError:
  454. return (False, self.yaml_dict)
  455. elif index is not None:
  456. ind = index
  457. if ind is not None and entry[ind] != value:
  458. entry[ind] = value
  459. return (True, self.yaml_dict)
  460. # see if it exists in the list
  461. try:
  462. ind = entry.index(value)
  463. except ValueError:
  464. # doesn't exist, append it
  465. entry.append(value)
  466. return (True, self.yaml_dict)
  467. # already exists, return
  468. if ind is not None:
  469. return (False, self.yaml_dict)
  470. return (False, self.yaml_dict)
  471. def put(self, path, value):
  472. ''' put path, value into a dict '''
  473. try:
  474. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  475. except KeyError:
  476. entry = None
  477. if entry == value:
  478. return (False, self.yaml_dict)
  479. # deepcopy didn't work
  480. tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict,
  481. default_flow_style=False),
  482. yaml.RoundTripLoader)
  483. # pylint: disable=no-member
  484. if hasattr(self.yaml_dict, 'fa'):
  485. tmp_copy.fa.set_block_style()
  486. result = Yedit.add_entry(tmp_copy, path, value, self.separator)
  487. if not result:
  488. return (False, self.yaml_dict)
  489. self.yaml_dict = tmp_copy
  490. return (True, self.yaml_dict)
  491. def create(self, path, value):
  492. ''' create a yaml file '''
  493. if not self.file_exists():
  494. # deepcopy didn't work
  495. tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict, default_flow_style=False), # noqa: E501
  496. yaml.RoundTripLoader)
  497. # pylint: disable=no-member
  498. if hasattr(self.yaml_dict, 'fa'):
  499. tmp_copy.fa.set_block_style()
  500. result = Yedit.add_entry(tmp_copy, path, value, self.separator)
  501. if result:
  502. self.yaml_dict = tmp_copy
  503. return (True, self.yaml_dict)
  504. return (False, self.yaml_dict)
  505. @staticmethod
  506. def get_curr_value(invalue, val_type):
  507. '''return the current value'''
  508. if invalue is None:
  509. return None
  510. curr_value = invalue
  511. if val_type == 'yaml':
  512. curr_value = yaml.load(invalue)
  513. elif val_type == 'json':
  514. curr_value = json.loads(invalue)
  515. return curr_value
  516. @staticmethod
  517. def parse_value(inc_value, vtype=''):
  518. '''determine value type passed'''
  519. true_bools = ['y', 'Y', 'yes', 'Yes', 'YES', 'true', 'True', 'TRUE',
  520. 'on', 'On', 'ON', ]
  521. false_bools = ['n', 'N', 'no', 'No', 'NO', 'false', 'False', 'FALSE',
  522. 'off', 'Off', 'OFF']
  523. # It came in as a string but you didn't specify value_type as string
  524. # we will convert to bool if it matches any of the above cases
  525. if isinstance(inc_value, str) and 'bool' in vtype:
  526. if inc_value not in true_bools and inc_value not in false_bools:
  527. raise YeditException('Not a boolean type. str=[%s] vtype=[%s]'
  528. % (inc_value, vtype))
  529. elif isinstance(inc_value, bool) and 'str' in vtype:
  530. inc_value = str(inc_value)
  531. # If vtype is not str then go ahead and attempt to yaml load it.
  532. if isinstance(inc_value, str) and 'str' not in vtype:
  533. try:
  534. inc_value = yaml.load(inc_value)
  535. except Exception:
  536. raise YeditException('Could not determine type of incoming ' +
  537. 'value. value=[%s] vtype=[%s]'
  538. % (type(inc_value), vtype))
  539. return inc_value
  540. # pylint: disable=too-many-return-statements,too-many-branches
  541. @staticmethod
  542. def run_ansible(module):
  543. '''perform the idempotent crud operations'''
  544. yamlfile = Yedit(filename=module.params['src'],
  545. backup=module.params['backup'],
  546. separator=module.params['separator'])
  547. if module.params['src']:
  548. rval = yamlfile.load()
  549. if yamlfile.yaml_dict is None and \
  550. module.params['state'] != 'present':
  551. return {'failed': True,
  552. 'msg': 'Error opening file [%s]. Verify that the ' +
  553. 'file exists, that it is has correct' +
  554. ' permissions, and is valid yaml.'}
  555. if module.params['state'] == 'list':
  556. if module.params['content']:
  557. content = Yedit.parse_value(module.params['content'],
  558. module.params['content_type'])
  559. yamlfile.yaml_dict = content
  560. if module.params['key']:
  561. rval = yamlfile.get(module.params['key']) or {}
  562. return {'changed': False, 'result': rval, 'state': "list"}
  563. elif module.params['state'] == 'absent':
  564. if module.params['content']:
  565. content = Yedit.parse_value(module.params['content'],
  566. module.params['content_type'])
  567. yamlfile.yaml_dict = content
  568. if module.params['update']:
  569. rval = yamlfile.pop(module.params['key'],
  570. module.params['value'])
  571. else:
  572. rval = yamlfile.delete(module.params['key'])
  573. if rval[0] and module.params['src']:
  574. yamlfile.write()
  575. return {'changed': rval[0], 'result': rval[1], 'state': "absent"}
  576. elif module.params['state'] == 'present':
  577. # check if content is different than what is in the file
  578. if module.params['content']:
  579. content = Yedit.parse_value(module.params['content'],
  580. module.params['content_type'])
  581. # We had no edits to make and the contents are the same
  582. if yamlfile.yaml_dict == content and \
  583. module.params['value'] is None:
  584. return {'changed': False,
  585. 'result': yamlfile.yaml_dict,
  586. 'state': "present"}
  587. yamlfile.yaml_dict = content
  588. # we were passed a value; parse it
  589. if module.params['value']:
  590. value = Yedit.parse_value(module.params['value'],
  591. module.params['value_type'])
  592. key = module.params['key']
  593. if module.params['update']:
  594. # pylint: disable=line-too-long
  595. curr_value = Yedit.get_curr_value(Yedit.parse_value(module.params['curr_value']), # noqa: E501
  596. module.params['curr_value_format']) # noqa: E501
  597. rval = yamlfile.update(key, value, module.params['index'], curr_value) # noqa: E501
  598. elif module.params['append']:
  599. rval = yamlfile.append(key, value)
  600. else:
  601. rval = yamlfile.put(key, value)
  602. if rval[0] and module.params['src']:
  603. yamlfile.write()
  604. return {'changed': rval[0],
  605. 'result': rval[1], 'state': "present"}
  606. # no edits to make
  607. if module.params['src']:
  608. # pylint: disable=redefined-variable-type
  609. rval = yamlfile.write()
  610. return {'changed': rval[0],
  611. 'result': rval[1],
  612. 'state': "present"}
  613. return {'failed': True, 'msg': 'Unkown state passed'}
  614. # pylint: disable=too-many-lines
  615. # noqa: E301,E302,E303,T001
  616. class OpenShiftCLIError(Exception):
  617. '''Exception class for openshiftcli'''
  618. pass
  619. # pylint: disable=too-few-public-methods
  620. class OpenShiftCLI(object):
  621. ''' Class to wrap the command line tools '''
  622. def __init__(self,
  623. namespace,
  624. kubeconfig='/etc/origin/master/admin.kubeconfig',
  625. verbose=False,
  626. all_namespaces=False):
  627. ''' Constructor for OpenshiftCLI '''
  628. self.namespace = namespace
  629. self.verbose = verbose
  630. self.kubeconfig = kubeconfig
  631. self.all_namespaces = all_namespaces
  632. # Pylint allows only 5 arguments to be passed.
  633. # pylint: disable=too-many-arguments
  634. def _replace_content(self, resource, rname, content, force=False, sep='.'):
  635. ''' replace the current object with the content '''
  636. res = self._get(resource, rname)
  637. if not res['results']:
  638. return res
  639. fname = '/tmp/%s' % rname
  640. yed = Yedit(fname, res['results'][0], separator=sep)
  641. changes = []
  642. for key, value in content.items():
  643. changes.append(yed.put(key, value))
  644. if any([change[0] for change in changes]):
  645. yed.write()
  646. atexit.register(Utils.cleanup, [fname])
  647. return self._replace(fname, force)
  648. return {'returncode': 0, 'updated': False}
  649. def _replace(self, fname, force=False):
  650. '''replace the current object with oc replace'''
  651. cmd = ['-n', self.namespace, 'replace', '-f', fname]
  652. if force:
  653. cmd.append('--force')
  654. return self.openshift_cmd(cmd)
  655. def _create_from_content(self, rname, content):
  656. '''create a temporary file and then call oc create on it'''
  657. fname = '/tmp/%s' % rname
  658. yed = Yedit(fname, content=content)
  659. yed.write()
  660. atexit.register(Utils.cleanup, [fname])
  661. return self._create(fname)
  662. def _create(self, fname):
  663. '''call oc create on a filename'''
  664. return self.openshift_cmd(['create', '-f', fname, '-n', self.namespace])
  665. def _delete(self, resource, rname, selector=None):
  666. '''call oc delete on a resource'''
  667. cmd = ['delete', resource, rname, '-n', self.namespace]
  668. if selector:
  669. cmd.append('--selector=%s' % selector)
  670. return self.openshift_cmd(cmd)
  671. def _process(self, template_name, create=False, params=None, template_data=None): # noqa: E501
  672. '''process a template
  673. template_name: the name of the template to process
  674. create: whether to send to oc create after processing
  675. params: the parameters for the template
  676. template_data: the incoming template's data; instead of a file
  677. '''
  678. cmd = ['process', '-n', self.namespace]
  679. if template_data:
  680. cmd.extend(['-f', '-'])
  681. else:
  682. cmd.append(template_name)
  683. if params:
  684. param_str = ["%s=%s" % (key, value) for key, value in params.items()]
  685. cmd.append('-v')
  686. cmd.extend(param_str)
  687. results = self.openshift_cmd(cmd, output=True, input_data=template_data)
  688. if results['returncode'] != 0 or not create:
  689. return results
  690. fname = '/tmp/%s' % template_name
  691. yed = Yedit(fname, results['results'])
  692. yed.write()
  693. atexit.register(Utils.cleanup, [fname])
  694. return self.openshift_cmd(['-n', self.namespace, 'create', '-f', fname])
  695. def _get(self, resource, rname=None, selector=None):
  696. '''return a resource by name '''
  697. cmd = ['get', resource]
  698. if selector:
  699. cmd.append('--selector=%s' % selector)
  700. if self.all_namespaces:
  701. cmd.extend(['--all-namespaces'])
  702. elif self.namespace:
  703. cmd.extend(['-n', self.namespace])
  704. cmd.extend(['-o', 'json'])
  705. if rname:
  706. cmd.append(rname)
  707. rval = self.openshift_cmd(cmd, output=True)
  708. # Ensure results are retuned in an array
  709. if 'items' in rval:
  710. rval['results'] = rval['items']
  711. elif not isinstance(rval['results'], list):
  712. rval['results'] = [rval['results']]
  713. return rval
  714. def _schedulable(self, node=None, selector=None, schedulable=True):
  715. ''' perform oadm manage-node scheduable '''
  716. cmd = ['manage-node']
  717. if node:
  718. cmd.extend(node)
  719. else:
  720. cmd.append('--selector=%s' % selector)
  721. cmd.append('--schedulable=%s' % schedulable)
  722. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw') # noqa: E501
  723. def _list_pods(self, node=None, selector=None, pod_selector=None):
  724. ''' perform oadm list pods
  725. node: the node in which to list pods
  726. selector: the label selector filter if provided
  727. pod_selector: the pod selector filter if provided
  728. '''
  729. cmd = ['manage-node']
  730. if node:
  731. cmd.extend(node)
  732. else:
  733. cmd.append('--selector=%s' % selector)
  734. if pod_selector:
  735. cmd.append('--pod-selector=%s' % pod_selector)
  736. cmd.extend(['--list-pods', '-o', 'json'])
  737. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  738. # pylint: disable=too-many-arguments
  739. def _evacuate(self, node=None, selector=None, pod_selector=None, dry_run=False, grace_period=None, force=False):
  740. ''' perform oadm manage-node evacuate '''
  741. cmd = ['manage-node']
  742. if node:
  743. cmd.extend(node)
  744. else:
  745. cmd.append('--selector=%s' % selector)
  746. if dry_run:
  747. cmd.append('--dry-run')
  748. if pod_selector:
  749. cmd.append('--pod-selector=%s' % pod_selector)
  750. if grace_period:
  751. cmd.append('--grace-period=%s' % int(grace_period))
  752. if force:
  753. cmd.append('--force')
  754. cmd.append('--evacuate')
  755. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  756. def _import_image(self, url=None, name=None, tag=None):
  757. ''' perform image import '''
  758. cmd = ['import-image']
  759. image = '{0}'.format(name)
  760. if tag:
  761. image += ':{0}'.format(tag)
  762. cmd.append(image)
  763. if url:
  764. cmd.append('--from={0}/{1}'.format(url, image))
  765. cmd.append('-n{0}'.format(self.namespace))
  766. cmd.append('--confirm')
  767. return self.openshift_cmd(cmd)
  768. # pylint: disable=too-many-arguments
  769. def openshift_cmd(self, cmd, oadm=False, output=False, output_type='json', input_data=None):
  770. '''Base command for oc '''
  771. cmds = []
  772. if oadm:
  773. cmds = ['/usr/bin/oadm']
  774. else:
  775. cmds = ['/usr/bin/oc']
  776. cmds.extend(cmd)
  777. rval = {}
  778. results = ''
  779. err = None
  780. if self.verbose:
  781. print(' '.join(cmds))
  782. proc = subprocess.Popen(cmds,
  783. stdin=subprocess.PIPE,
  784. stdout=subprocess.PIPE,
  785. stderr=subprocess.PIPE,
  786. env={'KUBECONFIG': self.kubeconfig})
  787. stdout, stderr = proc.communicate(input_data)
  788. rval = {"returncode": proc.returncode,
  789. "results": results,
  790. "cmd": ' '.join(cmds)}
  791. if proc.returncode == 0:
  792. if output:
  793. if output_type == 'json':
  794. try:
  795. rval['results'] = json.loads(stdout)
  796. except ValueError as err:
  797. if "No JSON object could be decoded" in err.args:
  798. err = err.args
  799. elif output_type == 'raw':
  800. rval['results'] = stdout
  801. if self.verbose:
  802. print("STDOUT: {0}".format(stdout))
  803. print("STDERR: {0}".format(stderr))
  804. if err:
  805. rval.update({"err": err,
  806. "stderr": stderr,
  807. "stdout": stdout,
  808. "cmd": cmds})
  809. else:
  810. rval.update({"stderr": stderr,
  811. "stdout": stdout,
  812. "results": {}})
  813. return rval
  814. class Utils(object):
  815. ''' utilities for openshiftcli modules '''
  816. @staticmethod
  817. def create_file(rname, data, ftype='yaml'):
  818. ''' create a file in tmp with name and contents'''
  819. path = os.path.join('/tmp', rname)
  820. with open(path, 'w') as fds:
  821. if ftype == 'yaml':
  822. fds.write(yaml.dump(data, Dumper=yaml.RoundTripDumper))
  823. elif ftype == 'json':
  824. fds.write(json.dumps(data))
  825. else:
  826. fds.write(data)
  827. # Register cleanup when module is done
  828. atexit.register(Utils.cleanup, [path])
  829. return path
  830. @staticmethod
  831. def create_files_from_contents(content, content_type=None):
  832. '''Turn an array of dict: filename, content into a files array'''
  833. if not isinstance(content, list):
  834. content = [content]
  835. files = []
  836. for item in content:
  837. path = Utils.create_file(item['path'], item['data'], ftype=content_type)
  838. files.append({'name': os.path.basename(path), 'path': path})
  839. return files
  840. @staticmethod
  841. def cleanup(files):
  842. '''Clean up on exit '''
  843. for sfile in files:
  844. if os.path.exists(sfile):
  845. if os.path.isdir(sfile):
  846. shutil.rmtree(sfile)
  847. elif os.path.isfile(sfile):
  848. os.remove(sfile)
  849. @staticmethod
  850. def exists(results, _name):
  851. ''' Check to see if the results include the name '''
  852. if not results:
  853. return False
  854. if Utils.find_result(results, _name):
  855. return True
  856. return False
  857. @staticmethod
  858. def find_result(results, _name):
  859. ''' Find the specified result by name'''
  860. rval = None
  861. for result in results:
  862. if 'metadata' in result and result['metadata']['name'] == _name:
  863. rval = result
  864. break
  865. return rval
  866. @staticmethod
  867. def get_resource_file(sfile, sfile_type='yaml'):
  868. ''' return the service file '''
  869. contents = None
  870. with open(sfile) as sfd:
  871. contents = sfd.read()
  872. if sfile_type == 'yaml':
  873. contents = yaml.load(contents, yaml.RoundTripLoader)
  874. elif sfile_type == 'json':
  875. contents = json.loads(contents)
  876. return contents
  877. # Disabling too-many-branches. This is a yaml dictionary comparison function
  878. # pylint: disable=too-many-branches,too-many-return-statements,too-many-statements
  879. @staticmethod
  880. def check_def_equal(user_def, result_def, skip_keys=None, debug=False):
  881. ''' Given a user defined definition, compare it with the results given back by our query. '''
  882. # Currently these values are autogenerated and we do not need to check them
  883. skip = ['metadata', 'status']
  884. if skip_keys:
  885. skip.extend(skip_keys)
  886. for key, value in result_def.items():
  887. if key in skip:
  888. continue
  889. # Both are lists
  890. if isinstance(value, list):
  891. if key not in user_def:
  892. if debug:
  893. print('User data does not have key [%s]' % key)
  894. print('User data: %s' % user_def)
  895. return False
  896. if not isinstance(user_def[key], list):
  897. if debug:
  898. print('user_def[key] is not a list key=[%s] user_def[key]=%s' % (key, user_def[key]))
  899. return False
  900. if len(user_def[key]) != len(value):
  901. if debug:
  902. print("List lengths are not equal.")
  903. print("key=[%s]: user_def[%s] != value[%s]" % (key, len(user_def[key]), len(value)))
  904. print("user_def: %s" % user_def[key])
  905. print("value: %s" % value)
  906. return False
  907. for values in zip(user_def[key], value):
  908. if isinstance(values[0], dict) and isinstance(values[1], dict):
  909. if debug:
  910. print('sending list - list')
  911. print(type(values[0]))
  912. print(type(values[1]))
  913. result = Utils.check_def_equal(values[0], values[1], skip_keys=skip_keys, debug=debug)
  914. if not result:
  915. print('list compare returned false')
  916. return False
  917. elif value != user_def[key]:
  918. if debug:
  919. print('value should be identical')
  920. print(value)
  921. print(user_def[key])
  922. return False
  923. # recurse on a dictionary
  924. elif isinstance(value, dict):
  925. if key not in user_def:
  926. if debug:
  927. print("user_def does not have key [%s]" % key)
  928. return False
  929. if not isinstance(user_def[key], dict):
  930. if debug:
  931. print("dict returned false: not instance of dict")
  932. return False
  933. # before passing ensure keys match
  934. api_values = set(value.keys()) - set(skip)
  935. user_values = set(user_def[key].keys()) - set(skip)
  936. if api_values != user_values:
  937. if debug:
  938. print("keys are not equal in dict")
  939. print(api_values)
  940. print(user_values)
  941. return False
  942. result = Utils.check_def_equal(user_def[key], value, skip_keys=skip_keys, debug=debug)
  943. if not result:
  944. if debug:
  945. print("dict returned false")
  946. print(result)
  947. return False
  948. # Verify each key, value pair is the same
  949. else:
  950. if key not in user_def or value != user_def[key]:
  951. if debug:
  952. print("value not equal; user_def does not have key")
  953. print(key)
  954. print(value)
  955. if key in user_def:
  956. print(user_def[key])
  957. return False
  958. if debug:
  959. print('returning true')
  960. return True
  961. class OpenShiftCLIConfig(object):
  962. '''Generic Config'''
  963. def __init__(self, rname, namespace, kubeconfig, options):
  964. self.kubeconfig = kubeconfig
  965. self.name = rname
  966. self.namespace = namespace
  967. self._options = options
  968. @property
  969. def config_options(self):
  970. ''' return config options '''
  971. return self._options
  972. def to_option_list(self):
  973. '''return all options as a string'''
  974. return self.stringify()
  975. def stringify(self):
  976. ''' return the options hash as cli params in a string '''
  977. rval = []
  978. for key, data in self.config_options.items():
  979. if data['include'] \
  980. and (data['value'] or isinstance(data['value'], int)):
  981. rval.append('--%s=%s' % (key.replace('_', '-'), data['value']))
  982. return rval
  983. # noqa: E302,E301
  984. # pylint: disable=too-many-instance-attributes
  985. class RouteConfig(object):
  986. ''' Handle route options '''
  987. # pylint: disable=too-many-arguments
  988. def __init__(self,
  989. sname,
  990. namespace,
  991. kubeconfig,
  992. destcacert=None,
  993. cacert=None,
  994. cert=None,
  995. key=None,
  996. host=None,
  997. tls_termination=None,
  998. service_name=None):
  999. ''' constructor for handling route options '''
  1000. self.kubeconfig = kubeconfig
  1001. self.name = sname
  1002. self.namespace = namespace
  1003. self.host = host
  1004. self.tls_termination = tls_termination
  1005. self.destcacert = destcacert
  1006. self.cacert = cacert
  1007. self.cert = cert
  1008. self.key = key
  1009. self.service_name = service_name
  1010. self.data = {}
  1011. self.create_dict()
  1012. def create_dict(self):
  1013. ''' return a service as a dict '''
  1014. self.data['apiVersion'] = 'v1'
  1015. self.data['kind'] = 'Route'
  1016. self.data['metadata'] = {}
  1017. self.data['metadata']['name'] = self.name
  1018. self.data['metadata']['namespace'] = self.namespace
  1019. self.data['spec'] = {}
  1020. self.data['spec']['host'] = self.host
  1021. if self.tls_termination:
  1022. self.data['spec']['tls'] = {}
  1023. if self.tls_termination == 'reencrypt':
  1024. self.data['spec']['tls']['destinationCACertificate'] = self.destcacert
  1025. self.data['spec']['tls']['key'] = self.key
  1026. self.data['spec']['tls']['caCertificate'] = self.cacert
  1027. self.data['spec']['tls']['certificate'] = self.cert
  1028. self.data['spec']['tls']['termination'] = self.tls_termination
  1029. self.data['spec']['to'] = {'kind': 'Service', 'name': self.service_name}
  1030. # pylint: disable=too-many-instance-attributes,too-many-public-methods
  1031. class Route(Yedit):
  1032. ''' Class to wrap the oc command line tools '''
  1033. host_path = "spec.host"
  1034. service_path = "spec.to.name"
  1035. cert_path = "spec.tls.certificate"
  1036. cacert_path = "spec.tls.caCertificate"
  1037. destcacert_path = "spec.tls.destinationCACertificate"
  1038. termination_path = "spec.tls.termination"
  1039. key_path = "spec.tls.key"
  1040. kind = 'route'
  1041. def __init__(self, content):
  1042. '''Route constructor'''
  1043. super(Route, self).__init__(content=content)
  1044. def get_destcacert(self):
  1045. ''' return cert '''
  1046. return self.get(Route.destcacert_path)
  1047. def get_cert(self):
  1048. ''' return cert '''
  1049. return self.get(Route.cert_path)
  1050. def get_key(self):
  1051. ''' return key '''
  1052. return self.get(Route.key_path)
  1053. def get_cacert(self):
  1054. ''' return cacert '''
  1055. return self.get(Route.cacert_path)
  1056. def get_service(self):
  1057. ''' return service name '''
  1058. return self.get(Route.service_path)
  1059. def get_termination(self):
  1060. ''' return tls termination'''
  1061. return self.get(Route.termination_path)
  1062. def get_host(self):
  1063. ''' return host '''
  1064. return self.get(Route.host_path)
  1065. # pylint: disable=too-many-instance-attributes
  1066. class OCRoute(OpenShiftCLI):
  1067. ''' Class to wrap the oc command line tools '''
  1068. kind = 'route'
  1069. def __init__(self,
  1070. config,
  1071. verbose=False):
  1072. ''' Constructor for OCVolume '''
  1073. super(OCRoute, self).__init__(config.namespace, config.kubeconfig)
  1074. self.config = config
  1075. self.namespace = config.namespace
  1076. self._route = None
  1077. @property
  1078. def route(self):
  1079. ''' property function for route'''
  1080. if not self._route:
  1081. self.get()
  1082. return self._route
  1083. @route.setter
  1084. def route(self, data):
  1085. ''' setter function for route '''
  1086. self._route = data
  1087. def exists(self):
  1088. ''' return whether a route exists '''
  1089. if self.route:
  1090. return True
  1091. return False
  1092. def get(self):
  1093. '''return route information '''
  1094. result = self._get(self.kind, self.config.name)
  1095. if result['returncode'] == 0:
  1096. self.route = Route(content=result['results'][0])
  1097. elif 'routes \"%s\" not found' % self.config.name in result['stderr']:
  1098. result['returncode'] = 0
  1099. result['results'] = [{}]
  1100. return result
  1101. def delete(self):
  1102. '''delete the object'''
  1103. return self._delete(self.kind, self.config.name)
  1104. def create(self):
  1105. '''create the object'''
  1106. return self._create_from_content(self.config.name, self.config.data)
  1107. def update(self):
  1108. '''update the object'''
  1109. # need to update the tls information and the service name
  1110. return self._replace_content(self.kind, self.config.name, self.config.data)
  1111. def needs_update(self):
  1112. ''' verify an update is needed '''
  1113. skip = []
  1114. return not Utils.check_def_equal(self.config.data, self.route.yaml_dict, skip_keys=skip, debug=True)
  1115. # pylint: disable=too-many-return-statements,too-many-branches
  1116. @staticmethod
  1117. def run_ansible(params, files, check_mode=False):
  1118. ''' run the idempotent asnible code
  1119. params comes from the ansible portion for this module
  1120. files: a dictionary for the certificates
  1121. {'cert': {'path': '',
  1122. 'content': '',
  1123. 'value': ''
  1124. }
  1125. }
  1126. check_mode: does the module support check mode. (module.check_mode)
  1127. '''
  1128. rconfig = RouteConfig(params['name'],
  1129. params['namespace'],
  1130. params['kubeconfig'],
  1131. files['destcacert']['value'],
  1132. files['cacert']['value'],
  1133. files['cert']['value'],
  1134. files['key']['value'],
  1135. params['host'],
  1136. params['tls_termination'],
  1137. params['service_name'])
  1138. oc_route = OCRoute(rconfig, verbose=params['debug'])
  1139. state = params['state']
  1140. api_rval = oc_route.get()
  1141. #####
  1142. # Get
  1143. #####
  1144. if state == 'list':
  1145. return {'changed': False,
  1146. 'results': api_rval['results'],
  1147. 'state': 'list'}
  1148. ########
  1149. # Delete
  1150. ########
  1151. if state == 'absent':
  1152. if oc_route.exists():
  1153. if check_mode:
  1154. return {'changed': False, 'msg': 'CHECK_MODE: Would have performed a delete.'} # noqa: E501
  1155. api_rval = oc_route.delete()
  1156. return {'changed': True, 'results': api_rval, 'state': "absent"} # noqa: E501
  1157. return {'changed': False, 'state': 'absent'}
  1158. if state == 'present':
  1159. ########
  1160. # Create
  1161. ########
  1162. if not oc_route.exists():
  1163. if check_mode:
  1164. return {'changed': True, 'msg': 'CHECK_MODE: Would have performed a create.'} # noqa: E501
  1165. # Create it here
  1166. api_rval = oc_route.create()
  1167. if api_rval['returncode'] != 0:
  1168. return {'failed': True, 'results': api_rval, 'state': "present"} # noqa: E501
  1169. # return the created object
  1170. api_rval = oc_route.get()
  1171. if api_rval['returncode'] != 0:
  1172. return {'failed': True, 'results': api_rval, 'state': "present"} # noqa: E501
  1173. return {'changed': True, 'results': api_rval, 'state': "present"} # noqa: E501
  1174. ########
  1175. # Update
  1176. ########
  1177. if oc_route.needs_update():
  1178. if check_mode:
  1179. return {'changed': True, 'msg': 'CHECK_MODE: Would have performed an update.'} # noqa: E501
  1180. api_rval = oc_route.update()
  1181. if api_rval['returncode'] != 0:
  1182. return {'failed': True, 'results': api_rval, 'state': "present"} # noqa: E501
  1183. # return the created object
  1184. api_rval = oc_route.get()
  1185. if api_rval['returncode'] != 0:
  1186. return {'failed': True, 'results': api_rval, 'state': "present"} # noqa: E501
  1187. return {'changed': True, 'results': api_rval, 'state': "present"} # noqa: E501
  1188. return {'changed': False, 'results': api_rval, 'state': "present"}
  1189. # catch all
  1190. return {'failed': True, 'msg': "Unknown State passed"}
  1191. def get_cert_data(path, content):
  1192. '''get the data for a particular value'''
  1193. if not path and not content:
  1194. return None
  1195. rval = None
  1196. if path and os.path.exists(path) and os.access(path, os.R_OK):
  1197. rval = open(path).read()
  1198. elif content:
  1199. rval = content
  1200. return rval
  1201. # pylint: disable=too-many-branches
  1202. def main():
  1203. '''
  1204. ansible oc module for route
  1205. '''
  1206. module = AnsibleModule(
  1207. argument_spec=dict(
  1208. kubeconfig=dict(default='/etc/origin/master/admin.kubeconfig', type='str'),
  1209. state=dict(default='present', type='str',
  1210. choices=['present', 'absent', 'list']),
  1211. debug=dict(default=False, type='bool'),
  1212. name=dict(default=None, required=True, type='str'),
  1213. namespace=dict(default=None, required=True, type='str'),
  1214. tls_termination=dict(default=None, type='str'),
  1215. dest_cacert_path=dict(default=None, type='str'),
  1216. cacert_path=dict(default=None, type='str'),
  1217. cert_path=dict(default=None, type='str'),
  1218. key_path=dict(default=None, type='str'),
  1219. dest_cacert_content=dict(default=None, type='str'),
  1220. cacert_content=dict(default=None, type='str'),
  1221. cert_content=dict(default=None, type='str'),
  1222. key_content=dict(default=None, type='str'),
  1223. service_name=dict(default=None, type='str'),
  1224. host=dict(default=None, type='str'),
  1225. ),
  1226. mutually_exclusive=[('dest_cacert_path', 'dest_cacert_content'),
  1227. ('cacert_path', 'cacert_content'),
  1228. ('cert_path', 'cert_content'),
  1229. ('key_path', 'key_content'), ],
  1230. supports_check_mode=True,
  1231. )
  1232. files = {'destcacert': {'path': module.params['dest_cacert_path'],
  1233. 'content': module.params['dest_cacert_content'],
  1234. 'value': None, },
  1235. 'cacert': {'path': module.params['cacert_path'],
  1236. 'content': module.params['cacert_content'],
  1237. 'value': None, },
  1238. 'cert': {'path': module.params['cert_path'],
  1239. 'content': module.params['cert_content'],
  1240. 'value': None, },
  1241. 'key': {'path': module.params['key_path'],
  1242. 'content': module.params['key_content'],
  1243. 'value': None, }, }
  1244. if module.params['tls_termination']:
  1245. for key, option in files.items():
  1246. if key == 'destcacert' and module.params['tls_termination'] != 'reencrypt':
  1247. continue
  1248. option['value'] = get_cert_data(option['path'], option['content'])
  1249. if not option['value']:
  1250. module.fail_json(msg='Verify that you pass a value for %s' % key)
  1251. results = OCRoute.run_ansible(module.params, files, module.check_mode)
  1252. if 'failed' in results:
  1253. module.fail_json(**results)
  1254. module.exit_json(**results)
  1255. if __name__ == '__main__':
  1256. main()