oc_obj.py 49 KB

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