oc_env.py 58 KB

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