oc_obj.py 48 KB

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