oc_edit.py 49 KB

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