oc_env.py 57 KB

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