oc_obj.py 50 KB

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