oc_obj.py 51 KB

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