oc_obj.py 50 KB

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