oc_process.py 52 KB

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