oc_obj.py 52 KB

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