oc_env.py 58 KB

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