oc_obj.py 50 KB

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