oc_edit.py 49 KB

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