oc_env.py 61 KB

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