oc_env.py 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847
  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/env -*- -*- -*-
  49. DOCUMENTATION = '''
  50. ---
  51. module: oc_env
  52. short_description: Modify, and idempotently manage openshift environment variables on pods, deploymentconfigs, and replication controllers.
  53. description:
  54. - Modify openshift environment variables 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 list of environment variables
  61. - absent - will remove the environment varibale from the object
  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: false
  82. default: None
  83. aliases: []
  84. namespace:
  85. description:
  86. - The namespace where the object lives.
  87. required: false
  88. default: str
  89. aliases: []
  90. kind:
  91. description:
  92. - The kind attribute of the object.
  93. required: False
  94. default: dc
  95. choices:
  96. - rc
  97. - dc
  98. - pods
  99. aliases: []
  100. env_vars:
  101. description:
  102. - The environment variables to insert. The format is a dict of value pairs.
  103. - e.g. {key1: value1, key2: value2})
  104. required: False
  105. default: None
  106. aliases: []
  107. author:
  108. - "Kenny Woodson <kwoodson@redhat.com>"
  109. extends_documentation_fragment: []
  110. '''
  111. EXAMPLES = '''
  112. - name: query a list of env vars on dc
  113. oc_env:
  114. kind: dc
  115. name: myawesomedc
  116. namespace: phpapp
  117. - name: Set the following variables.
  118. oc_env:
  119. kind: dc
  120. name: myawesomedc
  121. namespace: phpapp
  122. env_vars:
  123. SUPER_TURBO_MODE: 'true'
  124. ENABLE_PORTS: 'false'
  125. SERVICE_PORT: 9999
  126. '''
  127. # -*- -*- -*- End included fragment: doc/env -*- -*- -*-
  128. # -*- -*- -*- Begin included fragment: ../../lib_utils/src/class/yedit.py -*- -*- -*-
  129. # pylint: disable=undefined-variable,missing-docstring
  130. # noqa: E301,E302
  131. class YeditException(Exception):
  132. ''' Exception class for Yedit '''
  133. pass
  134. # pylint: disable=too-many-public-methods
  135. class Yedit(object):
  136. ''' Class to modify yaml files '''
  137. re_valid_key = r"(((\[-?\d+\])|([0-9a-zA-Z%s/_-]+)).?)+$"
  138. re_key = r"(?:\[(-?\d+)\])|([0-9a-zA-Z%s/_-]+)"
  139. com_sep = set(['.', '#', '|', ':'])
  140. # pylint: disable=too-many-arguments
  141. def __init__(self,
  142. filename=None,
  143. content=None,
  144. content_type='yaml',
  145. separator='.',
  146. backup=False):
  147. self.content = content
  148. self._separator = separator
  149. self.filename = filename
  150. self.__yaml_dict = content
  151. self.content_type = content_type
  152. self.backup = backup
  153. self.load(content_type=self.content_type)
  154. if self.__yaml_dict is None:
  155. self.__yaml_dict = {}
  156. @property
  157. def separator(self):
  158. ''' getter method for yaml_dict '''
  159. return self._separator
  160. @separator.setter
  161. def separator(self):
  162. ''' getter method for yaml_dict '''
  163. return self._separator
  164. @property
  165. def yaml_dict(self):
  166. ''' getter method for yaml_dict '''
  167. return self.__yaml_dict
  168. @yaml_dict.setter
  169. def yaml_dict(self, value):
  170. ''' setter method for yaml_dict '''
  171. self.__yaml_dict = value
  172. @staticmethod
  173. def parse_key(key, sep='.'):
  174. '''parse the key allowing the appropriate separator'''
  175. common_separators = list(Yedit.com_sep - set([sep]))
  176. return re.findall(Yedit.re_key % ''.join(common_separators), key)
  177. @staticmethod
  178. def valid_key(key, sep='.'):
  179. '''validate the incoming key'''
  180. common_separators = list(Yedit.com_sep - set([sep]))
  181. if not re.match(Yedit.re_valid_key % ''.join(common_separators), key):
  182. return False
  183. return True
  184. @staticmethod
  185. def remove_entry(data, key, sep='.'):
  186. ''' remove data at location key '''
  187. if key == '' and isinstance(data, dict):
  188. data.clear()
  189. return True
  190. elif key == '' and isinstance(data, list):
  191. del data[:]
  192. return True
  193. if not (key and Yedit.valid_key(key, sep)) and \
  194. isinstance(data, (list, dict)):
  195. return None
  196. key_indexes = Yedit.parse_key(key, sep)
  197. for arr_ind, dict_key in key_indexes[:-1]:
  198. if dict_key and isinstance(data, dict):
  199. data = data.get(dict_key, None)
  200. elif (arr_ind and isinstance(data, list) and
  201. int(arr_ind) <= len(data) - 1):
  202. data = data[int(arr_ind)]
  203. else:
  204. return None
  205. # process last index for remove
  206. # expected list entry
  207. if key_indexes[-1][0]:
  208. if isinstance(data, list) and int(key_indexes[-1][0]) <= len(data) - 1: # noqa: E501
  209. del data[int(key_indexes[-1][0])]
  210. return True
  211. # expected dict entry
  212. elif key_indexes[-1][1]:
  213. if isinstance(data, dict):
  214. del data[key_indexes[-1][1]]
  215. return True
  216. @staticmethod
  217. def add_entry(data, key, item=None, sep='.'):
  218. ''' Get an item from a dictionary with key notation a.b.c
  219. d = {'a': {'b': 'c'}}}
  220. key = a#b
  221. return c
  222. '''
  223. if key == '':
  224. pass
  225. elif (not (key and Yedit.valid_key(key, sep)) and
  226. isinstance(data, (list, dict))):
  227. return None
  228. key_indexes = Yedit.parse_key(key, sep)
  229. for arr_ind, dict_key in key_indexes[:-1]:
  230. if dict_key:
  231. if isinstance(data, dict) and dict_key in data and data[dict_key]: # noqa: E501
  232. data = data[dict_key]
  233. continue
  234. elif data and not isinstance(data, dict):
  235. return None
  236. data[dict_key] = {}
  237. data = data[dict_key]
  238. elif (arr_ind and isinstance(data, list) and
  239. int(arr_ind) <= len(data) - 1):
  240. data = data[int(arr_ind)]
  241. else:
  242. return None
  243. if key == '':
  244. data = item
  245. # process last index for add
  246. # expected list entry
  247. elif key_indexes[-1][0] and isinstance(data, list) and int(key_indexes[-1][0]) <= len(data) - 1: # noqa: E501
  248. data[int(key_indexes[-1][0])] = item
  249. # expected dict entry
  250. elif key_indexes[-1][1] and isinstance(data, dict):
  251. data[key_indexes[-1][1]] = item
  252. return data
  253. @staticmethod
  254. def get_entry(data, key, sep='.'):
  255. ''' Get an item from a dictionary with key notation a.b.c
  256. d = {'a': {'b': 'c'}}}
  257. key = a.b
  258. return c
  259. '''
  260. if key == '':
  261. pass
  262. elif (not (key and Yedit.valid_key(key, sep)) and
  263. isinstance(data, (list, dict))):
  264. return None
  265. key_indexes = Yedit.parse_key(key, sep)
  266. for arr_ind, dict_key in key_indexes:
  267. if dict_key and isinstance(data, dict):
  268. data = data.get(dict_key, None)
  269. elif (arr_ind and isinstance(data, list) and
  270. int(arr_ind) <= len(data) - 1):
  271. data = data[int(arr_ind)]
  272. else:
  273. return None
  274. return data
  275. @staticmethod
  276. def _write(filename, contents):
  277. ''' Actually write the file contents to disk. This helps with mocking. '''
  278. tmp_filename = filename + '.yedit'
  279. with open(tmp_filename, 'w') as yfd:
  280. yfd.write(contents)
  281. os.rename(tmp_filename, filename)
  282. def write(self):
  283. ''' write to file '''
  284. if not self.filename:
  285. raise YeditException('Please specify a filename.')
  286. if self.backup and self.file_exists():
  287. shutil.copy(self.filename, self.filename + '.orig')
  288. # Try to set format attributes if supported
  289. try:
  290. self.yaml_dict.fa.set_block_style()
  291. except AttributeError:
  292. pass
  293. # Try to use RoundTripDumper if supported.
  294. try:
  295. Yedit._write(self.filename, yaml.dump(self.yaml_dict, Dumper=yaml.RoundTripDumper))
  296. except AttributeError:
  297. Yedit._write(self.filename, yaml.safe_dump(self.yaml_dict, default_flow_style=False))
  298. return (True, self.yaml_dict)
  299. def read(self):
  300. ''' read from file '''
  301. # check if it exists
  302. if self.filename is None or not self.file_exists():
  303. return None
  304. contents = None
  305. with open(self.filename) as yfd:
  306. contents = yfd.read()
  307. return contents
  308. def file_exists(self):
  309. ''' return whether file exists '''
  310. if os.path.exists(self.filename):
  311. return True
  312. return False
  313. def load(self, content_type='yaml'):
  314. ''' return yaml file '''
  315. contents = self.read()
  316. if not contents and not self.content:
  317. return None
  318. if self.content:
  319. if isinstance(self.content, dict):
  320. self.yaml_dict = self.content
  321. return self.yaml_dict
  322. elif isinstance(self.content, str):
  323. contents = self.content
  324. # check if it is yaml
  325. try:
  326. if content_type == 'yaml' and contents:
  327. # Try to set format attributes if supported
  328. try:
  329. self.yaml_dict.fa.set_block_style()
  330. except AttributeError:
  331. pass
  332. # Try to use RoundTripLoader if supported.
  333. try:
  334. self.yaml_dict = yaml.safe_load(contents, yaml.RoundTripLoader)
  335. except AttributeError:
  336. self.yaml_dict = yaml.safe_load(contents)
  337. # Try to set format attributes if supported
  338. try:
  339. self.yaml_dict.fa.set_block_style()
  340. except AttributeError:
  341. pass
  342. elif content_type == 'json' and contents:
  343. self.yaml_dict = json.loads(contents)
  344. except yaml.YAMLError as err:
  345. # Error loading yaml or json
  346. raise YeditException('Problem with loading yaml file. %s' % err)
  347. return self.yaml_dict
  348. def get(self, key):
  349. ''' get a specified key'''
  350. try:
  351. entry = Yedit.get_entry(self.yaml_dict, key, self.separator)
  352. except KeyError:
  353. entry = None
  354. return entry
  355. def pop(self, path, key_or_item):
  356. ''' remove a key, value pair from a dict or an item for a list'''
  357. try:
  358. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  359. except KeyError:
  360. entry = None
  361. if entry is None:
  362. return (False, self.yaml_dict)
  363. if isinstance(entry, dict):
  364. # AUDIT:maybe-no-member makes sense due to fuzzy types
  365. # pylint: disable=maybe-no-member
  366. if key_or_item in entry:
  367. entry.pop(key_or_item)
  368. return (True, self.yaml_dict)
  369. return (False, self.yaml_dict)
  370. elif isinstance(entry, list):
  371. # AUDIT:maybe-no-member makes sense due to fuzzy types
  372. # pylint: disable=maybe-no-member
  373. ind = None
  374. try:
  375. ind = entry.index(key_or_item)
  376. except ValueError:
  377. return (False, self.yaml_dict)
  378. entry.pop(ind)
  379. return (True, self.yaml_dict)
  380. return (False, self.yaml_dict)
  381. def delete(self, path):
  382. ''' remove path from a dict'''
  383. try:
  384. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  385. except KeyError:
  386. entry = None
  387. if entry is None:
  388. return (False, self.yaml_dict)
  389. result = Yedit.remove_entry(self.yaml_dict, path, self.separator)
  390. if not result:
  391. return (False, self.yaml_dict)
  392. return (True, self.yaml_dict)
  393. def exists(self, path, value):
  394. ''' check if value exists at path'''
  395. try:
  396. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  397. except KeyError:
  398. entry = None
  399. if isinstance(entry, list):
  400. if value in entry:
  401. return True
  402. return False
  403. elif isinstance(entry, dict):
  404. if isinstance(value, dict):
  405. rval = False
  406. for key, val in value.items():
  407. if entry[key] != val:
  408. rval = False
  409. break
  410. else:
  411. rval = True
  412. return rval
  413. return value in entry
  414. return entry == value
  415. def append(self, path, value):
  416. '''append value to a list'''
  417. try:
  418. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  419. except KeyError:
  420. entry = None
  421. if entry is None:
  422. self.put(path, [])
  423. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  424. if not isinstance(entry, list):
  425. return (False, self.yaml_dict)
  426. # AUDIT:maybe-no-member makes sense due to loading data from
  427. # a serialized format.
  428. # pylint: disable=maybe-no-member
  429. entry.append(value)
  430. return (True, self.yaml_dict)
  431. # pylint: disable=too-many-arguments
  432. def update(self, path, value, index=None, curr_value=None):
  433. ''' put path, value into a dict '''
  434. try:
  435. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  436. except KeyError:
  437. entry = None
  438. if isinstance(entry, dict):
  439. # AUDIT:maybe-no-member makes sense due to fuzzy types
  440. # pylint: disable=maybe-no-member
  441. if not isinstance(value, dict):
  442. raise YeditException('Cannot replace key, value entry in ' +
  443. 'dict with non-dict type. value=[%s] [%s]' % (value, type(value))) # noqa: E501
  444. entry.update(value)
  445. return (True, self.yaml_dict)
  446. elif isinstance(entry, list):
  447. # AUDIT:maybe-no-member makes sense due to fuzzy types
  448. # pylint: disable=maybe-no-member
  449. ind = None
  450. if curr_value:
  451. try:
  452. ind = entry.index(curr_value)
  453. except ValueError:
  454. return (False, self.yaml_dict)
  455. elif index is not None:
  456. ind = index
  457. if ind is not None and entry[ind] != value:
  458. entry[ind] = value
  459. return (True, self.yaml_dict)
  460. # see if it exists in the list
  461. try:
  462. ind = entry.index(value)
  463. except ValueError:
  464. # doesn't exist, append it
  465. entry.append(value)
  466. return (True, self.yaml_dict)
  467. # already exists, return
  468. if ind is not None:
  469. return (False, self.yaml_dict)
  470. return (False, self.yaml_dict)
  471. def put(self, path, value):
  472. ''' put path, value into a dict '''
  473. try:
  474. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  475. except KeyError:
  476. entry = None
  477. if entry == value:
  478. return (False, self.yaml_dict)
  479. # deepcopy didn't work
  480. # Try to use ruamel.yaml and fallback to pyyaml
  481. try:
  482. tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict,
  483. default_flow_style=False),
  484. yaml.RoundTripLoader)
  485. except AttributeError:
  486. tmp_copy = copy.deepcopy(self.yaml_dict)
  487. # set the format attributes if available
  488. try:
  489. tmp_copy.fa.set_block_style()
  490. except AttributeError:
  491. pass
  492. result = Yedit.add_entry(tmp_copy, path, value, self.separator)
  493. if not result:
  494. return (False, self.yaml_dict)
  495. self.yaml_dict = tmp_copy
  496. return (True, self.yaml_dict)
  497. def create(self, path, value):
  498. ''' create a yaml file '''
  499. if not self.file_exists():
  500. # deepcopy didn't work
  501. # Try to use ruamel.yaml and fallback to pyyaml
  502. try:
  503. tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict,
  504. default_flow_style=False),
  505. yaml.RoundTripLoader)
  506. except AttributeError:
  507. tmp_copy = copy.deepcopy(self.yaml_dict)
  508. # set the format attributes if available
  509. try:
  510. tmp_copy.fa.set_block_style()
  511. except AttributeError:
  512. pass
  513. result = Yedit.add_entry(tmp_copy, path, value, self.separator)
  514. if result:
  515. self.yaml_dict = tmp_copy
  516. return (True, self.yaml_dict)
  517. return (False, self.yaml_dict)
  518. @staticmethod
  519. def get_curr_value(invalue, val_type):
  520. '''return the current value'''
  521. if invalue is None:
  522. return None
  523. curr_value = invalue
  524. if val_type == 'yaml':
  525. curr_value = yaml.load(invalue)
  526. elif val_type == 'json':
  527. curr_value = json.loads(invalue)
  528. return curr_value
  529. @staticmethod
  530. def parse_value(inc_value, vtype=''):
  531. '''determine value type passed'''
  532. true_bools = ['y', 'Y', 'yes', 'Yes', 'YES', 'true', 'True', 'TRUE',
  533. 'on', 'On', 'ON', ]
  534. false_bools = ['n', 'N', 'no', 'No', 'NO', 'false', 'False', 'FALSE',
  535. 'off', 'Off', 'OFF']
  536. # It came in as a string but you didn't specify value_type as string
  537. # we will convert to bool if it matches any of the above cases
  538. if isinstance(inc_value, str) and 'bool' in vtype:
  539. if inc_value not in true_bools and inc_value not in false_bools:
  540. raise YeditException('Not a boolean type. str=[%s] vtype=[%s]'
  541. % (inc_value, vtype))
  542. elif isinstance(inc_value, bool) and 'str' in vtype:
  543. inc_value = str(inc_value)
  544. # If vtype is not str then go ahead and attempt to yaml load it.
  545. if isinstance(inc_value, str) and 'str' not in vtype:
  546. try:
  547. inc_value = yaml.load(inc_value)
  548. except Exception:
  549. raise YeditException('Could not determine type of incoming ' +
  550. 'value. value=[%s] vtype=[%s]'
  551. % (type(inc_value), vtype))
  552. return inc_value
  553. # pylint: disable=too-many-return-statements,too-many-branches
  554. @staticmethod
  555. def run_ansible(module):
  556. '''perform the idempotent crud operations'''
  557. yamlfile = Yedit(filename=module.params['src'],
  558. backup=module.params['backup'],
  559. separator=module.params['separator'])
  560. if module.params['src']:
  561. rval = yamlfile.load()
  562. if yamlfile.yaml_dict is None and \
  563. module.params['state'] != 'present':
  564. return {'failed': True,
  565. 'msg': 'Error opening file [%s]. Verify that the ' +
  566. 'file exists, that it is has correct' +
  567. ' permissions, and is valid yaml.'}
  568. if module.params['state'] == 'list':
  569. if module.params['content']:
  570. content = Yedit.parse_value(module.params['content'],
  571. module.params['content_type'])
  572. yamlfile.yaml_dict = content
  573. if module.params['key']:
  574. rval = yamlfile.get(module.params['key']) or {}
  575. return {'changed': False, 'result': rval, 'state': "list"}
  576. elif module.params['state'] == 'absent':
  577. if module.params['content']:
  578. content = Yedit.parse_value(module.params['content'],
  579. module.params['content_type'])
  580. yamlfile.yaml_dict = content
  581. if module.params['update']:
  582. rval = yamlfile.pop(module.params['key'],
  583. module.params['value'])
  584. else:
  585. rval = yamlfile.delete(module.params['key'])
  586. if rval[0] and module.params['src']:
  587. yamlfile.write()
  588. return {'changed': rval[0], 'result': rval[1], 'state': "absent"}
  589. elif module.params['state'] == 'present':
  590. # check if content is different than what is in the file
  591. if module.params['content']:
  592. content = Yedit.parse_value(module.params['content'],
  593. module.params['content_type'])
  594. # We had no edits to make and the contents are the same
  595. if yamlfile.yaml_dict == content and \
  596. module.params['value'] is None:
  597. return {'changed': False,
  598. 'result': yamlfile.yaml_dict,
  599. 'state': "present"}
  600. yamlfile.yaml_dict = content
  601. # we were passed a value; parse it
  602. if module.params['value']:
  603. value = Yedit.parse_value(module.params['value'],
  604. module.params['value_type'])
  605. key = module.params['key']
  606. if module.params['update']:
  607. # pylint: disable=line-too-long
  608. curr_value = Yedit.get_curr_value(Yedit.parse_value(module.params['curr_value']), # noqa: E501
  609. module.params['curr_value_format']) # noqa: E501
  610. rval = yamlfile.update(key, value, module.params['index'], curr_value) # noqa: E501
  611. elif module.params['append']:
  612. rval = yamlfile.append(key, value)
  613. else:
  614. rval = yamlfile.put(key, value)
  615. if rval[0] and module.params['src']:
  616. yamlfile.write()
  617. return {'changed': rval[0],
  618. 'result': rval[1], 'state': "present"}
  619. # no edits to make
  620. if module.params['src']:
  621. # pylint: disable=redefined-variable-type
  622. rval = yamlfile.write()
  623. return {'changed': rval[0],
  624. 'result': rval[1],
  625. 'state': "present"}
  626. return {'failed': True, 'msg': 'Unkown state passed'}
  627. # -*- -*- -*- End included fragment: ../../lib_utils/src/class/yedit.py -*- -*- -*-
  628. # -*- -*- -*- Begin included fragment: lib/base.py -*- -*- -*-
  629. # pylint: disable=too-many-lines
  630. # noqa: E301,E302,E303,T001
  631. class OpenShiftCLIError(Exception):
  632. '''Exception class for openshiftcli'''
  633. pass
  634. # pylint: disable=too-few-public-methods
  635. class OpenShiftCLI(object):
  636. ''' Class to wrap the command line tools '''
  637. def __init__(self,
  638. namespace,
  639. kubeconfig='/etc/origin/master/admin.kubeconfig',
  640. verbose=False,
  641. all_namespaces=False):
  642. ''' Constructor for OpenshiftCLI '''
  643. self.namespace = namespace
  644. self.verbose = verbose
  645. self.kubeconfig = Utils.create_tmpfile_copy(kubeconfig)
  646. self.all_namespaces = all_namespaces
  647. # Pylint allows only 5 arguments to be passed.
  648. # pylint: disable=too-many-arguments
  649. def _replace_content(self, resource, rname, content, force=False, sep='.'):
  650. ''' replace the current object with the content '''
  651. res = self._get(resource, rname)
  652. if not res['results']:
  653. return res
  654. fname = Utils.create_tmpfile(rname + '-')
  655. yed = Yedit(fname, res['results'][0], separator=sep)
  656. changes = []
  657. for key, value in content.items():
  658. changes.append(yed.put(key, value))
  659. if any([change[0] for change in changes]):
  660. yed.write()
  661. atexit.register(Utils.cleanup, [fname])
  662. return self._replace(fname, force)
  663. return {'returncode': 0, 'updated': False}
  664. def _replace(self, fname, force=False):
  665. '''replace the current object with oc replace'''
  666. cmd = ['replace', '-f', fname]
  667. if force:
  668. cmd.append('--force')
  669. return self.openshift_cmd(cmd)
  670. def _create_from_content(self, rname, content):
  671. '''create a temporary file and then call oc create on it'''
  672. fname = Utils.create_tmpfile(rname + '-')
  673. yed = Yedit(fname, content=content)
  674. yed.write()
  675. atexit.register(Utils.cleanup, [fname])
  676. return self._create(fname)
  677. def _create(self, fname):
  678. '''call oc create on a filename'''
  679. return self.openshift_cmd(['create', '-f', fname])
  680. def _delete(self, resource, rname, selector=None):
  681. '''call oc delete on a resource'''
  682. cmd = ['delete', resource, rname]
  683. if selector:
  684. cmd.append('--selector=%s' % selector)
  685. return self.openshift_cmd(cmd)
  686. def _process(self, template_name, create=False, params=None, template_data=None): # noqa: E501
  687. '''process a template
  688. template_name: the name of the template to process
  689. create: whether to send to oc create after processing
  690. params: the parameters for the template
  691. template_data: the incoming template's data; instead of a file
  692. '''
  693. cmd = ['process']
  694. if template_data:
  695. cmd.extend(['-f', '-'])
  696. else:
  697. cmd.append(template_name)
  698. if params:
  699. param_str = ["%s=%s" % (key, value) for key, value in params.items()]
  700. cmd.append('-v')
  701. cmd.extend(param_str)
  702. results = self.openshift_cmd(cmd, output=True, input_data=template_data)
  703. if results['returncode'] != 0 or not create:
  704. return results
  705. fname = Utils.create_tmpfile(template_name + '-')
  706. yed = Yedit(fname, results['results'])
  707. yed.write()
  708. atexit.register(Utils.cleanup, [fname])
  709. return self.openshift_cmd(['create', '-f', fname])
  710. def _get(self, resource, rname=None, selector=None):
  711. '''return a resource by name '''
  712. cmd = ['get', resource]
  713. if selector:
  714. cmd.append('--selector=%s' % selector)
  715. elif rname:
  716. cmd.append(rname)
  717. cmd.extend(['-o', 'json'])
  718. rval = self.openshift_cmd(cmd, output=True)
  719. # Ensure results are retuned in an array
  720. if 'items' in rval:
  721. rval['results'] = rval['items']
  722. elif not isinstance(rval['results'], list):
  723. rval['results'] = [rval['results']]
  724. return rval
  725. def _schedulable(self, node=None, selector=None, schedulable=True):
  726. ''' perform oadm manage-node scheduable '''
  727. cmd = ['manage-node']
  728. if node:
  729. cmd.extend(node)
  730. else:
  731. cmd.append('--selector=%s' % selector)
  732. cmd.append('--schedulable=%s' % schedulable)
  733. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw') # noqa: E501
  734. def _list_pods(self, node=None, selector=None, pod_selector=None):
  735. ''' perform oadm list pods
  736. node: the node in which to list pods
  737. selector: the label selector filter if provided
  738. pod_selector: the pod selector filter if provided
  739. '''
  740. cmd = ['manage-node']
  741. if node:
  742. cmd.extend(node)
  743. else:
  744. cmd.append('--selector=%s' % selector)
  745. if pod_selector:
  746. cmd.append('--pod-selector=%s' % pod_selector)
  747. cmd.extend(['--list-pods', '-o', 'json'])
  748. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  749. # pylint: disable=too-many-arguments
  750. def _evacuate(self, node=None, selector=None, pod_selector=None, dry_run=False, grace_period=None, force=False):
  751. ''' perform oadm manage-node evacuate '''
  752. cmd = ['manage-node']
  753. if node:
  754. cmd.extend(node)
  755. else:
  756. cmd.append('--selector=%s' % selector)
  757. if dry_run:
  758. cmd.append('--dry-run')
  759. if pod_selector:
  760. cmd.append('--pod-selector=%s' % pod_selector)
  761. if grace_period:
  762. cmd.append('--grace-period=%s' % int(grace_period))
  763. if force:
  764. cmd.append('--force')
  765. cmd.append('--evacuate')
  766. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  767. def _version(self):
  768. ''' return the openshift version'''
  769. return self.openshift_cmd(['version'], output=True, output_type='raw')
  770. def _import_image(self, url=None, name=None, tag=None):
  771. ''' perform image import '''
  772. cmd = ['import-image']
  773. image = '{0}'.format(name)
  774. if tag:
  775. image += ':{0}'.format(tag)
  776. cmd.append(image)
  777. if url:
  778. cmd.append('--from={0}/{1}'.format(url, image))
  779. cmd.append('-n{0}'.format(self.namespace))
  780. cmd.append('--confirm')
  781. return self.openshift_cmd(cmd)
  782. def _run(self, cmds, input_data):
  783. ''' Actually executes the command. This makes mocking easier. '''
  784. curr_env = os.environ.copy()
  785. curr_env.update({'KUBECONFIG': self.kubeconfig})
  786. proc = subprocess.Popen(cmds,
  787. stdin=subprocess.PIPE,
  788. stdout=subprocess.PIPE,
  789. stderr=subprocess.PIPE,
  790. env=curr_env)
  791. stdout, stderr = proc.communicate(input_data)
  792. return proc.returncode, stdout.decode(), stderr.decode()
  793. # pylint: disable=too-many-arguments,too-many-branches
  794. def openshift_cmd(self, cmd, oadm=False, output=False, output_type='json', input_data=None):
  795. '''Base command for oc '''
  796. cmds = []
  797. if oadm:
  798. cmds = ['oadm']
  799. else:
  800. cmds = ['oc']
  801. if self.all_namespaces:
  802. cmds.extend(['--all-namespaces'])
  803. elif self.namespace is not None and self.namespace.lower() not in ['none', 'emtpy']: # E501
  804. cmds.extend(['-n', self.namespace])
  805. cmds.extend(cmd)
  806. rval = {}
  807. results = ''
  808. err = None
  809. if self.verbose:
  810. print(' '.join(cmds))
  811. returncode, stdout, stderr = self._run(cmds, input_data)
  812. rval = {"returncode": returncode,
  813. "results": results,
  814. "cmd": ' '.join(cmds)}
  815. if returncode == 0:
  816. if output:
  817. if output_type == 'json':
  818. try:
  819. rval['results'] = json.loads(stdout)
  820. except ValueError as err:
  821. if "No JSON object could be decoded" in err.args:
  822. err = err.args
  823. elif output_type == 'raw':
  824. rval['results'] = stdout
  825. if self.verbose:
  826. print("STDOUT: {0}".format(stdout))
  827. print("STDERR: {0}".format(stderr))
  828. if err:
  829. rval.update({"err": err,
  830. "stderr": stderr,
  831. "stdout": stdout,
  832. "cmd": cmds})
  833. else:
  834. rval.update({"stderr": stderr,
  835. "stdout": stdout,
  836. "results": {}})
  837. return rval
  838. class Utils(object):
  839. ''' utilities for openshiftcli modules '''
  840. @staticmethod
  841. def _write(filename, contents):
  842. ''' Actually write the file contents to disk. This helps with mocking. '''
  843. with open(filename, 'w') as sfd:
  844. sfd.write(contents)
  845. @staticmethod
  846. def create_tmp_file_from_contents(rname, data, ftype='yaml'):
  847. ''' create a file in tmp with name and contents'''
  848. tmp = Utils.create_tmpfile(prefix=rname)
  849. if ftype == 'yaml':
  850. # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage
  851. # pylint: disable=no-member
  852. if hasattr(yaml, 'RoundTripDumper'):
  853. Utils._write(tmp, yaml.dump(data, Dumper=yaml.RoundTripDumper))
  854. else:
  855. Utils._write(tmp, yaml.safe_dump(data, default_flow_style=False))
  856. elif ftype == 'json':
  857. Utils._write(tmp, json.dumps(data))
  858. else:
  859. Utils._write(tmp, data)
  860. # Register cleanup when module is done
  861. atexit.register(Utils.cleanup, [tmp])
  862. return tmp
  863. @staticmethod
  864. def create_tmpfile_copy(inc_file):
  865. '''create a temporary copy of a file'''
  866. tmpfile = Utils.create_tmpfile('lib_openshift-')
  867. Utils._write(tmpfile, open(inc_file).read())
  868. # Cleanup the tmpfile
  869. atexit.register(Utils.cleanup, [tmpfile])
  870. return tmpfile
  871. @staticmethod
  872. def create_tmpfile(prefix='tmp'):
  873. ''' Generates and returns a temporary file name '''
  874. with tempfile.NamedTemporaryFile(prefix=prefix, delete=False) as tmp:
  875. return tmp.name
  876. @staticmethod
  877. def create_tmp_files_from_contents(content, content_type=None):
  878. '''Turn an array of dict: filename, content into a files array'''
  879. if not isinstance(content, list):
  880. content = [content]
  881. files = []
  882. for item in content:
  883. path = Utils.create_tmp_file_from_contents(item['path'] + '-',
  884. item['data'],
  885. ftype=content_type)
  886. files.append({'name': os.path.basename(item['path']),
  887. 'path': path})
  888. return files
  889. @staticmethod
  890. def cleanup(files):
  891. '''Clean up on exit '''
  892. for sfile in files:
  893. if os.path.exists(sfile):
  894. if os.path.isdir(sfile):
  895. shutil.rmtree(sfile)
  896. elif os.path.isfile(sfile):
  897. os.remove(sfile)
  898. @staticmethod
  899. def exists(results, _name):
  900. ''' Check to see if the results include the name '''
  901. if not results:
  902. return False
  903. if Utils.find_result(results, _name):
  904. return True
  905. return False
  906. @staticmethod
  907. def find_result(results, _name):
  908. ''' Find the specified result by name'''
  909. rval = None
  910. for result in results:
  911. if 'metadata' in result and result['metadata']['name'] == _name:
  912. rval = result
  913. break
  914. return rval
  915. @staticmethod
  916. def get_resource_file(sfile, sfile_type='yaml'):
  917. ''' return the service file '''
  918. contents = None
  919. with open(sfile) as sfd:
  920. contents = sfd.read()
  921. if sfile_type == 'yaml':
  922. # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage
  923. # pylint: disable=no-member
  924. if hasattr(yaml, 'RoundTripLoader'):
  925. contents = yaml.load(contents, yaml.RoundTripLoader)
  926. else:
  927. contents = yaml.safe_load(contents)
  928. elif sfile_type == 'json':
  929. contents = json.loads(contents)
  930. return contents
  931. @staticmethod
  932. def filter_versions(stdout):
  933. ''' filter the oc version output '''
  934. version_dict = {}
  935. version_search = ['oc', 'openshift', 'kubernetes']
  936. for line in stdout.strip().split('\n'):
  937. for term in version_search:
  938. if not line:
  939. continue
  940. if line.startswith(term):
  941. version_dict[term] = line.split()[-1]
  942. # horrible hack to get openshift version in Openshift 3.2
  943. # By default "oc version in 3.2 does not return an "openshift" version
  944. if "openshift" not in version_dict:
  945. version_dict["openshift"] = version_dict["oc"]
  946. return version_dict
  947. @staticmethod
  948. def add_custom_versions(versions):
  949. ''' create custom versions strings '''
  950. versions_dict = {}
  951. for tech, version in versions.items():
  952. # clean up "-" from version
  953. if "-" in version:
  954. version = version.split("-")[0]
  955. if version.startswith('v'):
  956. versions_dict[tech + '_numeric'] = version[1:].split('+')[0]
  957. # "v3.3.0.33" is what we have, we want "3.3"
  958. versions_dict[tech + '_short'] = version[1:4]
  959. return versions_dict
  960. @staticmethod
  961. def openshift_installed():
  962. ''' check if openshift is installed '''
  963. import yum
  964. yum_base = yum.YumBase()
  965. if yum_base.rpmdb.searchNevra(name='atomic-openshift'):
  966. return True
  967. return False
  968. # Disabling too-many-branches. This is a yaml dictionary comparison function
  969. # pylint: disable=too-many-branches,too-many-return-statements,too-many-statements
  970. @staticmethod
  971. def check_def_equal(user_def, result_def, skip_keys=None, debug=False):
  972. ''' Given a user defined definition, compare it with the results given back by our query. '''
  973. # Currently these values are autogenerated and we do not need to check them
  974. skip = ['metadata', 'status']
  975. if skip_keys:
  976. skip.extend(skip_keys)
  977. for key, value in result_def.items():
  978. if key in skip:
  979. continue
  980. # Both are lists
  981. if isinstance(value, list):
  982. if key not in user_def:
  983. if debug:
  984. print('User data does not have key [%s]' % key)
  985. print('User data: %s' % user_def)
  986. return False
  987. if not isinstance(user_def[key], list):
  988. if debug:
  989. print('user_def[key] is not a list key=[%s] user_def[key]=%s' % (key, user_def[key]))
  990. return False
  991. if len(user_def[key]) != len(value):
  992. if debug:
  993. print("List lengths are not equal.")
  994. print("key=[%s]: user_def[%s] != value[%s]" % (key, len(user_def[key]), len(value)))
  995. print("user_def: %s" % user_def[key])
  996. print("value: %s" % value)
  997. return False
  998. for values in zip(user_def[key], value):
  999. if isinstance(values[0], dict) and isinstance(values[1], dict):
  1000. if debug:
  1001. print('sending list - list')
  1002. print(type(values[0]))
  1003. print(type(values[1]))
  1004. result = Utils.check_def_equal(values[0], values[1], skip_keys=skip_keys, debug=debug)
  1005. if not result:
  1006. print('list compare returned false')
  1007. return False
  1008. elif value != user_def[key]:
  1009. if debug:
  1010. print('value should be identical')
  1011. print(value)
  1012. print(user_def[key])
  1013. return False
  1014. # recurse on a dictionary
  1015. elif isinstance(value, dict):
  1016. if key not in user_def:
  1017. if debug:
  1018. print("user_def does not have key [%s]" % key)
  1019. return False
  1020. if not isinstance(user_def[key], dict):
  1021. if debug:
  1022. print("dict returned false: not instance of dict")
  1023. return False
  1024. # before passing ensure keys match
  1025. api_values = set(value.keys()) - set(skip)
  1026. user_values = set(user_def[key].keys()) - set(skip)
  1027. if api_values != user_values:
  1028. if debug:
  1029. print("keys are not equal in dict")
  1030. print(api_values)
  1031. print(user_values)
  1032. return False
  1033. result = Utils.check_def_equal(user_def[key], value, skip_keys=skip_keys, debug=debug)
  1034. if not result:
  1035. if debug:
  1036. print("dict returned false")
  1037. print(result)
  1038. return False
  1039. # Verify each key, value pair is the same
  1040. else:
  1041. if key not in user_def or value != user_def[key]:
  1042. if debug:
  1043. print("value not equal; user_def does not have key")
  1044. print(key)
  1045. print(value)
  1046. if key in user_def:
  1047. print(user_def[key])
  1048. return False
  1049. if debug:
  1050. print('returning true')
  1051. return True
  1052. class OpenShiftCLIConfig(object):
  1053. '''Generic Config'''
  1054. def __init__(self, rname, namespace, kubeconfig, options):
  1055. self.kubeconfig = kubeconfig
  1056. self.name = rname
  1057. self.namespace = namespace
  1058. self._options = options
  1059. @property
  1060. def config_options(self):
  1061. ''' return config options '''
  1062. return self._options
  1063. def to_option_list(self):
  1064. '''return all options as a string'''
  1065. return self.stringify()
  1066. def stringify(self):
  1067. ''' return the options hash as cli params in a string '''
  1068. rval = []
  1069. for key, data in self.config_options.items():
  1070. if data['include'] \
  1071. and (data['value'] or isinstance(data['value'], int)):
  1072. rval.append('--%s=%s' % (key.replace('_', '-'), data['value']))
  1073. return rval
  1074. # -*- -*- -*- End included fragment: lib/base.py -*- -*- -*-
  1075. # -*- -*- -*- Begin included fragment: lib/deploymentconfig.py -*- -*- -*-
  1076. # pylint: disable=too-many-public-methods
  1077. class DeploymentConfig(Yedit):
  1078. ''' Class to model an openshift DeploymentConfig'''
  1079. default_deployment_config = '''
  1080. apiVersion: v1
  1081. kind: DeploymentConfig
  1082. metadata:
  1083. name: default_dc
  1084. namespace: default
  1085. spec:
  1086. replicas: 0
  1087. selector:
  1088. default_dc: default_dc
  1089. strategy:
  1090. resources: {}
  1091. rollingParams:
  1092. intervalSeconds: 1
  1093. maxSurge: 0
  1094. maxUnavailable: 25%
  1095. timeoutSeconds: 600
  1096. updatePercent: -25
  1097. updatePeriodSeconds: 1
  1098. type: Rolling
  1099. template:
  1100. metadata:
  1101. spec:
  1102. containers:
  1103. - env:
  1104. - name: default
  1105. value: default
  1106. image: default
  1107. imagePullPolicy: IfNotPresent
  1108. name: default_dc
  1109. ports:
  1110. - containerPort: 8000
  1111. hostPort: 8000
  1112. protocol: TCP
  1113. name: default_port
  1114. resources: {}
  1115. terminationMessagePath: /dev/termination-log
  1116. dnsPolicy: ClusterFirst
  1117. hostNetwork: true
  1118. nodeSelector:
  1119. type: compute
  1120. restartPolicy: Always
  1121. securityContext: {}
  1122. serviceAccount: default
  1123. serviceAccountName: default
  1124. terminationGracePeriodSeconds: 30
  1125. triggers:
  1126. - type: ConfigChange
  1127. '''
  1128. replicas_path = "spec.replicas"
  1129. env_path = "spec.template.spec.containers[0].env"
  1130. volumes_path = "spec.template.spec.volumes"
  1131. container_path = "spec.template.spec.containers"
  1132. volume_mounts_path = "spec.template.spec.containers[0].volumeMounts"
  1133. def __init__(self, content=None):
  1134. ''' Constructor for deploymentconfig '''
  1135. if not content:
  1136. content = DeploymentConfig.default_deployment_config
  1137. super(DeploymentConfig, self).__init__(content=content)
  1138. def add_env_value(self, key, value):
  1139. ''' add key, value pair to env array '''
  1140. rval = False
  1141. env = self.get_env_vars()
  1142. if env:
  1143. env.append({'name': key, 'value': value})
  1144. rval = True
  1145. else:
  1146. result = self.put(DeploymentConfig.env_path, {'name': key, 'value': value})
  1147. rval = result[0]
  1148. return rval
  1149. def exists_env_value(self, key, value):
  1150. ''' return whether a key, value pair exists '''
  1151. results = self.get_env_vars()
  1152. if not results:
  1153. return False
  1154. for result in results:
  1155. if result['name'] == key and result['value'] == value:
  1156. return True
  1157. return False
  1158. def exists_env_key(self, key):
  1159. ''' return whether a key, value pair exists '''
  1160. results = self.get_env_vars()
  1161. if not results:
  1162. return False
  1163. for result in results:
  1164. if result['name'] == key:
  1165. return True
  1166. return False
  1167. def get_env_vars(self):
  1168. '''return a environment variables '''
  1169. return self.get(DeploymentConfig.env_path) or []
  1170. def delete_env_var(self, keys):
  1171. '''delete a list of keys '''
  1172. if not isinstance(keys, list):
  1173. keys = [keys]
  1174. env_vars_array = self.get_env_vars()
  1175. modified = False
  1176. idx = None
  1177. for key in keys:
  1178. for env_idx, env_var in enumerate(env_vars_array):
  1179. if env_var['name'] == key:
  1180. idx = env_idx
  1181. break
  1182. if idx:
  1183. modified = True
  1184. del env_vars_array[idx]
  1185. if modified:
  1186. return True
  1187. return False
  1188. def update_env_var(self, key, value):
  1189. '''place an env in the env var list'''
  1190. env_vars_array = self.get_env_vars()
  1191. idx = None
  1192. for env_idx, env_var in enumerate(env_vars_array):
  1193. if env_var['name'] == key:
  1194. idx = env_idx
  1195. break
  1196. if idx:
  1197. env_vars_array[idx]['value'] = value
  1198. else:
  1199. self.add_env_value(key, value)
  1200. return True
  1201. def exists_volume_mount(self, volume_mount):
  1202. ''' return whether a volume mount exists '''
  1203. exist_volume_mounts = self.get_volume_mounts()
  1204. if not exist_volume_mounts:
  1205. return False
  1206. volume_mount_found = False
  1207. for exist_volume_mount in exist_volume_mounts:
  1208. if exist_volume_mount['name'] == volume_mount['name']:
  1209. volume_mount_found = True
  1210. break
  1211. return volume_mount_found
  1212. def exists_volume(self, volume):
  1213. ''' return whether a volume exists '''
  1214. exist_volumes = self.get_volumes()
  1215. volume_found = False
  1216. for exist_volume in exist_volumes:
  1217. if exist_volume['name'] == volume['name']:
  1218. volume_found = True
  1219. break
  1220. return volume_found
  1221. def find_volume_by_name(self, volume, mounts=False):
  1222. ''' return the index of a volume '''
  1223. volumes = []
  1224. if mounts:
  1225. volumes = self.get_volume_mounts()
  1226. else:
  1227. volumes = self.get_volumes()
  1228. for exist_volume in volumes:
  1229. if exist_volume['name'] == volume['name']:
  1230. return exist_volume
  1231. return None
  1232. def get_replicas(self):
  1233. ''' return replicas setting '''
  1234. return self.get(DeploymentConfig.replicas_path)
  1235. def get_volume_mounts(self):
  1236. '''return volume mount information '''
  1237. return self.get_volumes(mounts=True)
  1238. def get_volumes(self, mounts=False):
  1239. '''return volume mount information '''
  1240. if mounts:
  1241. return self.get(DeploymentConfig.volume_mounts_path) or []
  1242. return self.get(DeploymentConfig.volumes_path) or []
  1243. def delete_volume_by_name(self, volume):
  1244. '''delete a volume '''
  1245. modified = False
  1246. exist_volume_mounts = self.get_volume_mounts()
  1247. exist_volumes = self.get_volumes()
  1248. del_idx = None
  1249. for idx, exist_volume in enumerate(exist_volumes):
  1250. if 'name' in exist_volume and exist_volume['name'] == volume['name']:
  1251. del_idx = idx
  1252. break
  1253. if del_idx != None:
  1254. del exist_volumes[del_idx]
  1255. modified = True
  1256. del_idx = None
  1257. for idx, exist_volume_mount in enumerate(exist_volume_mounts):
  1258. if 'name' in exist_volume_mount and exist_volume_mount['name'] == volume['name']:
  1259. del_idx = idx
  1260. break
  1261. if del_idx != None:
  1262. del exist_volume_mounts[idx]
  1263. modified = True
  1264. return modified
  1265. def add_volume_mount(self, volume_mount):
  1266. ''' add a volume or volume mount to the proper location '''
  1267. exist_volume_mounts = self.get_volume_mounts()
  1268. if not exist_volume_mounts and volume_mount:
  1269. self.put(DeploymentConfig.volume_mounts_path, [volume_mount])
  1270. else:
  1271. exist_volume_mounts.append(volume_mount)
  1272. def add_volume(self, volume):
  1273. ''' add a volume or volume mount to the proper location '''
  1274. exist_volumes = self.get_volumes()
  1275. if not volume:
  1276. return
  1277. if not exist_volumes:
  1278. self.put(DeploymentConfig.volumes_path, [volume])
  1279. else:
  1280. exist_volumes.append(volume)
  1281. def update_replicas(self, replicas):
  1282. ''' update replicas value '''
  1283. self.put(DeploymentConfig.replicas_path, replicas)
  1284. def update_volume(self, volume):
  1285. '''place an env in the env var list'''
  1286. exist_volumes = self.get_volumes()
  1287. if not volume:
  1288. return False
  1289. # update the volume
  1290. update_idx = None
  1291. for idx, exist_vol in enumerate(exist_volumes):
  1292. if exist_vol['name'] == volume['name']:
  1293. update_idx = idx
  1294. break
  1295. if update_idx != None:
  1296. exist_volumes[update_idx] = volume
  1297. else:
  1298. self.add_volume(volume)
  1299. return True
  1300. def update_volume_mount(self, volume_mount):
  1301. '''place an env in the env var list'''
  1302. modified = False
  1303. exist_volume_mounts = self.get_volume_mounts()
  1304. if not volume_mount:
  1305. return False
  1306. # update the volume mount
  1307. for exist_vol_mount in exist_volume_mounts:
  1308. if exist_vol_mount['name'] == volume_mount['name']:
  1309. if 'mountPath' in exist_vol_mount and \
  1310. str(exist_vol_mount['mountPath']) != str(volume_mount['mountPath']):
  1311. exist_vol_mount['mountPath'] = volume_mount['mountPath']
  1312. modified = True
  1313. break
  1314. if not modified:
  1315. self.add_volume_mount(volume_mount)
  1316. modified = True
  1317. return modified
  1318. def needs_update_volume(self, volume, volume_mount):
  1319. ''' verify a volume update is needed '''
  1320. exist_volume = self.find_volume_by_name(volume)
  1321. exist_volume_mount = self.find_volume_by_name(volume, mounts=True)
  1322. results = []
  1323. results.append(exist_volume['name'] == volume['name'])
  1324. if 'secret' in volume:
  1325. results.append('secret' in exist_volume)
  1326. results.append(exist_volume['secret']['secretName'] == volume['secret']['secretName'])
  1327. results.append(exist_volume_mount['name'] == volume_mount['name'])
  1328. results.append(exist_volume_mount['mountPath'] == volume_mount['mountPath'])
  1329. elif 'emptyDir' in volume:
  1330. results.append(exist_volume_mount['name'] == volume['name'])
  1331. results.append(exist_volume_mount['mountPath'] == volume_mount['mountPath'])
  1332. elif 'persistentVolumeClaim' in volume:
  1333. pvc = 'persistentVolumeClaim'
  1334. results.append(pvc in exist_volume)
  1335. if results[-1]:
  1336. results.append(exist_volume[pvc]['claimName'] == volume[pvc]['claimName'])
  1337. if 'claimSize' in volume[pvc]:
  1338. results.append(exist_volume[pvc]['claimSize'] == volume[pvc]['claimSize'])
  1339. elif 'hostpath' in volume:
  1340. results.append('hostPath' in exist_volume)
  1341. results.append(exist_volume['hostPath']['path'] == volume_mount['mountPath'])
  1342. return not all(results)
  1343. def needs_update_replicas(self, replicas):
  1344. ''' verify whether a replica update is needed '''
  1345. current_reps = self.get(DeploymentConfig.replicas_path)
  1346. return not current_reps == replicas
  1347. # -*- -*- -*- End included fragment: lib/deploymentconfig.py -*- -*- -*-
  1348. # -*- -*- -*- Begin included fragment: class/oc_env.py -*- -*- -*-
  1349. # pylint: disable=too-many-instance-attributes
  1350. class OCEnv(OpenShiftCLI):
  1351. ''' Class to wrap the oc command line tools '''
  1352. container_path = {"pod": "spec.containers[0].env",
  1353. "dc": "spec.template.spec.containers[0].env",
  1354. "rc": "spec.template.spec.containers[0].env",
  1355. }
  1356. # pylint allows 5. we need 6
  1357. # pylint: disable=too-many-arguments
  1358. def __init__(self,
  1359. namespace,
  1360. kind,
  1361. env_vars,
  1362. resource_name=None,
  1363. kubeconfig='/etc/origin/master/admin.kubeconfig',
  1364. verbose=False):
  1365. ''' Constructor for OpenshiftOC '''
  1366. super(OCEnv, self).__init__(namespace, kubeconfig=kubeconfig, verbose=verbose)
  1367. self.kind = kind
  1368. self.name = resource_name
  1369. self.env_vars = env_vars
  1370. self._resource = None
  1371. @property
  1372. def resource(self):
  1373. ''' property function for resource var'''
  1374. if not self._resource:
  1375. self.get()
  1376. return self._resource
  1377. @resource.setter
  1378. def resource(self, data):
  1379. ''' setter function for resource var'''
  1380. self._resource = data
  1381. def key_value_exists(self, key, value):
  1382. ''' return whether a key, value pair exists '''
  1383. return self.resource.exists_env_value(key, value)
  1384. def key_exists(self, key):
  1385. ''' return whether a key exists '''
  1386. return self.resource.exists_env_key(key)
  1387. def get(self):
  1388. '''return environment variables '''
  1389. result = self._get(self.kind, self.name)
  1390. if result['returncode'] == 0:
  1391. if self.kind == 'dc':
  1392. self.resource = DeploymentConfig(content=result['results'][0])
  1393. result['results'] = self.resource.get(OCEnv.container_path[self.kind]) or []
  1394. return result
  1395. def delete(self):
  1396. ''' delete environment variables '''
  1397. if self.resource.delete_env_var(self.env_vars.keys()):
  1398. return self._replace_content(self.kind, self.name, self.resource.yaml_dict)
  1399. return {'returncode': 0, 'changed': False}
  1400. def put(self):
  1401. '''place env vars into dc '''
  1402. for update_key, update_value in self.env_vars.items():
  1403. self.resource.update_env_var(update_key, update_value)
  1404. return self._replace_content(self.kind, self.name, self.resource.yaml_dict)
  1405. # pylint: disable=too-many-return-statements
  1406. @staticmethod
  1407. def run_ansible(params, check_mode):
  1408. '''run the idempotent ansible code'''
  1409. ocenv = OCEnv(params['namespace'],
  1410. params['kind'],
  1411. params['env_vars'],
  1412. resource_name=params['name'],
  1413. kubeconfig=params['kubeconfig'],
  1414. verbose=params['debug'])
  1415. state = params['state']
  1416. api_rval = ocenv.get()
  1417. #####
  1418. # Get
  1419. #####
  1420. if state == 'list':
  1421. return {'changed': False, 'results': api_rval['results'], 'state': "list"}
  1422. ########
  1423. # Delete
  1424. ########
  1425. if state == 'absent':
  1426. for key in params.get('env_vars', {}).keys():
  1427. if ocenv.resource.exists_env_key(key):
  1428. if check_mode:
  1429. return {'changed': False,
  1430. 'msg': 'CHECK_MODE: Would have performed a delete.'}
  1431. api_rval = ocenv.delete()
  1432. return {'changed': True, 'state': 'absent'}
  1433. return {'changed': False, 'state': 'absent'}
  1434. if state == 'present':
  1435. ########
  1436. # Create
  1437. ########
  1438. for key, value in params.get('env_vars', {}).items():
  1439. if not ocenv.key_value_exists(key, value):
  1440. if check_mode:
  1441. return {'changed': False,
  1442. 'msg': 'CHECK_MODE: Would have performed a create.'}
  1443. # Create it here
  1444. api_rval = ocenv.put()
  1445. if api_rval['returncode'] != 0:
  1446. return {'failed': True, 'msg': api_rval}
  1447. # return the created object
  1448. api_rval = ocenv.get()
  1449. if api_rval['returncode'] != 0:
  1450. return {'failed': True, 'msg': api_rval}
  1451. return {'changed': True, 'results': api_rval['results'], 'state': 'present'}
  1452. return {'changed': False, 'results': api_rval['results'], 'state': 'present'}
  1453. return {'failed': True,
  1454. 'changed': False,
  1455. 'msg': 'Unknown state passed. %s' % state}
  1456. # -*- -*- -*- End included fragment: class/oc_env.py -*- -*- -*-
  1457. # -*- -*- -*- Begin included fragment: ansible/oc_env.py -*- -*- -*-
  1458. def main():
  1459. '''
  1460. ansible oc module for environment variables
  1461. '''
  1462. module = AnsibleModule(
  1463. argument_spec=dict(
  1464. kubeconfig=dict(default='/etc/origin/master/admin.kubeconfig', type='str'),
  1465. state=dict(default='present', type='str',
  1466. choices=['present', 'absent', 'list']),
  1467. debug=dict(default=False, type='bool'),
  1468. kind=dict(default='rc', choices=['dc', 'rc', 'pods'], type='str'),
  1469. namespace=dict(default='default', type='str'),
  1470. name=dict(default=None, required=True, type='str'),
  1471. env_vars=dict(default=None, type='dict'),
  1472. ),
  1473. mutually_exclusive=[["content", "files"]],
  1474. supports_check_mode=True,
  1475. )
  1476. results = OCEnv.run_ansible(module.params, module.check_mode)
  1477. if 'failed' in results:
  1478. module.fail_json(**results)
  1479. module.exit_json(**results)
  1480. if __name__ == '__main__':
  1481. main()
  1482. # -*- -*- -*- End included fragment: ansible/oc_env.py -*- -*- -*-