oc_obj.py 53 KB

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