oc_edit.py 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377
  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. '''
  28. OpenShiftCLI class that wraps the oc commands in a subprocess
  29. '''
  30. # pylint: disable=too-many-lines
  31. from __future__ import print_function
  32. import atexit
  33. import json
  34. import os
  35. import re
  36. import shutil
  37. import subprocess
  38. # pylint: disable=import-error
  39. import ruamel.yaml as yaml
  40. from ansible.module_utils.basic import AnsibleModule
  41. DOCUMENTATION = '''
  42. ---
  43. module: oc_edit
  44. short_description: Modify, and idempotently manage openshift objects.
  45. description:
  46. - Modify openshift objects programmatically.
  47. options:
  48. state:
  49. description:
  50. - Currently present is only supported state.
  51. required: true
  52. default: present
  53. choices: ["present"]
  54. aliases: []
  55. kubeconfig:
  56. description:
  57. - The path for the kubeconfig file to use for authentication
  58. required: false
  59. default: /etc/origin/master/admin.kubeconfig
  60. aliases: []
  61. debug:
  62. description:
  63. - Turn on debug output.
  64. required: false
  65. default: False
  66. aliases: []
  67. name:
  68. description:
  69. - Name of the object that is being queried.
  70. required: false
  71. default: None
  72. aliases: []
  73. namespace:
  74. description:
  75. - The namespace where the object lives.
  76. required: false
  77. default: str
  78. aliases: []
  79. kind:
  80. description:
  81. - The kind attribute of the object.
  82. required: True
  83. default: None
  84. choices:
  85. - bc
  86. - buildconfig
  87. - configmaps
  88. - dc
  89. - deploymentconfig
  90. - imagestream
  91. - imagestreamtag
  92. - is
  93. - istag
  94. - namespace
  95. - project
  96. - projects
  97. - node
  98. - ns
  99. - persistentvolume
  100. - pv
  101. - rc
  102. - replicationcontroller
  103. - routes
  104. - scc
  105. - secret
  106. - securitycontextconstraints
  107. - service
  108. - svc
  109. aliases: []
  110. file_name:
  111. description:
  112. - The file name in which to edit
  113. required: false
  114. default: None
  115. aliases: []
  116. file_format:
  117. description:
  118. - The format of the file being edited.
  119. required: false
  120. default: yaml
  121. aliases: []
  122. content:
  123. description:
  124. - Content of the file
  125. required: false
  126. default: None
  127. aliases: []
  128. force:
  129. description:
  130. - Whether or not to force the operation
  131. required: false
  132. default: None
  133. aliases: []
  134. separator:
  135. description:
  136. - The separator format for the edit.
  137. required: false
  138. default: '.'
  139. aliases: []
  140. author:
  141. - "Kenny Woodson <kwoodson@redhat.com>"
  142. extends_documentation_fragment: []
  143. '''
  144. EXAMPLES = '''
  145. oc_edit:
  146. kind: rc
  147. name: hawkular-cassandra-rc
  148. namespace: openshift-infra
  149. content:
  150. spec.template.spec.containers[0].resources.limits.memory: 512
  151. spec.template.spec.containers[0].resources.requests.memory: 256
  152. '''
  153. # noqa: E301,E302
  154. class YeditException(Exception):
  155. ''' Exception class for Yedit '''
  156. pass
  157. # pylint: disable=too-many-public-methods
  158. class Yedit(object):
  159. ''' Class to modify yaml files '''
  160. re_valid_key = r"(((\[-?\d+\])|([0-9a-zA-Z%s/_-]+)).?)+$"
  161. re_key = r"(?:\[(-?\d+)\])|([0-9a-zA-Z%s/_-]+)"
  162. com_sep = set(['.', '#', '|', ':'])
  163. # pylint: disable=too-many-arguments
  164. def __init__(self,
  165. filename=None,
  166. content=None,
  167. content_type='yaml',
  168. separator='.',
  169. backup=False):
  170. self.content = content
  171. self._separator = separator
  172. self.filename = filename
  173. self.__yaml_dict = content
  174. self.content_type = content_type
  175. self.backup = backup
  176. self.load(content_type=self.content_type)
  177. if self.__yaml_dict is None:
  178. self.__yaml_dict = {}
  179. @property
  180. def separator(self):
  181. ''' getter method for yaml_dict '''
  182. return self._separator
  183. @separator.setter
  184. def separator(self):
  185. ''' getter method for yaml_dict '''
  186. return self._separator
  187. @property
  188. def yaml_dict(self):
  189. ''' getter method for yaml_dict '''
  190. return self.__yaml_dict
  191. @yaml_dict.setter
  192. def yaml_dict(self, value):
  193. ''' setter method for yaml_dict '''
  194. self.__yaml_dict = value
  195. @staticmethod
  196. def parse_key(key, sep='.'):
  197. '''parse the key allowing the appropriate separator'''
  198. common_separators = list(Yedit.com_sep - set([sep]))
  199. return re.findall(Yedit.re_key % ''.join(common_separators), key)
  200. @staticmethod
  201. def valid_key(key, sep='.'):
  202. '''validate the incoming key'''
  203. common_separators = list(Yedit.com_sep - set([sep]))
  204. if not re.match(Yedit.re_valid_key % ''.join(common_separators), key):
  205. return False
  206. return True
  207. @staticmethod
  208. def remove_entry(data, key, sep='.'):
  209. ''' remove data at location key '''
  210. if key == '' and isinstance(data, dict):
  211. data.clear()
  212. return True
  213. elif key == '' and isinstance(data, list):
  214. del data[:]
  215. return True
  216. if not (key and Yedit.valid_key(key, sep)) and \
  217. isinstance(data, (list, dict)):
  218. return None
  219. key_indexes = Yedit.parse_key(key, sep)
  220. for arr_ind, dict_key in key_indexes[:-1]:
  221. if dict_key and isinstance(data, dict):
  222. data = data.get(dict_key, None)
  223. elif (arr_ind and isinstance(data, list) and
  224. int(arr_ind) <= len(data) - 1):
  225. data = data[int(arr_ind)]
  226. else:
  227. return None
  228. # process last index for remove
  229. # expected list entry
  230. if key_indexes[-1][0]:
  231. if isinstance(data, list) and int(key_indexes[-1][0]) <= len(data) - 1: # noqa: E501
  232. del data[int(key_indexes[-1][0])]
  233. return True
  234. # expected dict entry
  235. elif key_indexes[-1][1]:
  236. if isinstance(data, dict):
  237. del data[key_indexes[-1][1]]
  238. return True
  239. @staticmethod
  240. def add_entry(data, key, item=None, sep='.'):
  241. ''' Get an item from a dictionary with key notation a.b.c
  242. d = {'a': {'b': 'c'}}}
  243. key = a#b
  244. return c
  245. '''
  246. if key == '':
  247. pass
  248. elif (not (key and Yedit.valid_key(key, sep)) and
  249. isinstance(data, (list, dict))):
  250. return None
  251. key_indexes = Yedit.parse_key(key, sep)
  252. for arr_ind, dict_key in key_indexes[:-1]:
  253. if dict_key:
  254. if isinstance(data, dict) and dict_key in data and data[dict_key]: # noqa: E501
  255. data = data[dict_key]
  256. continue
  257. elif data and not isinstance(data, dict):
  258. return None
  259. data[dict_key] = {}
  260. data = data[dict_key]
  261. elif (arr_ind and isinstance(data, list) and
  262. int(arr_ind) <= len(data) - 1):
  263. data = data[int(arr_ind)]
  264. else:
  265. return None
  266. if key == '':
  267. data = item
  268. # process last index for add
  269. # expected list entry
  270. elif key_indexes[-1][0] and isinstance(data, list) and int(key_indexes[-1][0]) <= len(data) - 1: # noqa: E501
  271. data[int(key_indexes[-1][0])] = item
  272. # expected dict entry
  273. elif key_indexes[-1][1] and isinstance(data, dict):
  274. data[key_indexes[-1][1]] = item
  275. return data
  276. @staticmethod
  277. def get_entry(data, key, sep='.'):
  278. ''' Get an item from a dictionary with key notation a.b.c
  279. d = {'a': {'b': 'c'}}}
  280. key = a.b
  281. return c
  282. '''
  283. if key == '':
  284. pass
  285. elif (not (key and Yedit.valid_key(key, sep)) and
  286. isinstance(data, (list, dict))):
  287. return None
  288. key_indexes = Yedit.parse_key(key, sep)
  289. for arr_ind, dict_key in key_indexes:
  290. if dict_key and isinstance(data, dict):
  291. data = data.get(dict_key, None)
  292. elif (arr_ind and isinstance(data, list) and
  293. int(arr_ind) <= len(data) - 1):
  294. data = data[int(arr_ind)]
  295. else:
  296. return None
  297. return data
  298. def write(self):
  299. ''' write to file '''
  300. if not self.filename:
  301. raise YeditException('Please specify a filename.')
  302. if self.backup and self.file_exists():
  303. shutil.copy(self.filename, self.filename + '.orig')
  304. tmp_filename = self.filename + '.yedit'
  305. with open(tmp_filename, 'w') as yfd:
  306. # pylint: disable=no-member
  307. if hasattr(self.yaml_dict, 'fa'):
  308. self.yaml_dict.fa.set_block_style()
  309. yfd.write(yaml.dump(self.yaml_dict, Dumper=yaml.RoundTripDumper))
  310. os.rename(tmp_filename, self.filename)
  311. return (True, self.yaml_dict)
  312. def read(self):
  313. ''' read from file '''
  314. # check if it exists
  315. if self.filename is None or not self.file_exists():
  316. return None
  317. contents = None
  318. with open(self.filename) as yfd:
  319. contents = yfd.read()
  320. return contents
  321. def file_exists(self):
  322. ''' return whether file exists '''
  323. if os.path.exists(self.filename):
  324. return True
  325. return False
  326. def load(self, content_type='yaml'):
  327. ''' return yaml file '''
  328. contents = self.read()
  329. if not contents and not self.content:
  330. return None
  331. if self.content:
  332. if isinstance(self.content, dict):
  333. self.yaml_dict = self.content
  334. return self.yaml_dict
  335. elif isinstance(self.content, str):
  336. contents = self.content
  337. # check if it is yaml
  338. try:
  339. if content_type == 'yaml' and contents:
  340. self.yaml_dict = yaml.load(contents, yaml.RoundTripLoader)
  341. # pylint: disable=no-member
  342. if hasattr(self.yaml_dict, 'fa'):
  343. self.yaml_dict.fa.set_block_style()
  344. elif content_type == 'json' and contents:
  345. self.yaml_dict = json.loads(contents)
  346. except yaml.YAMLError as err:
  347. # Error loading yaml or json
  348. raise YeditException('Problem with loading yaml file. %s' % err)
  349. return self.yaml_dict
  350. def get(self, key):
  351. ''' get a specified key'''
  352. try:
  353. entry = Yedit.get_entry(self.yaml_dict, key, self.separator)
  354. except KeyError:
  355. entry = None
  356. return entry
  357. def pop(self, path, key_or_item):
  358. ''' remove a key, value pair from a dict or an item for a list'''
  359. try:
  360. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  361. except KeyError:
  362. entry = None
  363. if entry is None:
  364. return (False, self.yaml_dict)
  365. if isinstance(entry, dict):
  366. # pylint: disable=no-member,maybe-no-member
  367. if key_or_item in entry:
  368. entry.pop(key_or_item)
  369. return (True, self.yaml_dict)
  370. return (False, self.yaml_dict)
  371. elif isinstance(entry, list):
  372. # pylint: disable=no-member,maybe-no-member
  373. ind = None
  374. try:
  375. ind = entry.index(key_or_item)
  376. except ValueError:
  377. return (False, self.yaml_dict)
  378. entry.pop(ind)
  379. return (True, self.yaml_dict)
  380. return (False, self.yaml_dict)
  381. def delete(self, path):
  382. ''' remove path from a dict'''
  383. try:
  384. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  385. except KeyError:
  386. entry = None
  387. if entry is None:
  388. return (False, self.yaml_dict)
  389. result = Yedit.remove_entry(self.yaml_dict, path, self.separator)
  390. if not result:
  391. return (False, self.yaml_dict)
  392. return (True, self.yaml_dict)
  393. def exists(self, path, value):
  394. ''' check if value exists at path'''
  395. try:
  396. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  397. except KeyError:
  398. entry = None
  399. if isinstance(entry, list):
  400. if value in entry:
  401. return True
  402. return False
  403. elif isinstance(entry, dict):
  404. if isinstance(value, dict):
  405. rval = False
  406. for key, val in value.items():
  407. if entry[key] != val:
  408. rval = False
  409. break
  410. else:
  411. rval = True
  412. return rval
  413. return value in entry
  414. return entry == value
  415. def append(self, path, value):
  416. '''append value to a list'''
  417. try:
  418. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  419. except KeyError:
  420. entry = None
  421. if entry is None:
  422. self.put(path, [])
  423. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  424. if not isinstance(entry, list):
  425. return (False, self.yaml_dict)
  426. # pylint: disable=no-member,maybe-no-member
  427. entry.append(value)
  428. return (True, self.yaml_dict)
  429. # pylint: disable=too-many-arguments
  430. def update(self, path, value, index=None, curr_value=None):
  431. ''' put path, value into a dict '''
  432. try:
  433. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  434. except KeyError:
  435. entry = None
  436. if isinstance(entry, dict):
  437. # pylint: disable=no-member,maybe-no-member
  438. if not isinstance(value, dict):
  439. raise YeditException('Cannot replace key, value entry in ' +
  440. 'dict with non-dict type. value=[%s] [%s]' % (value, type(value))) # noqa: E501
  441. entry.update(value)
  442. return (True, self.yaml_dict)
  443. elif isinstance(entry, list):
  444. # pylint: disable=no-member,maybe-no-member
  445. ind = None
  446. if curr_value:
  447. try:
  448. ind = entry.index(curr_value)
  449. except ValueError:
  450. return (False, self.yaml_dict)
  451. elif index is not None:
  452. ind = index
  453. if ind is not None and entry[ind] != value:
  454. entry[ind] = value
  455. return (True, self.yaml_dict)
  456. # see if it exists in the list
  457. try:
  458. ind = entry.index(value)
  459. except ValueError:
  460. # doesn't exist, append it
  461. entry.append(value)
  462. return (True, self.yaml_dict)
  463. # already exists, return
  464. if ind is not None:
  465. return (False, self.yaml_dict)
  466. return (False, self.yaml_dict)
  467. def put(self, path, value):
  468. ''' put path, value into a dict '''
  469. try:
  470. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  471. except KeyError:
  472. entry = None
  473. if entry == value:
  474. return (False, self.yaml_dict)
  475. # deepcopy didn't work
  476. tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict,
  477. default_flow_style=False),
  478. yaml.RoundTripLoader)
  479. # pylint: disable=no-member
  480. if hasattr(self.yaml_dict, 'fa'):
  481. tmp_copy.fa.set_block_style()
  482. result = Yedit.add_entry(tmp_copy, path, value, self.separator)
  483. if not result:
  484. return (False, self.yaml_dict)
  485. self.yaml_dict = tmp_copy
  486. return (True, self.yaml_dict)
  487. def create(self, path, value):
  488. ''' create a yaml file '''
  489. if not self.file_exists():
  490. # deepcopy didn't work
  491. tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict, default_flow_style=False), # noqa: E501
  492. yaml.RoundTripLoader)
  493. # pylint: disable=no-member
  494. if hasattr(self.yaml_dict, 'fa'):
  495. tmp_copy.fa.set_block_style()
  496. result = Yedit.add_entry(tmp_copy, path, value, self.separator)
  497. if result:
  498. self.yaml_dict = tmp_copy
  499. return (True, self.yaml_dict)
  500. return (False, self.yaml_dict)
  501. @staticmethod
  502. def get_curr_value(invalue, val_type):
  503. '''return the current value'''
  504. if invalue is None:
  505. return None
  506. curr_value = invalue
  507. if val_type == 'yaml':
  508. curr_value = yaml.load(invalue)
  509. elif val_type == 'json':
  510. curr_value = json.loads(invalue)
  511. return curr_value
  512. @staticmethod
  513. def parse_value(inc_value, vtype=''):
  514. '''determine value type passed'''
  515. true_bools = ['y', 'Y', 'yes', 'Yes', 'YES', 'true', 'True', 'TRUE',
  516. 'on', 'On', 'ON', ]
  517. false_bools = ['n', 'N', 'no', 'No', 'NO', 'false', 'False', 'FALSE',
  518. 'off', 'Off', 'OFF']
  519. # It came in as a string but you didn't specify value_type as string
  520. # we will convert to bool if it matches any of the above cases
  521. if isinstance(inc_value, str) and 'bool' in vtype:
  522. if inc_value not in true_bools and inc_value not in false_bools:
  523. raise YeditException('Not a boolean type. str=[%s] vtype=[%s]'
  524. % (inc_value, vtype))
  525. elif isinstance(inc_value, bool) and 'str' in vtype:
  526. inc_value = str(inc_value)
  527. # If vtype is not str then go ahead and attempt to yaml load it.
  528. if isinstance(inc_value, str) and 'str' not in vtype:
  529. try:
  530. inc_value = yaml.load(inc_value)
  531. except Exception:
  532. raise YeditException('Could not determine type of incoming ' +
  533. 'value. value=[%s] vtype=[%s]'
  534. % (type(inc_value), vtype))
  535. return inc_value
  536. # pylint: disable=too-many-return-statements,too-many-branches
  537. @staticmethod
  538. def run_ansible(module):
  539. '''perform the idempotent crud operations'''
  540. yamlfile = Yedit(filename=module.params['src'],
  541. backup=module.params['backup'],
  542. separator=module.params['separator'])
  543. if module.params['src']:
  544. rval = yamlfile.load()
  545. if yamlfile.yaml_dict is None and \
  546. module.params['state'] != 'present':
  547. return {'failed': True,
  548. 'msg': 'Error opening file [%s]. Verify that the ' +
  549. 'file exists, that it is has correct' +
  550. ' permissions, and is valid yaml.'}
  551. if module.params['state'] == 'list':
  552. if module.params['content']:
  553. content = Yedit.parse_value(module.params['content'],
  554. module.params['content_type'])
  555. yamlfile.yaml_dict = content
  556. if module.params['key']:
  557. rval = yamlfile.get(module.params['key']) or {}
  558. return {'changed': False, 'result': rval, 'state': "list"}
  559. elif module.params['state'] == 'absent':
  560. if module.params['content']:
  561. content = Yedit.parse_value(module.params['content'],
  562. module.params['content_type'])
  563. yamlfile.yaml_dict = content
  564. if module.params['update']:
  565. rval = yamlfile.pop(module.params['key'],
  566. module.params['value'])
  567. else:
  568. rval = yamlfile.delete(module.params['key'])
  569. if rval[0] and module.params['src']:
  570. yamlfile.write()
  571. return {'changed': rval[0], 'result': rval[1], 'state': "absent"}
  572. elif module.params['state'] == 'present':
  573. # check if content is different than what is in the file
  574. if module.params['content']:
  575. content = Yedit.parse_value(module.params['content'],
  576. module.params['content_type'])
  577. # We had no edits to make and the contents are the same
  578. if yamlfile.yaml_dict == content and \
  579. module.params['value'] is None:
  580. return {'changed': False,
  581. 'result': yamlfile.yaml_dict,
  582. 'state': "present"}
  583. yamlfile.yaml_dict = content
  584. # we were passed a value; parse it
  585. if module.params['value']:
  586. value = Yedit.parse_value(module.params['value'],
  587. module.params['value_type'])
  588. key = module.params['key']
  589. if module.params['update']:
  590. # pylint: disable=line-too-long
  591. curr_value = Yedit.get_curr_value(Yedit.parse_value(module.params['curr_value']), # noqa: E501
  592. module.params['curr_value_format']) # noqa: E501
  593. rval = yamlfile.update(key, value, module.params['index'], curr_value) # noqa: E501
  594. elif module.params['append']:
  595. rval = yamlfile.append(key, value)
  596. else:
  597. rval = yamlfile.put(key, value)
  598. if rval[0] and module.params['src']:
  599. yamlfile.write()
  600. return {'changed': rval[0],
  601. 'result': rval[1], 'state': "present"}
  602. # no edits to make
  603. if module.params['src']:
  604. # pylint: disable=redefined-variable-type
  605. rval = yamlfile.write()
  606. return {'changed': rval[0],
  607. 'result': rval[1],
  608. 'state': "present"}
  609. return {'failed': True, 'msg': 'Unkown state passed'}
  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 = 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 = '/tmp/%s' % 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 = '/tmp/%s' % 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 = '/tmp/%s' % 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. cmd.extend(['-o', 'json'])
  697. if rname:
  698. cmd.append(rname)
  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. # pylint: disable=too-many-arguments,too-many-branches
  764. def openshift_cmd(self, cmd, oadm=False, output=False, output_type='json', input_data=None):
  765. '''Base command for oc '''
  766. cmds = []
  767. if oadm:
  768. cmds = ['/usr/bin/oadm']
  769. else:
  770. cmds = ['/usr/bin/oc']
  771. if self.all_namespaces:
  772. cmds.extend(['--all-namespaces'])
  773. elif self.namespace:
  774. cmds.extend(['-n', self.namespace])
  775. cmds.extend(cmd)
  776. rval = {}
  777. results = ''
  778. err = None
  779. if self.verbose:
  780. print(' '.join(cmds))
  781. proc = subprocess.Popen(cmds,
  782. stdin=subprocess.PIPE,
  783. stdout=subprocess.PIPE,
  784. stderr=subprocess.PIPE,
  785. env={'KUBECONFIG': self.kubeconfig})
  786. stdout, stderr = proc.communicate(input_data)
  787. rval = {"returncode": proc.returncode,
  788. "results": results,
  789. "cmd": ' '.join(cmds)}
  790. if proc.returncode == 0:
  791. if output:
  792. if output_type == 'json':
  793. try:
  794. rval['results'] = json.loads(stdout)
  795. except ValueError as err:
  796. if "No JSON object could be decoded" in err.args:
  797. err = err.args
  798. elif output_type == 'raw':
  799. rval['results'] = stdout
  800. if self.verbose:
  801. print("STDOUT: {0}".format(stdout))
  802. print("STDERR: {0}".format(stderr))
  803. if err:
  804. rval.update({"err": err,
  805. "stderr": stderr,
  806. "stdout": stdout,
  807. "cmd": cmds})
  808. else:
  809. rval.update({"stderr": stderr,
  810. "stdout": stdout,
  811. "results": {}})
  812. return rval
  813. class Utils(object):
  814. ''' utilities for openshiftcli modules '''
  815. @staticmethod
  816. def create_file(rname, data, ftype='yaml'):
  817. ''' create a file in tmp with name and contents'''
  818. path = os.path.join('/tmp', rname)
  819. with open(path, 'w') as fds:
  820. if ftype == 'yaml':
  821. fds.write(yaml.dump(data, Dumper=yaml.RoundTripDumper))
  822. elif ftype == 'json':
  823. fds.write(json.dumps(data))
  824. else:
  825. fds.write(data)
  826. # Register cleanup when module is done
  827. atexit.register(Utils.cleanup, [path])
  828. return path
  829. @staticmethod
  830. def create_files_from_contents(content, content_type=None):
  831. '''Turn an array of dict: filename, content into a files array'''
  832. if not isinstance(content, list):
  833. content = [content]
  834. files = []
  835. for item in content:
  836. path = Utils.create_file(item['path'], item['data'], ftype=content_type)
  837. files.append({'name': os.path.basename(path), 'path': path})
  838. return files
  839. @staticmethod
  840. def cleanup(files):
  841. '''Clean up on exit '''
  842. for sfile in files:
  843. if os.path.exists(sfile):
  844. if os.path.isdir(sfile):
  845. shutil.rmtree(sfile)
  846. elif os.path.isfile(sfile):
  847. os.remove(sfile)
  848. @staticmethod
  849. def exists(results, _name):
  850. ''' Check to see if the results include the name '''
  851. if not results:
  852. return False
  853. if Utils.find_result(results, _name):
  854. return True
  855. return False
  856. @staticmethod
  857. def find_result(results, _name):
  858. ''' Find the specified result by name'''
  859. rval = None
  860. for result in results:
  861. if 'metadata' in result and result['metadata']['name'] == _name:
  862. rval = result
  863. break
  864. return rval
  865. @staticmethod
  866. def get_resource_file(sfile, sfile_type='yaml'):
  867. ''' return the service file '''
  868. contents = None
  869. with open(sfile) as sfd:
  870. contents = sfd.read()
  871. if sfile_type == 'yaml':
  872. contents = yaml.load(contents, yaml.RoundTripLoader)
  873. elif sfile_type == 'json':
  874. contents = json.loads(contents)
  875. return contents
  876. @staticmethod
  877. def filter_versions(stdout):
  878. ''' filter the oc version output '''
  879. version_dict = {}
  880. version_search = ['oc', 'openshift', 'kubernetes']
  881. for line in stdout.strip().split('\n'):
  882. for term in version_search:
  883. if not line:
  884. continue
  885. if line.startswith(term):
  886. version_dict[term] = line.split()[-1]
  887. # horrible hack to get openshift version in Openshift 3.2
  888. # By default "oc version in 3.2 does not return an "openshift" version
  889. if "openshift" not in version_dict:
  890. version_dict["openshift"] = version_dict["oc"]
  891. return version_dict
  892. @staticmethod
  893. def add_custom_versions(versions):
  894. ''' create custom versions strings '''
  895. versions_dict = {}
  896. for tech, version in versions.items():
  897. # clean up "-" from version
  898. if "-" in version:
  899. version = version.split("-")[0]
  900. if version.startswith('v'):
  901. versions_dict[tech + '_numeric'] = version[1:].split('+')[0]
  902. # "v3.3.0.33" is what we have, we want "3.3"
  903. versions_dict[tech + '_short'] = version[1:4]
  904. return versions_dict
  905. @staticmethod
  906. def openshift_installed():
  907. ''' check if openshift is installed '''
  908. import yum
  909. yum_base = yum.YumBase()
  910. if yum_base.rpmdb.searchNevra(name='atomic-openshift'):
  911. return True
  912. return False
  913. # Disabling too-many-branches. This is a yaml dictionary comparison function
  914. # pylint: disable=too-many-branches,too-many-return-statements,too-many-statements
  915. @staticmethod
  916. def check_def_equal(user_def, result_def, skip_keys=None, debug=False):
  917. ''' Given a user defined definition, compare it with the results given back by our query. '''
  918. # Currently these values are autogenerated and we do not need to check them
  919. skip = ['metadata', 'status']
  920. if skip_keys:
  921. skip.extend(skip_keys)
  922. for key, value in result_def.items():
  923. if key in skip:
  924. continue
  925. # Both are lists
  926. if isinstance(value, list):
  927. if key not in user_def:
  928. if debug:
  929. print('User data does not have key [%s]' % key)
  930. print('User data: %s' % user_def)
  931. return False
  932. if not isinstance(user_def[key], list):
  933. if debug:
  934. print('user_def[key] is not a list key=[%s] user_def[key]=%s' % (key, user_def[key]))
  935. return False
  936. if len(user_def[key]) != len(value):
  937. if debug:
  938. print("List lengths are not equal.")
  939. print("key=[%s]: user_def[%s] != value[%s]" % (key, len(user_def[key]), len(value)))
  940. print("user_def: %s" % user_def[key])
  941. print("value: %s" % value)
  942. return False
  943. for values in zip(user_def[key], value):
  944. if isinstance(values[0], dict) and isinstance(values[1], dict):
  945. if debug:
  946. print('sending list - list')
  947. print(type(values[0]))
  948. print(type(values[1]))
  949. result = Utils.check_def_equal(values[0], values[1], skip_keys=skip_keys, debug=debug)
  950. if not result:
  951. print('list compare returned false')
  952. return False
  953. elif value != user_def[key]:
  954. if debug:
  955. print('value should be identical')
  956. print(value)
  957. print(user_def[key])
  958. return False
  959. # recurse on a dictionary
  960. elif isinstance(value, dict):
  961. if key not in user_def:
  962. if debug:
  963. print("user_def does not have key [%s]" % key)
  964. return False
  965. if not isinstance(user_def[key], dict):
  966. if debug:
  967. print("dict returned false: not instance of dict")
  968. return False
  969. # before passing ensure keys match
  970. api_values = set(value.keys()) - set(skip)
  971. user_values = set(user_def[key].keys()) - set(skip)
  972. if api_values != user_values:
  973. if debug:
  974. print("keys are not equal in dict")
  975. print(api_values)
  976. print(user_values)
  977. return False
  978. result = Utils.check_def_equal(user_def[key], value, skip_keys=skip_keys, debug=debug)
  979. if not result:
  980. if debug:
  981. print("dict returned false")
  982. print(result)
  983. return False
  984. # Verify each key, value pair is the same
  985. else:
  986. if key not in user_def or value != user_def[key]:
  987. if debug:
  988. print("value not equal; user_def does not have key")
  989. print(key)
  990. print(value)
  991. if key in user_def:
  992. print(user_def[key])
  993. return False
  994. if debug:
  995. print('returning true')
  996. return True
  997. class OpenShiftCLIConfig(object):
  998. '''Generic Config'''
  999. def __init__(self, rname, namespace, kubeconfig, options):
  1000. self.kubeconfig = kubeconfig
  1001. self.name = rname
  1002. self.namespace = namespace
  1003. self._options = options
  1004. @property
  1005. def config_options(self):
  1006. ''' return config options '''
  1007. return self._options
  1008. def to_option_list(self):
  1009. '''return all options as a string'''
  1010. return self.stringify()
  1011. def stringify(self):
  1012. ''' return the options hash as cli params in a string '''
  1013. rval = []
  1014. for key, data in self.config_options.items():
  1015. if data['include'] \
  1016. and (data['value'] or isinstance(data['value'], int)):
  1017. rval.append('--%s=%s' % (key.replace('_', '-'), data['value']))
  1018. return rval
  1019. class Edit(OpenShiftCLI):
  1020. ''' Class to wrap the oc command line tools
  1021. '''
  1022. # pylint: disable=too-many-arguments
  1023. def __init__(self,
  1024. kind,
  1025. namespace,
  1026. resource_name=None,
  1027. kubeconfig='/etc/origin/master/admin.kubeconfig',
  1028. separator='.',
  1029. verbose=False):
  1030. ''' Constructor for OpenshiftOC '''
  1031. super(Edit, self).__init__(namespace, kubeconfig)
  1032. self.namespace = namespace
  1033. self.kind = kind
  1034. self.name = resource_name
  1035. self.kubeconfig = kubeconfig
  1036. self.separator = separator
  1037. self.verbose = verbose
  1038. def get(self):
  1039. '''return a secret by name '''
  1040. return self._get(self.kind, self.name)
  1041. def update(self, file_name, content, force=False, content_type='yaml'):
  1042. '''run update '''
  1043. if file_name:
  1044. if content_type == 'yaml':
  1045. data = yaml.load(open(file_name))
  1046. elif content_type == 'json':
  1047. data = json.loads(open(file_name).read())
  1048. changes = []
  1049. yed = Yedit(filename=file_name, content=data, separator=self.separator)
  1050. for key, value in content.items():
  1051. changes.append(yed.put(key, value))
  1052. if any([not change[0] for change in changes]):
  1053. return {'returncode': 0, 'updated': False}
  1054. yed.write()
  1055. atexit.register(Utils.cleanup, [file_name])
  1056. return self._replace(file_name, force=force)
  1057. return self._replace_content(self.kind, self.name, content, force=force, sep=self.separator)
  1058. @staticmethod
  1059. def run_ansible(params, check_mode):
  1060. '''run the ansible idempotent code'''
  1061. ocedit = Edit(params['kind'],
  1062. params['namespace'],
  1063. params['name'],
  1064. kubeconfig=params['kubeconfig'],
  1065. separator=params['separator'],
  1066. verbose=params['debug'])
  1067. api_rval = ocedit.get()
  1068. ########
  1069. # Create
  1070. ########
  1071. if not Utils.exists(api_rval['results'], params['name']):
  1072. return {"failed": True, 'msg': api_rval}
  1073. ########
  1074. # Update
  1075. ########
  1076. if check_mode:
  1077. return {'changed': True, 'msg': 'CHECK_MODE: Would have performed edit'}
  1078. api_rval = ocedit.update(params['file_name'],
  1079. params['content'],
  1080. params['force'],
  1081. params['file_format'])
  1082. if api_rval['returncode'] != 0:
  1083. return {"failed": True, 'msg': api_rval}
  1084. if 'updated' in api_rval and not api_rval['updated']:
  1085. return {"changed": False, 'results': api_rval, 'state': 'present'}
  1086. # return the created object
  1087. api_rval = ocedit.get()
  1088. if api_rval['returncode'] != 0:
  1089. return {"failed": True, 'msg': api_rval}
  1090. return {"changed": True, 'results': api_rval, 'state': 'present'}
  1091. def main():
  1092. '''
  1093. ansible oc module for editing objects
  1094. '''
  1095. module = AnsibleModule(
  1096. argument_spec=dict(
  1097. kubeconfig=dict(default='/etc/origin/master/admin.kubeconfig', type='str'),
  1098. state=dict(default='present', type='str',
  1099. choices=['present']),
  1100. debug=dict(default=False, type='bool'),
  1101. namespace=dict(default='default', type='str'),
  1102. name=dict(default=None, required=True, type='str'),
  1103. kind=dict(required=True,
  1104. type='str',
  1105. choices=['dc', 'deploymentconfig',
  1106. 'rc', 'replicationcontroller',
  1107. 'svc', 'service',
  1108. 'scc', 'securitycontextconstraints',
  1109. 'ns', 'namespace', 'project', 'projects',
  1110. 'is', 'imagestream',
  1111. 'istag', 'imagestreamtag',
  1112. 'bc', 'buildconfig',
  1113. 'routes',
  1114. 'node',
  1115. 'secret',
  1116. 'pv', 'persistentvolume']),
  1117. file_name=dict(default=None, type='str'),
  1118. file_format=dict(default='yaml', type='str'),
  1119. content=dict(default=None, required=True, type='dict'),
  1120. force=dict(default=False, type='bool'),
  1121. separator=dict(default='.', type='str'),
  1122. ),
  1123. supports_check_mode=True,
  1124. )
  1125. rval = Edit.run_ansible(module.params, module.check_mode)
  1126. if 'failed' in rval:
  1127. module.fail_json(**rval)
  1128. module.exit_json(**rval)
  1129. if __name__ == '__main__':
  1130. main()