oc_volume.py 70 KB

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