oc_edit.py 49 KB

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