oc_edit.py 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311
  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. '''return all pods '''
  647. cmd = ['-n', self.namespace, '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. '''return all pods '''
  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. '''return all pods '''
  660. return self.openshift_cmd(['create', '-f', fname, '-n', self.namespace])
  661. def _delete(self, resource, rname, selector=None):
  662. '''return all pods '''
  663. cmd = ['delete', resource, rname, '-n', self.namespace]
  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. '''return all pods '''
  669. cmd = ['process', '-n', self.namespace]
  670. if template_data:
  671. cmd.extend(['-f', '-'])
  672. else:
  673. cmd.append(template_name)
  674. if params:
  675. param_str = ["%s=%s" % (key, value) for key, value in params.items()]
  676. cmd.append('-v')
  677. cmd.extend(param_str)
  678. results = self.openshift_cmd(cmd, output=True, input_data=template_data)
  679. if results['returncode'] != 0 or not create:
  680. return results
  681. fname = '/tmp/%s' % template_name
  682. yed = Yedit(fname, results['results'])
  683. yed.write()
  684. atexit.register(Utils.cleanup, [fname])
  685. return self.openshift_cmd(['-n', self.namespace, 'create', '-f', fname])
  686. def _get(self, resource, rname=None, selector=None):
  687. '''return a resource by name '''
  688. cmd = ['get', resource]
  689. if selector:
  690. cmd.append('--selector=%s' % selector)
  691. if self.all_namespaces:
  692. cmd.extend(['--all-namespaces'])
  693. elif self.namespace:
  694. cmd.extend(['-n', self.namespace])
  695. cmd.extend(['-o', 'json'])
  696. if rname:
  697. cmd.append(rname)
  698. rval = self.openshift_cmd(cmd, output=True)
  699. # Ensure results are retuned in an array
  700. if 'items' in rval:
  701. rval['results'] = rval['items']
  702. elif not isinstance(rval['results'], list):
  703. rval['results'] = [rval['results']]
  704. return rval
  705. def _schedulable(self, node=None, selector=None, schedulable=True):
  706. ''' perform oadm manage-node scheduable '''
  707. cmd = ['manage-node']
  708. if node:
  709. cmd.extend(node)
  710. else:
  711. cmd.append('--selector=%s' % selector)
  712. cmd.append('--schedulable=%s' % schedulable)
  713. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw') # noqa: E501
  714. def _list_pods(self, node=None, selector=None, pod_selector=None):
  715. ''' perform oadm manage-node evacuate '''
  716. cmd = ['manage-node']
  717. if node:
  718. cmd.extend(node)
  719. else:
  720. cmd.append('--selector=%s' % selector)
  721. if pod_selector:
  722. cmd.append('--pod-selector=%s' % pod_selector)
  723. cmd.extend(['--list-pods', '-o', 'json'])
  724. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  725. # pylint: disable=too-many-arguments
  726. def _evacuate(self, node=None, selector=None, pod_selector=None, dry_run=False, grace_period=None, force=False):
  727. ''' perform oadm manage-node evacuate '''
  728. cmd = ['manage-node']
  729. if node:
  730. cmd.extend(node)
  731. else:
  732. cmd.append('--selector=%s' % selector)
  733. if dry_run:
  734. cmd.append('--dry-run')
  735. if pod_selector:
  736. cmd.append('--pod-selector=%s' % pod_selector)
  737. if grace_period:
  738. cmd.append('--grace-period=%s' % int(grace_period))
  739. if force:
  740. cmd.append('--force')
  741. cmd.append('--evacuate')
  742. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  743. def _import_image(self, url=None, name=None, tag=None):
  744. ''' perform image import '''
  745. cmd = ['import-image']
  746. image = '{0}'.format(name)
  747. if tag:
  748. image += ':{0}'.format(tag)
  749. cmd.append(image)
  750. if url:
  751. cmd.append('--from={0}/{1}'.format(url, image))
  752. cmd.append('-n{0}'.format(self.namespace))
  753. cmd.append('--confirm')
  754. return self.openshift_cmd(cmd)
  755. # pylint: disable=too-many-arguments
  756. def openshift_cmd(self, cmd, oadm=False, output=False, output_type='json', input_data=None):
  757. '''Base command for oc '''
  758. cmds = []
  759. if oadm:
  760. cmds = ['/usr/bin/oadm']
  761. else:
  762. cmds = ['/usr/bin/oc']
  763. cmds.extend(cmd)
  764. rval = {}
  765. results = ''
  766. err = None
  767. if self.verbose:
  768. print(' '.join(cmds))
  769. proc = subprocess.Popen(cmds,
  770. stdin=subprocess.PIPE,
  771. stdout=subprocess.PIPE,
  772. stderr=subprocess.PIPE,
  773. env={'KUBECONFIG': self.kubeconfig})
  774. stdout, stderr = proc.communicate(input_data)
  775. rval = {"returncode": proc.returncode,
  776. "results": results,
  777. "cmd": ' '.join(cmds)}
  778. if proc.returncode == 0:
  779. if output:
  780. if output_type == 'json':
  781. try:
  782. rval['results'] = json.loads(stdout)
  783. except ValueError as err:
  784. if "No JSON object could be decoded" in err.args:
  785. err = err.args
  786. elif output_type == 'raw':
  787. rval['results'] = stdout
  788. if self.verbose:
  789. print("STDOUT: {0}".format(stdout))
  790. print("STDERR: {0}".format(stderr))
  791. if err:
  792. rval.update({"err": err,
  793. "stderr": stderr,
  794. "stdout": stdout,
  795. "cmd": cmds})
  796. else:
  797. rval.update({"stderr": stderr,
  798. "stdout": stdout,
  799. "results": {}})
  800. return rval
  801. class Utils(object):
  802. ''' utilities for openshiftcli modules '''
  803. @staticmethod
  804. def create_file(rname, data, ftype='yaml'):
  805. ''' create a file in tmp with name and contents'''
  806. path = os.path.join('/tmp', rname)
  807. with open(path, 'w') as fds:
  808. if ftype == 'yaml':
  809. fds.write(yaml.dump(data, Dumper=yaml.RoundTripDumper))
  810. elif ftype == 'json':
  811. fds.write(json.dumps(data))
  812. else:
  813. fds.write(data)
  814. # Register cleanup when module is done
  815. atexit.register(Utils.cleanup, [path])
  816. return path
  817. @staticmethod
  818. def create_files_from_contents(content, content_type=None):
  819. '''Turn an array of dict: filename, content into a files array'''
  820. if not isinstance(content, list):
  821. content = [content]
  822. files = []
  823. for item in content:
  824. path = Utils.create_file(item['path'], item['data'], ftype=content_type)
  825. files.append({'name': os.path.basename(path), 'path': path})
  826. return files
  827. @staticmethod
  828. def cleanup(files):
  829. '''Clean up on exit '''
  830. for sfile in files:
  831. if os.path.exists(sfile):
  832. if os.path.isdir(sfile):
  833. shutil.rmtree(sfile)
  834. elif os.path.isfile(sfile):
  835. os.remove(sfile)
  836. @staticmethod
  837. def exists(results, _name):
  838. ''' Check to see if the results include the name '''
  839. if not results:
  840. return False
  841. if Utils.find_result(results, _name):
  842. return True
  843. return False
  844. @staticmethod
  845. def find_result(results, _name):
  846. ''' Find the specified result by name'''
  847. rval = None
  848. for result in results:
  849. if 'metadata' in result and result['metadata']['name'] == _name:
  850. rval = result
  851. break
  852. return rval
  853. @staticmethod
  854. def get_resource_file(sfile, sfile_type='yaml'):
  855. ''' return the service file '''
  856. contents = None
  857. with open(sfile) as sfd:
  858. contents = sfd.read()
  859. if sfile_type == 'yaml':
  860. contents = yaml.load(contents, yaml.RoundTripLoader)
  861. elif sfile_type == 'json':
  862. contents = json.loads(contents)
  863. return contents
  864. # Disabling too-many-branches. This is a yaml dictionary comparison function
  865. # pylint: disable=too-many-branches,too-many-return-statements,too-many-statements
  866. @staticmethod
  867. def check_def_equal(user_def, result_def, skip_keys=None, debug=False):
  868. ''' Given a user defined definition, compare it with the results given back by our query. '''
  869. # Currently these values are autogenerated and we do not need to check them
  870. skip = ['metadata', 'status']
  871. if skip_keys:
  872. skip.extend(skip_keys)
  873. for key, value in result_def.items():
  874. if key in skip:
  875. continue
  876. # Both are lists
  877. if isinstance(value, list):
  878. if key not in user_def:
  879. if debug:
  880. print('User data does not have key [%s]' % key)
  881. print('User data: %s' % user_def)
  882. return False
  883. if not isinstance(user_def[key], list):
  884. if debug:
  885. print('user_def[key] is not a list key=[%s] user_def[key]=%s' % (key, user_def[key]))
  886. return False
  887. if len(user_def[key]) != len(value):
  888. if debug:
  889. print("List lengths are not equal.")
  890. print("key=[%s]: user_def[%s] != value[%s]" % (key, len(user_def[key]), len(value)))
  891. print("user_def: %s" % user_def[key])
  892. print("value: %s" % value)
  893. return False
  894. for values in zip(user_def[key], value):
  895. if isinstance(values[0], dict) and isinstance(values[1], dict):
  896. if debug:
  897. print('sending list - list')
  898. print(type(values[0]))
  899. print(type(values[1]))
  900. result = Utils.check_def_equal(values[0], values[1], skip_keys=skip_keys, debug=debug)
  901. if not result:
  902. print('list compare returned false')
  903. return False
  904. elif value != user_def[key]:
  905. if debug:
  906. print('value should be identical')
  907. print(value)
  908. print(user_def[key])
  909. return False
  910. # recurse on a dictionary
  911. elif isinstance(value, dict):
  912. if key not in user_def:
  913. if debug:
  914. print("user_def does not have key [%s]" % key)
  915. return False
  916. if not isinstance(user_def[key], dict):
  917. if debug:
  918. print("dict returned false: not instance of dict")
  919. return False
  920. # before passing ensure keys match
  921. api_values = set(value.keys()) - set(skip)
  922. user_values = set(user_def[key].keys()) - set(skip)
  923. if api_values != user_values:
  924. if debug:
  925. print("keys are not equal in dict")
  926. print(api_values)
  927. print(user_values)
  928. return False
  929. result = Utils.check_def_equal(user_def[key], value, skip_keys=skip_keys, debug=debug)
  930. if not result:
  931. if debug:
  932. print("dict returned false")
  933. print(result)
  934. return False
  935. # Verify each key, value pair is the same
  936. else:
  937. if key not in user_def or value != user_def[key]:
  938. if debug:
  939. print("value not equal; user_def does not have key")
  940. print(key)
  941. print(value)
  942. if key in user_def:
  943. print(user_def[key])
  944. return False
  945. if debug:
  946. print('returning true')
  947. return True
  948. class OpenShiftCLIConfig(object):
  949. '''Generic Config'''
  950. def __init__(self, rname, namespace, kubeconfig, options):
  951. self.kubeconfig = kubeconfig
  952. self.name = rname
  953. self.namespace = namespace
  954. self._options = options
  955. @property
  956. def config_options(self):
  957. ''' return config options '''
  958. return self._options
  959. def to_option_list(self):
  960. '''return all options as a string'''
  961. return self.stringify()
  962. def stringify(self):
  963. ''' return the options hash as cli params in a string '''
  964. rval = []
  965. for key, data in self.config_options.items():
  966. if data['include'] \
  967. and (data['value'] or isinstance(data['value'], int)):
  968. rval.append('--%s=%s' % (key.replace('_', '-'), data['value']))
  969. return rval
  970. class Edit(OpenShiftCLI):
  971. ''' Class to wrap the oc command line tools
  972. '''
  973. # pylint: disable=too-many-arguments
  974. def __init__(self,
  975. kind,
  976. namespace,
  977. resource_name=None,
  978. kubeconfig='/etc/origin/master/admin.kubeconfig',
  979. separator='.',
  980. verbose=False):
  981. ''' Constructor for OpenshiftOC '''
  982. super(Edit, self).__init__(namespace, kubeconfig)
  983. self.namespace = namespace
  984. self.kind = kind
  985. self.name = resource_name
  986. self.kubeconfig = kubeconfig
  987. self.separator = separator
  988. self.verbose = verbose
  989. def get(self):
  990. '''return a secret by name '''
  991. return self._get(self.kind, self.name)
  992. def update(self, file_name, content, force=False, content_type='yaml'):
  993. '''run update '''
  994. if file_name:
  995. if content_type == 'yaml':
  996. data = yaml.load(open(file_name))
  997. elif content_type == 'json':
  998. data = json.loads(open(file_name).read())
  999. changes = []
  1000. yed = Yedit(filename=file_name, content=data, separator=self.separator)
  1001. for key, value in content.items():
  1002. changes.append(yed.put(key, value))
  1003. if any([not change[0] for change in changes]):
  1004. return {'returncode': 0, 'updated': False}
  1005. yed.write()
  1006. atexit.register(Utils.cleanup, [file_name])
  1007. return self._replace(file_name, force=force)
  1008. return self._replace_content(self.kind, self.name, content, force=force, sep=self.separator)
  1009. @staticmethod
  1010. def run_ansible(params, check_mode):
  1011. '''run the ansible idempotent code'''
  1012. ocedit = Edit(params['kind'],
  1013. params['namespace'],
  1014. params['name'],
  1015. kubeconfig=params['kubeconfig'],
  1016. separator=params['separator'],
  1017. verbose=params['debug'])
  1018. api_rval = ocedit.get()
  1019. ########
  1020. # Create
  1021. ########
  1022. if not Utils.exists(api_rval['results'], params['name']):
  1023. return {"failed": True, 'msg': api_rval}
  1024. ########
  1025. # Update
  1026. ########
  1027. if check_mode:
  1028. return {'changed': True, 'msg': 'CHECK_MODE: Would have performed edit'}
  1029. api_rval = ocedit.update(params['file_name'],
  1030. params['content'],
  1031. params['force'],
  1032. params['file_format'])
  1033. if api_rval['returncode'] != 0:
  1034. return {"failed": True, 'msg': api_rval}
  1035. if 'updated' in api_rval and not api_rval['updated']:
  1036. return {"changed": False, 'results': api_rval, 'state': 'present'}
  1037. # return the created object
  1038. api_rval = ocedit.get()
  1039. if api_rval['returncode'] != 0:
  1040. return {"failed": True, 'msg': api_rval}
  1041. return {"changed": True, 'results': api_rval, 'state': 'present'}
  1042. def main():
  1043. '''
  1044. ansible oc module for editing objects
  1045. '''
  1046. module = AnsibleModule(
  1047. argument_spec=dict(
  1048. kubeconfig=dict(default='/etc/origin/master/admin.kubeconfig', type='str'),
  1049. state=dict(default='present', type='str',
  1050. choices=['present']),
  1051. debug=dict(default=False, type='bool'),
  1052. namespace=dict(default='default', type='str'),
  1053. name=dict(default=None, required=True, type='str'),
  1054. kind=dict(required=True,
  1055. type='str',
  1056. choices=['dc', 'deploymentconfig',
  1057. 'rc', 'replicationcontroller',
  1058. 'svc', 'service',
  1059. 'scc', 'securitycontextconstraints',
  1060. 'ns', 'namespace', 'project', 'projects',
  1061. 'is', 'imagestream',
  1062. 'istag', 'imagestreamtag',
  1063. 'bc', 'buildconfig',
  1064. 'routes',
  1065. 'node',
  1066. 'secret',
  1067. 'pv', 'persistentvolume']),
  1068. file_name=dict(default=None, type='str'),
  1069. file_format=dict(default='yaml', type='str'),
  1070. content=dict(default=None, required=True, type='dict'),
  1071. force=dict(default=False, type='bool'),
  1072. separator=dict(default='.', type='str'),
  1073. ),
  1074. supports_check_mode=True,
  1075. )
  1076. rval = Edit.run_ansible(module.params, module.check_mode)
  1077. if 'failed' in rval:
  1078. module.fail_json(**rval)
  1079. module.exit_json(**rval)
  1080. if __name__ == '__main__':
  1081. main()