oc_env.py 59 KB

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