oc_configmap.py 52 KB

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