oc_obj.py 51 KB

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