oc_obj.py 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483
  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 json
  35. import os
  36. import re
  37. import shutil
  38. import subprocess
  39. # pylint: disable=import-error
  40. import ruamel.yaml as yaml
  41. from ansible.module_utils.basic import AnsibleModule
  42. # -*- -*- -*- End included fragment: lib/import.py -*- -*- -*-
  43. # -*- -*- -*- Begin included fragment: doc/obj -*- -*- -*-
  44. DOCUMENTATION = '''
  45. ---
  46. module: oc_obj
  47. short_description: Generic interface to openshift objects
  48. description:
  49. - Manage openshift objects programmatically.
  50. options:
  51. state:
  52. description:
  53. - Currently present is only supported state.
  54. required: true
  55. default: present
  56. choices: ["present", "absent", "list"]
  57. aliases: []
  58. kubeconfig:
  59. description:
  60. - The path for the kubeconfig file to use for authentication
  61. required: false
  62. default: /etc/origin/master/admin.kubeconfig
  63. aliases: []
  64. debug:
  65. description:
  66. - Turn on debug output.
  67. required: false
  68. default: False
  69. aliases: []
  70. name:
  71. description:
  72. - Name of the object that is being queried.
  73. required: false
  74. default: None
  75. aliases: []
  76. namespace:
  77. description:
  78. - The namespace where the object lives.
  79. required: false
  80. default: str
  81. aliases: []
  82. all_namespace:
  83. description:
  84. - The namespace where the object lives.
  85. required: false
  86. default: false
  87. aliases: []
  88. kind:
  89. description:
  90. - The kind attribute of the object. e.g. dc, bc, svc, route
  91. required: True
  92. default: None
  93. aliases: []
  94. files:
  95. description:
  96. - A list of files provided for object
  97. required: false
  98. default: None
  99. aliases: []
  100. delete_after:
  101. description:
  102. - Whether or not to delete the files after processing them.
  103. required: false
  104. default: false
  105. aliases: []
  106. content:
  107. description:
  108. - Content of the object being managed.
  109. required: false
  110. default: None
  111. aliases: []
  112. force:
  113. description:
  114. - Whether or not to force the operation
  115. required: false
  116. default: None
  117. aliases: []
  118. selector:
  119. description:
  120. - Selector that gets added to the query.
  121. required: false
  122. default: None
  123. aliases: []
  124. author:
  125. - "Kenny Woodson <kwoodson@redhat.com>"
  126. extends_documentation_fragment: []
  127. '''
  128. EXAMPLES = '''
  129. oc_obj:
  130. kind: dc
  131. name: router
  132. namespace: default
  133. register: router_output
  134. '''
  135. # -*- -*- -*- End included fragment: doc/obj -*- -*- -*-
  136. # -*- -*- -*- Begin included fragment: ../../lib_utils/src/class/yedit.py -*- -*- -*-
  137. # noqa: E301,E302
  138. class YeditException(Exception):
  139. ''' Exception class for Yedit '''
  140. pass
  141. # pylint: disable=too-many-public-methods
  142. class Yedit(object):
  143. ''' Class to modify yaml files '''
  144. re_valid_key = r"(((\[-?\d+\])|([0-9a-zA-Z%s/_-]+)).?)+$"
  145. re_key = r"(?:\[(-?\d+)\])|([0-9a-zA-Z%s/_-]+)"
  146. com_sep = set(['.', '#', '|', ':'])
  147. # pylint: disable=too-many-arguments
  148. def __init__(self,
  149. filename=None,
  150. content=None,
  151. content_type='yaml',
  152. separator='.',
  153. backup=False):
  154. self.content = content
  155. self._separator = separator
  156. self.filename = filename
  157. self.__yaml_dict = content
  158. self.content_type = content_type
  159. self.backup = backup
  160. self.load(content_type=self.content_type)
  161. if self.__yaml_dict is None:
  162. self.__yaml_dict = {}
  163. @property
  164. def separator(self):
  165. ''' getter method for yaml_dict '''
  166. return self._separator
  167. @separator.setter
  168. def separator(self):
  169. ''' getter method for yaml_dict '''
  170. return self._separator
  171. @property
  172. def yaml_dict(self):
  173. ''' getter method for yaml_dict '''
  174. return self.__yaml_dict
  175. @yaml_dict.setter
  176. def yaml_dict(self, value):
  177. ''' setter method for yaml_dict '''
  178. self.__yaml_dict = value
  179. @staticmethod
  180. def parse_key(key, sep='.'):
  181. '''parse the key allowing the appropriate separator'''
  182. common_separators = list(Yedit.com_sep - set([sep]))
  183. return re.findall(Yedit.re_key % ''.join(common_separators), key)
  184. @staticmethod
  185. def valid_key(key, sep='.'):
  186. '''validate the incoming key'''
  187. common_separators = list(Yedit.com_sep - set([sep]))
  188. if not re.match(Yedit.re_valid_key % ''.join(common_separators), key):
  189. return False
  190. return True
  191. @staticmethod
  192. def remove_entry(data, key, sep='.'):
  193. ''' remove data at location key '''
  194. if key == '' and isinstance(data, dict):
  195. data.clear()
  196. return True
  197. elif key == '' and isinstance(data, list):
  198. del data[:]
  199. return True
  200. if not (key and Yedit.valid_key(key, sep)) and \
  201. isinstance(data, (list, dict)):
  202. return None
  203. key_indexes = Yedit.parse_key(key, sep)
  204. for arr_ind, dict_key in key_indexes[:-1]:
  205. if dict_key and isinstance(data, dict):
  206. data = data.get(dict_key, None)
  207. elif (arr_ind and isinstance(data, list) and
  208. int(arr_ind) <= len(data) - 1):
  209. data = data[int(arr_ind)]
  210. else:
  211. return None
  212. # process last index for remove
  213. # expected list entry
  214. if key_indexes[-1][0]:
  215. if isinstance(data, list) and int(key_indexes[-1][0]) <= len(data) - 1: # noqa: E501
  216. del data[int(key_indexes[-1][0])]
  217. return True
  218. # expected dict entry
  219. elif key_indexes[-1][1]:
  220. if isinstance(data, dict):
  221. del data[key_indexes[-1][1]]
  222. return True
  223. @staticmethod
  224. def add_entry(data, key, item=None, sep='.'):
  225. ''' Get an item from a dictionary with key notation a.b.c
  226. d = {'a': {'b': 'c'}}}
  227. key = a#b
  228. return c
  229. '''
  230. if key == '':
  231. pass
  232. elif (not (key and Yedit.valid_key(key, sep)) and
  233. isinstance(data, (list, dict))):
  234. return None
  235. key_indexes = Yedit.parse_key(key, sep)
  236. for arr_ind, dict_key in key_indexes[:-1]:
  237. if dict_key:
  238. if isinstance(data, dict) and dict_key in data and data[dict_key]: # noqa: E501
  239. data = data[dict_key]
  240. continue
  241. elif data and not isinstance(data, dict):
  242. return None
  243. data[dict_key] = {}
  244. data = data[dict_key]
  245. elif (arr_ind and isinstance(data, list) and
  246. int(arr_ind) <= len(data) - 1):
  247. data = data[int(arr_ind)]
  248. else:
  249. return None
  250. if key == '':
  251. data = item
  252. # process last index for add
  253. # expected list entry
  254. elif key_indexes[-1][0] and isinstance(data, list) and int(key_indexes[-1][0]) <= len(data) - 1: # noqa: E501
  255. data[int(key_indexes[-1][0])] = item
  256. # expected dict entry
  257. elif key_indexes[-1][1] and isinstance(data, dict):
  258. data[key_indexes[-1][1]] = item
  259. return data
  260. @staticmethod
  261. def get_entry(data, key, sep='.'):
  262. ''' Get an item from a dictionary with key notation a.b.c
  263. d = {'a': {'b': 'c'}}}
  264. key = a.b
  265. return c
  266. '''
  267. if key == '':
  268. pass
  269. elif (not (key and Yedit.valid_key(key, sep)) and
  270. isinstance(data, (list, dict))):
  271. return None
  272. key_indexes = Yedit.parse_key(key, sep)
  273. for arr_ind, dict_key in key_indexes:
  274. if dict_key and isinstance(data, dict):
  275. data = data.get(dict_key, None)
  276. elif (arr_ind and isinstance(data, list) and
  277. int(arr_ind) <= len(data) - 1):
  278. data = data[int(arr_ind)]
  279. else:
  280. return None
  281. return data
  282. @staticmethod
  283. def _write(filename, contents):
  284. ''' Actually write the file contents to disk. This helps with mocking. '''
  285. tmp_filename = filename + '.yedit'
  286. with open(tmp_filename, 'w') as yfd:
  287. yfd.write(contents)
  288. os.rename(tmp_filename, filename)
  289. def write(self):
  290. ''' write to file '''
  291. if not self.filename:
  292. raise YeditException('Please specify a filename.')
  293. if self.backup and self.file_exists():
  294. shutil.copy(self.filename, self.filename + '.orig')
  295. # pylint: disable=no-member
  296. if hasattr(self.yaml_dict, 'fa'):
  297. self.yaml_dict.fa.set_block_style()
  298. Yedit._write(self.filename, yaml.dump(self.yaml_dict, Dumper=yaml.RoundTripDumper))
  299. return (True, self.yaml_dict)
  300. def read(self):
  301. ''' read from file '''
  302. # check if it exists
  303. if self.filename is None or not self.file_exists():
  304. return None
  305. contents = None
  306. with open(self.filename) as yfd:
  307. contents = yfd.read()
  308. return contents
  309. def file_exists(self):
  310. ''' return whether file exists '''
  311. if os.path.exists(self.filename):
  312. return True
  313. return False
  314. def load(self, content_type='yaml'):
  315. ''' return yaml file '''
  316. contents = self.read()
  317. if not contents and not self.content:
  318. return None
  319. if self.content:
  320. if isinstance(self.content, dict):
  321. self.yaml_dict = self.content
  322. return self.yaml_dict
  323. elif isinstance(self.content, str):
  324. contents = self.content
  325. # check if it is yaml
  326. try:
  327. if content_type == 'yaml' and contents:
  328. self.yaml_dict = yaml.load(contents, yaml.RoundTripLoader)
  329. # pylint: disable=no-member
  330. if hasattr(self.yaml_dict, 'fa'):
  331. self.yaml_dict.fa.set_block_style()
  332. elif content_type == 'json' and contents:
  333. self.yaml_dict = json.loads(contents)
  334. except yaml.YAMLError as err:
  335. # Error loading yaml or json
  336. raise YeditException('Problem with loading yaml file. %s' % err)
  337. return self.yaml_dict
  338. def get(self, key):
  339. ''' get a specified key'''
  340. try:
  341. entry = Yedit.get_entry(self.yaml_dict, key, self.separator)
  342. except KeyError:
  343. entry = None
  344. return entry
  345. def pop(self, path, key_or_item):
  346. ''' remove a key, value pair from a dict or an item for a list'''
  347. try:
  348. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  349. except KeyError:
  350. entry = None
  351. if entry is None:
  352. return (False, self.yaml_dict)
  353. if isinstance(entry, dict):
  354. # pylint: disable=no-member,maybe-no-member
  355. if key_or_item in entry:
  356. entry.pop(key_or_item)
  357. return (True, self.yaml_dict)
  358. return (False, self.yaml_dict)
  359. elif isinstance(entry, list):
  360. # pylint: disable=no-member,maybe-no-member
  361. ind = None
  362. try:
  363. ind = entry.index(key_or_item)
  364. except ValueError:
  365. return (False, self.yaml_dict)
  366. entry.pop(ind)
  367. return (True, self.yaml_dict)
  368. return (False, self.yaml_dict)
  369. def delete(self, path):
  370. ''' remove path from a dict'''
  371. try:
  372. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  373. except KeyError:
  374. entry = None
  375. if entry is None:
  376. return (False, self.yaml_dict)
  377. result = Yedit.remove_entry(self.yaml_dict, path, self.separator)
  378. if not result:
  379. return (False, self.yaml_dict)
  380. return (True, self.yaml_dict)
  381. def exists(self, path, value):
  382. ''' check if value exists at path'''
  383. try:
  384. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  385. except KeyError:
  386. entry = None
  387. if isinstance(entry, list):
  388. if value in entry:
  389. return True
  390. return False
  391. elif isinstance(entry, dict):
  392. if isinstance(value, dict):
  393. rval = False
  394. for key, val in value.items():
  395. if entry[key] != val:
  396. rval = False
  397. break
  398. else:
  399. rval = True
  400. return rval
  401. return value in entry
  402. return entry == value
  403. def append(self, path, value):
  404. '''append value to a list'''
  405. try:
  406. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  407. except KeyError:
  408. entry = None
  409. if entry is None:
  410. self.put(path, [])
  411. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  412. if not isinstance(entry, list):
  413. return (False, self.yaml_dict)
  414. # pylint: disable=no-member,maybe-no-member
  415. entry.append(value)
  416. return (True, self.yaml_dict)
  417. # pylint: disable=too-many-arguments
  418. def update(self, path, value, index=None, curr_value=None):
  419. ''' put path, value into a dict '''
  420. try:
  421. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  422. except KeyError:
  423. entry = None
  424. if isinstance(entry, dict):
  425. # pylint: disable=no-member,maybe-no-member
  426. if not isinstance(value, dict):
  427. raise YeditException('Cannot replace key, value entry in ' +
  428. 'dict with non-dict type. value=[%s] [%s]' % (value, type(value))) # noqa: E501
  429. entry.update(value)
  430. return (True, self.yaml_dict)
  431. elif isinstance(entry, list):
  432. # pylint: disable=no-member,maybe-no-member
  433. ind = None
  434. if curr_value:
  435. try:
  436. ind = entry.index(curr_value)
  437. except ValueError:
  438. return (False, self.yaml_dict)
  439. elif index is not None:
  440. ind = index
  441. if ind is not None and entry[ind] != value:
  442. entry[ind] = value
  443. return (True, self.yaml_dict)
  444. # see if it exists in the list
  445. try:
  446. ind = entry.index(value)
  447. except ValueError:
  448. # doesn't exist, append it
  449. entry.append(value)
  450. return (True, self.yaml_dict)
  451. # already exists, return
  452. if ind is not None:
  453. return (False, self.yaml_dict)
  454. return (False, self.yaml_dict)
  455. def put(self, path, value):
  456. ''' put path, value into a dict '''
  457. try:
  458. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  459. except KeyError:
  460. entry = None
  461. if entry == value:
  462. return (False, self.yaml_dict)
  463. # deepcopy didn't work
  464. tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict,
  465. default_flow_style=False),
  466. yaml.RoundTripLoader)
  467. # pylint: disable=no-member
  468. if hasattr(self.yaml_dict, 'fa'):
  469. tmp_copy.fa.set_block_style()
  470. result = Yedit.add_entry(tmp_copy, path, value, self.separator)
  471. if not result:
  472. return (False, self.yaml_dict)
  473. self.yaml_dict = tmp_copy
  474. return (True, self.yaml_dict)
  475. def create(self, path, value):
  476. ''' create a yaml file '''
  477. if not self.file_exists():
  478. # deepcopy didn't work
  479. tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict, default_flow_style=False), # noqa: E501
  480. yaml.RoundTripLoader)
  481. # pylint: disable=no-member
  482. if hasattr(self.yaml_dict, 'fa'):
  483. tmp_copy.fa.set_block_style()
  484. result = Yedit.add_entry(tmp_copy, path, value, self.separator)
  485. if result:
  486. self.yaml_dict = tmp_copy
  487. return (True, self.yaml_dict)
  488. return (False, self.yaml_dict)
  489. @staticmethod
  490. def get_curr_value(invalue, val_type):
  491. '''return the current value'''
  492. if invalue is None:
  493. return None
  494. curr_value = invalue
  495. if val_type == 'yaml':
  496. curr_value = yaml.load(invalue)
  497. elif val_type == 'json':
  498. curr_value = json.loads(invalue)
  499. return curr_value
  500. @staticmethod
  501. def parse_value(inc_value, vtype=''):
  502. '''determine value type passed'''
  503. true_bools = ['y', 'Y', 'yes', 'Yes', 'YES', 'true', 'True', 'TRUE',
  504. 'on', 'On', 'ON', ]
  505. false_bools = ['n', 'N', 'no', 'No', 'NO', 'false', 'False', 'FALSE',
  506. 'off', 'Off', 'OFF']
  507. # It came in as a string but you didn't specify value_type as string
  508. # we will convert to bool if it matches any of the above cases
  509. if isinstance(inc_value, str) and 'bool' in vtype:
  510. if inc_value not in true_bools and inc_value not in false_bools:
  511. raise YeditException('Not a boolean type. str=[%s] vtype=[%s]'
  512. % (inc_value, vtype))
  513. elif isinstance(inc_value, bool) and 'str' in vtype:
  514. inc_value = str(inc_value)
  515. # If vtype is not str then go ahead and attempt to yaml load it.
  516. if isinstance(inc_value, str) and 'str' not in vtype:
  517. try:
  518. inc_value = yaml.load(inc_value)
  519. except Exception:
  520. raise YeditException('Could not determine type of incoming ' +
  521. 'value. value=[%s] vtype=[%s]'
  522. % (type(inc_value), vtype))
  523. return inc_value
  524. # pylint: disable=too-many-return-statements,too-many-branches
  525. @staticmethod
  526. def run_ansible(module):
  527. '''perform the idempotent crud operations'''
  528. yamlfile = Yedit(filename=module.params['src'],
  529. backup=module.params['backup'],
  530. separator=module.params['separator'])
  531. if module.params['src']:
  532. rval = yamlfile.load()
  533. if yamlfile.yaml_dict is None and \
  534. module.params['state'] != 'present':
  535. return {'failed': True,
  536. 'msg': 'Error opening file [%s]. Verify that the ' +
  537. 'file exists, that it is has correct' +
  538. ' permissions, and is valid yaml.'}
  539. if module.params['state'] == 'list':
  540. if module.params['content']:
  541. content = Yedit.parse_value(module.params['content'],
  542. module.params['content_type'])
  543. yamlfile.yaml_dict = content
  544. if module.params['key']:
  545. rval = yamlfile.get(module.params['key']) or {}
  546. return {'changed': False, 'result': rval, 'state': "list"}
  547. elif module.params['state'] == 'absent':
  548. if module.params['content']:
  549. content = Yedit.parse_value(module.params['content'],
  550. module.params['content_type'])
  551. yamlfile.yaml_dict = content
  552. if module.params['update']:
  553. rval = yamlfile.pop(module.params['key'],
  554. module.params['value'])
  555. else:
  556. rval = yamlfile.delete(module.params['key'])
  557. if rval[0] and module.params['src']:
  558. yamlfile.write()
  559. return {'changed': rval[0], 'result': rval[1], 'state': "absent"}
  560. elif module.params['state'] == 'present':
  561. # check if content is different than what is in the file
  562. if module.params['content']:
  563. content = Yedit.parse_value(module.params['content'],
  564. module.params['content_type'])
  565. # We had no edits to make and the contents are the same
  566. if yamlfile.yaml_dict == content and \
  567. module.params['value'] is None:
  568. return {'changed': False,
  569. 'result': yamlfile.yaml_dict,
  570. 'state': "present"}
  571. yamlfile.yaml_dict = content
  572. # we were passed a value; parse it
  573. if module.params['value']:
  574. value = Yedit.parse_value(module.params['value'],
  575. module.params['value_type'])
  576. key = module.params['key']
  577. if module.params['update']:
  578. # pylint: disable=line-too-long
  579. curr_value = Yedit.get_curr_value(Yedit.parse_value(module.params['curr_value']), # noqa: E501
  580. module.params['curr_value_format']) # noqa: E501
  581. rval = yamlfile.update(key, value, module.params['index'], curr_value) # noqa: E501
  582. elif module.params['append']:
  583. rval = yamlfile.append(key, value)
  584. else:
  585. rval = yamlfile.put(key, value)
  586. if rval[0] and module.params['src']:
  587. yamlfile.write()
  588. return {'changed': rval[0],
  589. 'result': rval[1], 'state': "present"}
  590. # no edits to make
  591. if module.params['src']:
  592. # pylint: disable=redefined-variable-type
  593. rval = yamlfile.write()
  594. return {'changed': rval[0],
  595. 'result': rval[1],
  596. 'state': "present"}
  597. return {'failed': True, 'msg': 'Unkown state passed'}
  598. # -*- -*- -*- End included fragment: ../../lib_utils/src/class/yedit.py -*- -*- -*-
  599. # -*- -*- -*- Begin included fragment: lib/base.py -*- -*- -*-
  600. # pylint: disable=too-many-lines
  601. # noqa: E301,E302,E303,T001
  602. class OpenShiftCLIError(Exception):
  603. '''Exception class for openshiftcli'''
  604. pass
  605. # pylint: disable=too-few-public-methods
  606. class OpenShiftCLI(object):
  607. ''' Class to wrap the command line tools '''
  608. def __init__(self,
  609. namespace,
  610. kubeconfig='/etc/origin/master/admin.kubeconfig',
  611. verbose=False,
  612. all_namespaces=False):
  613. ''' Constructor for OpenshiftCLI '''
  614. self.namespace = namespace
  615. self.verbose = verbose
  616. self.kubeconfig = kubeconfig
  617. self.all_namespaces = all_namespaces
  618. # Pylint allows only 5 arguments to be passed.
  619. # pylint: disable=too-many-arguments
  620. def _replace_content(self, resource, rname, content, force=False, sep='.'):
  621. ''' replace the current object with the content '''
  622. res = self._get(resource, rname)
  623. if not res['results']:
  624. return res
  625. fname = '/tmp/%s' % rname
  626. yed = Yedit(fname, res['results'][0], separator=sep)
  627. changes = []
  628. for key, value in content.items():
  629. changes.append(yed.put(key, value))
  630. if any([change[0] for change in changes]):
  631. yed.write()
  632. atexit.register(Utils.cleanup, [fname])
  633. return self._replace(fname, force)
  634. return {'returncode': 0, 'updated': False}
  635. def _replace(self, fname, force=False):
  636. '''replace the current object with oc replace'''
  637. cmd = ['replace', '-f', fname]
  638. if force:
  639. cmd.append('--force')
  640. return self.openshift_cmd(cmd)
  641. def _create_from_content(self, rname, content):
  642. '''create a temporary file and then call oc create on it'''
  643. fname = '/tmp/%s' % rname
  644. yed = Yedit(fname, content=content)
  645. yed.write()
  646. atexit.register(Utils.cleanup, [fname])
  647. return self._create(fname)
  648. def _create(self, fname):
  649. '''call oc create on a filename'''
  650. return self.openshift_cmd(['create', '-f', fname])
  651. def _delete(self, resource, rname, selector=None):
  652. '''call oc delete on a resource'''
  653. cmd = ['delete', resource, rname]
  654. if selector:
  655. cmd.append('--selector=%s' % selector)
  656. return self.openshift_cmd(cmd)
  657. def _process(self, template_name, create=False, params=None, template_data=None): # noqa: E501
  658. '''process a template
  659. template_name: the name of the template to process
  660. create: whether to send to oc create after processing
  661. params: the parameters for the template
  662. template_data: the incoming template's data; instead of a file
  663. '''
  664. cmd = ['process']
  665. if template_data:
  666. cmd.extend(['-f', '-'])
  667. else:
  668. cmd.append(template_name)
  669. if params:
  670. param_str = ["%s=%s" % (key, value) for key, value in params.items()]
  671. cmd.append('-v')
  672. cmd.extend(param_str)
  673. results = self.openshift_cmd(cmd, output=True, input_data=template_data)
  674. if results['returncode'] != 0 or not create:
  675. return results
  676. fname = '/tmp/%s' % template_name
  677. yed = Yedit(fname, results['results'])
  678. yed.write()
  679. atexit.register(Utils.cleanup, [fname])
  680. return self.openshift_cmd(['create', '-f', fname])
  681. def _get(self, resource, rname=None, selector=None):
  682. '''return a resource by name '''
  683. cmd = ['get', resource]
  684. if selector:
  685. cmd.append('--selector=%s' % selector)
  686. elif rname:
  687. cmd.append(rname)
  688. cmd.extend(['-o', 'json'])
  689. rval = self.openshift_cmd(cmd, output=True)
  690. # Ensure results are retuned in an array
  691. if 'items' in rval:
  692. rval['results'] = rval['items']
  693. elif not isinstance(rval['results'], list):
  694. rval['results'] = [rval['results']]
  695. return rval
  696. def _schedulable(self, node=None, selector=None, schedulable=True):
  697. ''' perform oadm manage-node scheduable '''
  698. cmd = ['manage-node']
  699. if node:
  700. cmd.extend(node)
  701. else:
  702. cmd.append('--selector=%s' % selector)
  703. cmd.append('--schedulable=%s' % schedulable)
  704. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw') # noqa: E501
  705. def _list_pods(self, node=None, selector=None, pod_selector=None):
  706. ''' perform oadm list pods
  707. node: the node in which to list pods
  708. selector: the label selector filter if provided
  709. pod_selector: the pod selector filter if provided
  710. '''
  711. cmd = ['manage-node']
  712. if node:
  713. cmd.extend(node)
  714. else:
  715. cmd.append('--selector=%s' % selector)
  716. if pod_selector:
  717. cmd.append('--pod-selector=%s' % pod_selector)
  718. cmd.extend(['--list-pods', '-o', 'json'])
  719. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  720. # pylint: disable=too-many-arguments
  721. def _evacuate(self, node=None, selector=None, pod_selector=None, dry_run=False, grace_period=None, force=False):
  722. ''' perform oadm manage-node evacuate '''
  723. cmd = ['manage-node']
  724. if node:
  725. cmd.extend(node)
  726. else:
  727. cmd.append('--selector=%s' % selector)
  728. if dry_run:
  729. cmd.append('--dry-run')
  730. if pod_selector:
  731. cmd.append('--pod-selector=%s' % pod_selector)
  732. if grace_period:
  733. cmd.append('--grace-period=%s' % int(grace_period))
  734. if force:
  735. cmd.append('--force')
  736. cmd.append('--evacuate')
  737. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  738. def _version(self):
  739. ''' return the openshift version'''
  740. return self.openshift_cmd(['version'], output=True, output_type='raw')
  741. def _import_image(self, url=None, name=None, tag=None):
  742. ''' perform image import '''
  743. cmd = ['import-image']
  744. image = '{0}'.format(name)
  745. if tag:
  746. image += ':{0}'.format(tag)
  747. cmd.append(image)
  748. if url:
  749. cmd.append('--from={0}/{1}'.format(url, image))
  750. cmd.append('-n{0}'.format(self.namespace))
  751. cmd.append('--confirm')
  752. return self.openshift_cmd(cmd)
  753. def _run(self, cmds, input_data):
  754. ''' Actually executes the command. This makes mocking easier. '''
  755. curr_env = os.environ.copy()
  756. curr_env.update({'KUBECONFIG': self.kubeconfig})
  757. proc = subprocess.Popen(cmds,
  758. stdin=subprocess.PIPE,
  759. stdout=subprocess.PIPE,
  760. stderr=subprocess.PIPE,
  761. env=curr_env)
  762. stdout, stderr = proc.communicate(input_data)
  763. return proc.returncode, stdout, stderr
  764. # pylint: disable=too-many-arguments,too-many-branches
  765. def openshift_cmd(self, cmd, oadm=False, output=False, output_type='json', input_data=None):
  766. '''Base command for oc '''
  767. cmds = []
  768. if oadm:
  769. cmds = ['oadm']
  770. else:
  771. cmds = ['oc']
  772. if self.all_namespaces:
  773. cmds.extend(['--all-namespaces'])
  774. elif self.namespace is not None and self.namespace.lower() not in ['none', 'emtpy']: # E501
  775. cmds.extend(['-n', self.namespace])
  776. cmds.extend(cmd)
  777. rval = {}
  778. results = ''
  779. err = None
  780. if self.verbose:
  781. print(' '.join(cmds))
  782. returncode, stdout, stderr = self._run(cmds, input_data)
  783. rval = {"returncode": returncode,
  784. "results": results,
  785. "cmd": ' '.join(cmds)}
  786. if returncode == 0:
  787. if output:
  788. if output_type == 'json':
  789. try:
  790. rval['results'] = json.loads(stdout)
  791. except ValueError as err:
  792. if "No JSON object could be decoded" in err.args:
  793. err = err.args
  794. elif output_type == 'raw':
  795. rval['results'] = stdout
  796. if self.verbose:
  797. print("STDOUT: {0}".format(stdout))
  798. print("STDERR: {0}".format(stderr))
  799. if err:
  800. rval.update({"err": err,
  801. "stderr": stderr,
  802. "stdout": stdout,
  803. "cmd": cmds})
  804. else:
  805. rval.update({"stderr": stderr,
  806. "stdout": stdout,
  807. "results": {}})
  808. return rval
  809. class Utils(object):
  810. ''' utilities for openshiftcli modules '''
  811. @staticmethod
  812. def create_file(rname, data, ftype='yaml'):
  813. ''' create a file in tmp with name and contents'''
  814. path = os.path.join('/tmp', rname)
  815. with open(path, 'w') as fds:
  816. if ftype == 'yaml':
  817. fds.write(yaml.dump(data, Dumper=yaml.RoundTripDumper))
  818. elif ftype == 'json':
  819. fds.write(json.dumps(data))
  820. else:
  821. fds.write(data)
  822. # Register cleanup when module is done
  823. atexit.register(Utils.cleanup, [path])
  824. return path
  825. @staticmethod
  826. def create_files_from_contents(content, content_type=None):
  827. '''Turn an array of dict: filename, content into a files array'''
  828. if not isinstance(content, list):
  829. content = [content]
  830. files = []
  831. for item in content:
  832. path = Utils.create_file(item['path'], item['data'], ftype=content_type)
  833. files.append({'name': os.path.basename(path), 'path': path})
  834. return files
  835. @staticmethod
  836. def cleanup(files):
  837. '''Clean up on exit '''
  838. for sfile in files:
  839. if os.path.exists(sfile):
  840. if os.path.isdir(sfile):
  841. shutil.rmtree(sfile)
  842. elif os.path.isfile(sfile):
  843. os.remove(sfile)
  844. @staticmethod
  845. def exists(results, _name):
  846. ''' Check to see if the results include the name '''
  847. if not results:
  848. return False
  849. if Utils.find_result(results, _name):
  850. return True
  851. return False
  852. @staticmethod
  853. def find_result(results, _name):
  854. ''' Find the specified result by name'''
  855. rval = None
  856. for result in results:
  857. if 'metadata' in result and result['metadata']['name'] == _name:
  858. rval = result
  859. break
  860. return rval
  861. @staticmethod
  862. def get_resource_file(sfile, sfile_type='yaml'):
  863. ''' return the service file '''
  864. contents = None
  865. with open(sfile) as sfd:
  866. contents = sfd.read()
  867. if sfile_type == 'yaml':
  868. contents = yaml.load(contents, yaml.RoundTripLoader)
  869. elif sfile_type == 'json':
  870. contents = json.loads(contents)
  871. return contents
  872. @staticmethod
  873. def filter_versions(stdout):
  874. ''' filter the oc version output '''
  875. version_dict = {}
  876. version_search = ['oc', 'openshift', 'kubernetes']
  877. for line in stdout.strip().split('\n'):
  878. for term in version_search:
  879. if not line:
  880. continue
  881. if line.startswith(term):
  882. version_dict[term] = line.split()[-1]
  883. # horrible hack to get openshift version in Openshift 3.2
  884. # By default "oc version in 3.2 does not return an "openshift" version
  885. if "openshift" not in version_dict:
  886. version_dict["openshift"] = version_dict["oc"]
  887. return version_dict
  888. @staticmethod
  889. def add_custom_versions(versions):
  890. ''' create custom versions strings '''
  891. versions_dict = {}
  892. for tech, version in versions.items():
  893. # clean up "-" from version
  894. if "-" in version:
  895. version = version.split("-")[0]
  896. if version.startswith('v'):
  897. versions_dict[tech + '_numeric'] = version[1:].split('+')[0]
  898. # "v3.3.0.33" is what we have, we want "3.3"
  899. versions_dict[tech + '_short'] = version[1:4]
  900. return versions_dict
  901. @staticmethod
  902. def openshift_installed():
  903. ''' check if openshift is installed '''
  904. import yum
  905. yum_base = yum.YumBase()
  906. if yum_base.rpmdb.searchNevra(name='atomic-openshift'):
  907. return True
  908. return False
  909. # Disabling too-many-branches. This is a yaml dictionary comparison function
  910. # pylint: disable=too-many-branches,too-many-return-statements,too-many-statements
  911. @staticmethod
  912. def check_def_equal(user_def, result_def, skip_keys=None, debug=False):
  913. ''' Given a user defined definition, compare it with the results given back by our query. '''
  914. # Currently these values are autogenerated and we do not need to check them
  915. skip = ['metadata', 'status']
  916. if skip_keys:
  917. skip.extend(skip_keys)
  918. for key, value in result_def.items():
  919. if key in skip:
  920. continue
  921. # Both are lists
  922. if isinstance(value, list):
  923. if key not in user_def:
  924. if debug:
  925. print('User data does not have key [%s]' % key)
  926. print('User data: %s' % user_def)
  927. return False
  928. if not isinstance(user_def[key], list):
  929. if debug:
  930. print('user_def[key] is not a list key=[%s] user_def[key]=%s' % (key, user_def[key]))
  931. return False
  932. if len(user_def[key]) != len(value):
  933. if debug:
  934. print("List lengths are not equal.")
  935. print("key=[%s]: user_def[%s] != value[%s]" % (key, len(user_def[key]), len(value)))
  936. print("user_def: %s" % user_def[key])
  937. print("value: %s" % value)
  938. return False
  939. for values in zip(user_def[key], value):
  940. if isinstance(values[0], dict) and isinstance(values[1], dict):
  941. if debug:
  942. print('sending list - list')
  943. print(type(values[0]))
  944. print(type(values[1]))
  945. result = Utils.check_def_equal(values[0], values[1], skip_keys=skip_keys, debug=debug)
  946. if not result:
  947. print('list compare returned false')
  948. return False
  949. elif value != user_def[key]:
  950. if debug:
  951. print('value should be identical')
  952. print(value)
  953. print(user_def[key])
  954. return False
  955. # recurse on a dictionary
  956. elif isinstance(value, dict):
  957. if key not in user_def:
  958. if debug:
  959. print("user_def does not have key [%s]" % key)
  960. return False
  961. if not isinstance(user_def[key], dict):
  962. if debug:
  963. print("dict returned false: not instance of dict")
  964. return False
  965. # before passing ensure keys match
  966. api_values = set(value.keys()) - set(skip)
  967. user_values = set(user_def[key].keys()) - set(skip)
  968. if api_values != user_values:
  969. if debug:
  970. print("keys are not equal in dict")
  971. print(api_values)
  972. print(user_values)
  973. return False
  974. result = Utils.check_def_equal(user_def[key], value, skip_keys=skip_keys, debug=debug)
  975. if not result:
  976. if debug:
  977. print("dict returned false")
  978. print(result)
  979. return False
  980. # Verify each key, value pair is the same
  981. else:
  982. if key not in user_def or value != user_def[key]:
  983. if debug:
  984. print("value not equal; user_def does not have key")
  985. print(key)
  986. print(value)
  987. if key in user_def:
  988. print(user_def[key])
  989. return False
  990. if debug:
  991. print('returning true')
  992. return True
  993. class OpenShiftCLIConfig(object):
  994. '''Generic Config'''
  995. def __init__(self, rname, namespace, kubeconfig, options):
  996. self.kubeconfig = kubeconfig
  997. self.name = rname
  998. self.namespace = namespace
  999. self._options = options
  1000. @property
  1001. def config_options(self):
  1002. ''' return config options '''
  1003. return self._options
  1004. def to_option_list(self):
  1005. '''return all options as a string'''
  1006. return self.stringify()
  1007. def stringify(self):
  1008. ''' return the options hash as cli params in a string '''
  1009. rval = []
  1010. for key, data in self.config_options.items():
  1011. if data['include'] \
  1012. and (data['value'] or isinstance(data['value'], int)):
  1013. rval.append('--%s=%s' % (key.replace('_', '-'), data['value']))
  1014. return rval
  1015. # -*- -*- -*- End included fragment: lib/base.py -*- -*- -*-
  1016. # -*- -*- -*- Begin included fragment: class/oc_obj.py -*- -*- -*-
  1017. # pylint: disable=too-many-instance-attributes
  1018. class OCObject(OpenShiftCLI):
  1019. ''' Class to wrap the oc command line tools '''
  1020. # pylint allows 5. we need 6
  1021. # pylint: disable=too-many-arguments
  1022. def __init__(self,
  1023. kind,
  1024. namespace,
  1025. rname=None,
  1026. selector=None,
  1027. kubeconfig='/etc/origin/master/admin.kubeconfig',
  1028. verbose=False,
  1029. all_namespaces=False):
  1030. ''' Constructor for OpenshiftOC '''
  1031. super(OCObject, self).__init__(namespace, kubeconfig,
  1032. all_namespaces=all_namespaces)
  1033. self.kind = kind
  1034. self.namespace = namespace
  1035. self.name = rname
  1036. self.selector = selector
  1037. self.kubeconfig = kubeconfig
  1038. self.verbose = verbose
  1039. def get(self):
  1040. '''return a kind by name '''
  1041. results = self._get(self.kind, rname=self.name, selector=self.selector)
  1042. if results['returncode'] != 0 and 'stderr' in results and \
  1043. '\"%s\" not found' % self.name in results['stderr']:
  1044. results['returncode'] = 0
  1045. return results
  1046. def delete(self):
  1047. '''return all pods '''
  1048. return self._delete(self.kind, self.name)
  1049. def create(self, files=None, content=None):
  1050. '''
  1051. Create a config
  1052. NOTE: This creates the first file OR the first conent.
  1053. TODO: Handle all files and content passed in
  1054. '''
  1055. if files:
  1056. return self._create(files[0])
  1057. content['data'] = yaml.dump(content['data'])
  1058. content_file = Utils.create_files_from_contents(content)[0]
  1059. return self._create(content_file['path'])
  1060. # pylint: disable=too-many-function-args
  1061. def update(self, files=None, content=None, force=False):
  1062. '''update a current openshift object
  1063. This receives a list of file names or content
  1064. and takes the first and calls replace.
  1065. TODO: take an entire list
  1066. '''
  1067. if files:
  1068. return self._replace(files[0], force)
  1069. if content and 'data' in content:
  1070. content = content['data']
  1071. return self.update_content(content, force)
  1072. def update_content(self, content, force=False):
  1073. '''update an object through using the content param'''
  1074. return self._replace_content(self.kind, self.name, content, force=force)
  1075. def needs_update(self, files=None, content=None, content_type='yaml'):
  1076. ''' check to see if we need to update '''
  1077. objects = self.get()
  1078. if objects['returncode'] != 0:
  1079. return objects
  1080. # pylint: disable=no-member
  1081. data = None
  1082. if files:
  1083. data = Utils.get_resource_file(files[0], content_type)
  1084. elif content and 'data' in content:
  1085. data = content['data']
  1086. else:
  1087. data = content
  1088. # if equal then no need. So not equal is True
  1089. return not Utils.check_def_equal(data, objects['results'][0], skip_keys=None, debug=False)
  1090. # pylint: disable=too-many-return-statements,too-many-branches
  1091. @staticmethod
  1092. def run_ansible(params, check_mode=False):
  1093. '''perform the ansible idempotent code'''
  1094. ocobj = OCObject(params['kind'],
  1095. params['namespace'],
  1096. params['name'],
  1097. params['selector'],
  1098. kubeconfig=params['kubeconfig'],
  1099. verbose=params['debug'],
  1100. all_namespaces=params['all_namespaces'])
  1101. state = params['state']
  1102. api_rval = ocobj.get()
  1103. #####
  1104. # Get
  1105. #####
  1106. if state == 'list':
  1107. return {'changed': False, 'results': api_rval, 'state': 'list'}
  1108. if not params['name']:
  1109. return {'failed': True, 'msg': 'Please specify a name when state is absent|present.'} # noqa: E501
  1110. ########
  1111. # Delete
  1112. ########
  1113. if state == 'absent':
  1114. if not Utils.exists(api_rval['results'], params['name']):
  1115. return {'changed': False, 'state': 'absent'}
  1116. if check_mode:
  1117. return {'changed': True, 'msg': 'CHECK_MODE: Would have performed a delete'}
  1118. api_rval = ocobj.delete()
  1119. return {'changed': True, 'results': api_rval, 'state': 'absent'}
  1120. if state == 'present':
  1121. ########
  1122. # Create
  1123. ########
  1124. if not Utils.exists(api_rval['results'], params['name']):
  1125. if check_mode:
  1126. return {'changed': True, 'msg': 'CHECK_MODE: Would have performed a create'}
  1127. # Create it here
  1128. api_rval = ocobj.create(params['files'], params['content'])
  1129. if api_rval['returncode'] != 0:
  1130. return {'failed': True, 'msg': api_rval}
  1131. # return the created object
  1132. api_rval = ocobj.get()
  1133. if api_rval['returncode'] != 0:
  1134. return {'failed': True, 'msg': api_rval}
  1135. # Remove files
  1136. if params['files'] and params['delete_after']:
  1137. Utils.cleanup(params['files'])
  1138. return {'changed': True, 'results': api_rval, 'state': "present"}
  1139. ########
  1140. # Update
  1141. ########
  1142. # if a file path is passed, use it.
  1143. update = ocobj.needs_update(params['files'], params['content'])
  1144. if not isinstance(update, bool):
  1145. return {'failed': True, 'msg': update}
  1146. # No changes
  1147. if not update:
  1148. if params['files'] and params['delete_after']:
  1149. Utils.cleanup(params['files'])
  1150. return {'changed': False, 'results': api_rval['results'][0], 'state': "present"}
  1151. if check_mode:
  1152. return {'changed': True, 'msg': 'CHECK_MODE: Would have performed an update.'}
  1153. api_rval = ocobj.update(params['files'],
  1154. params['content'],
  1155. params['force'])
  1156. if api_rval['returncode'] != 0:
  1157. return {'failed': True, 'msg': api_rval}
  1158. # return the created object
  1159. api_rval = ocobj.get()
  1160. if api_rval['returncode'] != 0:
  1161. return {'failed': True, 'msg': api_rval}
  1162. return {'changed': True, 'results': api_rval, 'state': "present"}
  1163. # -*- -*- -*- End included fragment: class/oc_obj.py -*- -*- -*-
  1164. # -*- -*- -*- Begin included fragment: ansible/oc_obj.py -*- -*- -*-
  1165. # pylint: disable=too-many-branches
  1166. def main():
  1167. '''
  1168. ansible oc module for services
  1169. '''
  1170. module = AnsibleModule(
  1171. argument_spec=dict(
  1172. kubeconfig=dict(default='/etc/origin/master/admin.kubeconfig', type='str'),
  1173. state=dict(default='present', type='str',
  1174. choices=['present', 'absent', 'list']),
  1175. debug=dict(default=False, type='bool'),
  1176. namespace=dict(default='default', type='str'),
  1177. all_namespaces=dict(defaul=False, type='bool'),
  1178. name=dict(default=None, type='str'),
  1179. files=dict(default=None, type='list'),
  1180. kind=dict(required=True, type='str'),
  1181. delete_after=dict(default=False, type='bool'),
  1182. content=dict(default=None, type='dict'),
  1183. force=dict(default=False, type='bool'),
  1184. selector=dict(default=None, type='str'),
  1185. ),
  1186. mutually_exclusive=[["content", "files"]],
  1187. supports_check_mode=True,
  1188. )
  1189. rval = OCObject.run_ansible(module.params, module.check_mode)
  1190. if 'failed' in rval:
  1191. module.fail_json(**rval)
  1192. module.exit_json(**rval)
  1193. if __name__ == '__main__':
  1194. main()
  1195. # -*- -*- -*- End included fragment: ansible/oc_obj.py -*- -*- -*-