oc_volume.py 69 KB

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