oc_env.py 58 KB

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