oc_env.py 60 KB

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