oc_process.py 50 KB

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