oc_secret.py 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878
  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 fcntl
  36. import json
  37. import time
  38. import os
  39. import re
  40. import shutil
  41. import subprocess
  42. import tempfile
  43. # pylint: disable=import-error
  44. try:
  45. import ruamel.yaml as yaml
  46. except ImportError:
  47. import yaml
  48. from ansible.module_utils.basic import AnsibleModule
  49. # -*- -*- -*- End included fragment: lib/import.py -*- -*- -*-
  50. # -*- -*- -*- Begin included fragment: doc/secret -*- -*- -*-
  51. DOCUMENTATION = '''
  52. ---
  53. module: oc_secret
  54. short_description: Module to manage openshift secrets
  55. description:
  56. - Manage openshift secrets programmatically.
  57. options:
  58. state:
  59. description:
  60. - State controls the action that will be taken with resource
  61. - present - the secret will be created if it doesn't exist or updated if different.
  62. - absent - the secret will be removed if present.
  63. - list - information about the secret will be gathered and returned as part of the Ansible call results.
  64. required: false
  65. default: present
  66. choices: ["present", "absent", "list"]
  67. aliases: []
  68. kubeconfig:
  69. description:
  70. - The path for the kubeconfig file to use for authentication
  71. required: false
  72. default: /etc/origin/master/admin.kubeconfig
  73. aliases: []
  74. debug:
  75. description:
  76. - Turn on debug output.
  77. required: false
  78. default: False
  79. aliases: []
  80. name:
  81. description:
  82. - Name of the object that is being queried.
  83. required: false
  84. default: None
  85. aliases: []
  86. namespace:
  87. description:
  88. - The namespace where the object lives.
  89. required: false
  90. default: default
  91. aliases: []
  92. annotations:
  93. description:
  94. - Annotations to apply to the object
  95. required: false
  96. default: None
  97. aliases: []
  98. files:
  99. description:
  100. - A list of files provided for secrets
  101. required: false
  102. default: None
  103. aliases: []
  104. delete_after:
  105. description:
  106. - Whether or not to delete the files after processing them.
  107. required: false
  108. default: false
  109. aliases: []
  110. contents:
  111. description:
  112. - Content of the secrets
  113. required: false
  114. default: None
  115. aliases: []
  116. type:
  117. description:
  118. - The secret type.
  119. required: false
  120. default: None
  121. aliases: []
  122. force:
  123. description:
  124. - Whether or not to force the operation
  125. required: false
  126. default: false
  127. aliases: []
  128. decode:
  129. description:
  130. - base64 decode the object
  131. required: false
  132. default: false
  133. aliases: []
  134. author:
  135. - "Kenny Woodson <kwoodson@redhat.com>"
  136. extends_documentation_fragment: []
  137. '''
  138. EXAMPLES = '''
  139. - name: create secret
  140. oc_secret:
  141. state: present
  142. namespace: openshift-infra
  143. name: metrics-deployer
  144. files:
  145. - name: nothing
  146. path: /dev/null
  147. register: secretout
  148. run_once: true
  149. - name: get ca from hawkular
  150. oc_secret:
  151. state: list
  152. namespace: openshift-infra
  153. name: hawkular-metrics-certificate
  154. decode: True
  155. register: hawkout
  156. run_once: true
  157. - name: Create secrets
  158. oc_secret:
  159. namespace: mynamespace
  160. name: mysecrets
  161. contents:
  162. - path: data.yml
  163. data: "{{ data_content }}"
  164. - path: auth-keys
  165. data: "{{ auth_keys_content }}"
  166. - path: configdata.yml
  167. data: "{{ configdata_content }}"
  168. - path: cert.crt
  169. data: "{{ cert_content }}"
  170. - path: key.pem
  171. data: "{{ osso_site_key_content }}"
  172. - path: ca.cert.pem
  173. data: "{{ ca_cert_content }}"
  174. register: secretout
  175. '''
  176. # -*- -*- -*- End included fragment: doc/secret -*- -*- -*-
  177. # -*- -*- -*- Begin included fragment: ../../lib_utils/src/class/yedit.py -*- -*- -*-
  178. class YeditException(Exception): # pragma: no cover
  179. ''' Exception class for Yedit '''
  180. pass
  181. # pylint: disable=too-many-public-methods,too-many-instance-attributes
  182. class Yedit(object): # pragma: no cover
  183. ''' Class to modify yaml files '''
  184. re_valid_key = r"(((\[-?\d+\])|([0-9a-zA-Z%s/_-]+)).?)+$"
  185. re_key = r"(?:\[(-?\d+)\])|([0-9a-zA-Z{}/_-]+)"
  186. com_sep = set(['.', '#', '|', ':'])
  187. # pylint: disable=too-many-arguments
  188. def __init__(self,
  189. filename=None,
  190. content=None,
  191. content_type='yaml',
  192. separator='.',
  193. backup_ext=None,
  194. backup=False):
  195. self.content = content
  196. self._separator = separator
  197. self.filename = filename
  198. self.__yaml_dict = content
  199. self.content_type = content_type
  200. self.backup = backup
  201. if backup_ext is None:
  202. self.backup_ext = ".{}".format(time.strftime("%Y%m%dT%H%M%S"))
  203. else:
  204. self.backup_ext = backup_ext
  205. self.load(content_type=self.content_type)
  206. if self.__yaml_dict is None:
  207. self.__yaml_dict = {}
  208. @property
  209. def separator(self):
  210. ''' getter method for separator '''
  211. return self._separator
  212. @separator.setter
  213. def separator(self, inc_sep):
  214. ''' setter method for separator '''
  215. self._separator = inc_sep
  216. @property
  217. def yaml_dict(self):
  218. ''' getter method for yaml_dict '''
  219. return self.__yaml_dict
  220. @yaml_dict.setter
  221. def yaml_dict(self, value):
  222. ''' setter method for yaml_dict '''
  223. self.__yaml_dict = value
  224. @staticmethod
  225. def parse_key(key, sep='.'):
  226. '''parse the key allowing the appropriate separator'''
  227. common_separators = list(Yedit.com_sep - set([sep]))
  228. return re.findall(Yedit.re_key.format(''.join(common_separators)), key)
  229. @staticmethod
  230. def valid_key(key, sep='.'):
  231. '''validate the incoming key'''
  232. common_separators = list(Yedit.com_sep - set([sep]))
  233. if not re.match(Yedit.re_valid_key.format(''.join(common_separators)), key):
  234. return False
  235. return True
  236. # pylint: disable=too-many-return-statements,too-many-branches
  237. @staticmethod
  238. def remove_entry(data, key, index=None, value=None, sep='.'):
  239. ''' remove data at location key '''
  240. if key == '' and isinstance(data, dict):
  241. if value is not None:
  242. data.pop(value)
  243. elif index is not None:
  244. raise YeditException("remove_entry for a dictionary does not have an index {}".format(index))
  245. else:
  246. data.clear()
  247. return True
  248. elif key == '' and isinstance(data, list):
  249. ind = None
  250. if value is not None:
  251. try:
  252. ind = data.index(value)
  253. except ValueError:
  254. return False
  255. elif index is not None:
  256. ind = index
  257. else:
  258. del data[:]
  259. if ind is not None:
  260. data.pop(ind)
  261. return True
  262. if not (key and Yedit.valid_key(key, sep)) and \
  263. isinstance(data, (list, dict)):
  264. return None
  265. key_indexes = Yedit.parse_key(key, sep)
  266. for arr_ind, dict_key in key_indexes[:-1]:
  267. if dict_key and isinstance(data, dict):
  268. data = data.get(dict_key)
  269. elif (arr_ind and isinstance(data, list) and
  270. int(arr_ind) <= len(data) - 1):
  271. data = data[int(arr_ind)]
  272. else:
  273. return None
  274. # process last index for remove
  275. # expected list entry
  276. if key_indexes[-1][0]:
  277. if isinstance(data, list) and int(key_indexes[-1][0]) <= len(data) - 1: # noqa: E501
  278. del data[int(key_indexes[-1][0])]
  279. return True
  280. # expected dict entry
  281. elif key_indexes[-1][1]:
  282. if isinstance(data, dict):
  283. del data[key_indexes[-1][1]]
  284. return True
  285. @staticmethod
  286. def add_entry(data, key, item=None, sep='.'):
  287. ''' Get an item from a dictionary with key notation a.b.c
  288. d = {'a': {'b': 'c'}}}
  289. key = a#b
  290. return c
  291. '''
  292. if key == '':
  293. pass
  294. elif (not (key and Yedit.valid_key(key, sep)) and
  295. isinstance(data, (list, dict))):
  296. return None
  297. key_indexes = Yedit.parse_key(key, sep)
  298. for arr_ind, dict_key in key_indexes[:-1]:
  299. if dict_key:
  300. if isinstance(data, dict) and dict_key in data and data[dict_key]: # noqa: E501
  301. data = data[dict_key]
  302. continue
  303. elif data and not isinstance(data, dict):
  304. raise YeditException("Unexpected item type found while going through key " +
  305. "path: {} (at key: {})".format(key, dict_key))
  306. data[dict_key] = {}
  307. data = data[dict_key]
  308. elif (arr_ind and isinstance(data, list) and
  309. int(arr_ind) <= len(data) - 1):
  310. data = data[int(arr_ind)]
  311. else:
  312. raise YeditException("Unexpected item type found while going through key path: {}".format(key))
  313. if key == '':
  314. data = item
  315. # process last index for add
  316. # expected list entry
  317. elif key_indexes[-1][0] and isinstance(data, list) and int(key_indexes[-1][0]) <= len(data) - 1: # noqa: E501
  318. data[int(key_indexes[-1][0])] = item
  319. # expected dict entry
  320. elif key_indexes[-1][1] and isinstance(data, dict):
  321. data[key_indexes[-1][1]] = item
  322. # didn't add/update to an existing list, nor add/update key to a dict
  323. # so we must have been provided some syntax like a.b.c[<int>] = "data" for a
  324. # non-existent array
  325. else:
  326. raise YeditException("Error adding to object at path: {}".format(key))
  327. return data
  328. @staticmethod
  329. def get_entry(data, key, sep='.'):
  330. ''' Get an item from a dictionary with key notation a.b.c
  331. d = {'a': {'b': 'c'}}}
  332. key = a.b
  333. return c
  334. '''
  335. if key == '':
  336. pass
  337. elif (not (key and Yedit.valid_key(key, sep)) and
  338. isinstance(data, (list, dict))):
  339. return None
  340. key_indexes = Yedit.parse_key(key, sep)
  341. for arr_ind, dict_key in key_indexes:
  342. if dict_key and isinstance(data, dict):
  343. data = data.get(dict_key)
  344. elif (arr_ind and isinstance(data, list) and
  345. int(arr_ind) <= len(data) - 1):
  346. data = data[int(arr_ind)]
  347. else:
  348. return None
  349. return data
  350. @staticmethod
  351. def _write(filename, contents):
  352. ''' Actually write the file contents to disk. This helps with mocking. '''
  353. tmp_filename = filename + '.yedit'
  354. with open(tmp_filename, 'w') as yfd:
  355. fcntl.flock(yfd, fcntl.LOCK_EX | fcntl.LOCK_NB)
  356. yfd.write(contents)
  357. fcntl.flock(yfd, fcntl.LOCK_UN)
  358. os.rename(tmp_filename, filename)
  359. def write(self):
  360. ''' write to file '''
  361. if not self.filename:
  362. raise YeditException('Please specify a filename.')
  363. if self.backup and self.file_exists():
  364. shutil.copy(self.filename, '{}{}'.format(self.filename, self.backup_ext))
  365. # Try to set format attributes if supported
  366. try:
  367. self.yaml_dict.fa.set_block_style()
  368. except AttributeError:
  369. pass
  370. # Try to use RoundTripDumper if supported.
  371. if self.content_type == 'yaml':
  372. try:
  373. Yedit._write(self.filename, yaml.dump(self.yaml_dict, Dumper=yaml.RoundTripDumper))
  374. except AttributeError:
  375. Yedit._write(self.filename, yaml.safe_dump(self.yaml_dict, default_flow_style=False))
  376. elif self.content_type == 'json':
  377. Yedit._write(self.filename, json.dumps(self.yaml_dict, indent=4, sort_keys=True))
  378. else:
  379. raise YeditException('Unsupported content_type: {}.'.format(self.content_type) +
  380. 'Please specify a content_type of yaml or json.')
  381. return (True, self.yaml_dict)
  382. def read(self):
  383. ''' read from file '''
  384. # check if it exists
  385. if self.filename is None or not self.file_exists():
  386. return None
  387. contents = None
  388. with open(self.filename) as yfd:
  389. contents = yfd.read()
  390. return contents
  391. def file_exists(self):
  392. ''' return whether file exists '''
  393. if os.path.exists(self.filename):
  394. return True
  395. return False
  396. def load(self, content_type='yaml'):
  397. ''' return yaml file '''
  398. contents = self.read()
  399. if not contents and not self.content:
  400. return None
  401. if self.content:
  402. if isinstance(self.content, dict):
  403. self.yaml_dict = self.content
  404. return self.yaml_dict
  405. elif isinstance(self.content, str):
  406. contents = self.content
  407. # check if it is yaml
  408. try:
  409. if content_type == 'yaml' and contents:
  410. # Try to set format attributes if supported
  411. try:
  412. self.yaml_dict.fa.set_block_style()
  413. except AttributeError:
  414. pass
  415. # Try to use RoundTripLoader if supported.
  416. try:
  417. self.yaml_dict = yaml.load(contents, yaml.RoundTripLoader)
  418. except AttributeError:
  419. self.yaml_dict = yaml.safe_load(contents)
  420. # Try to set format attributes if supported
  421. try:
  422. self.yaml_dict.fa.set_block_style()
  423. except AttributeError:
  424. pass
  425. elif content_type == 'json' and contents:
  426. self.yaml_dict = json.loads(contents)
  427. except yaml.YAMLError as err:
  428. # Error loading yaml or json
  429. raise YeditException('Problem with loading yaml file. {}'.format(err))
  430. return self.yaml_dict
  431. def get(self, key):
  432. ''' get a specified key'''
  433. try:
  434. entry = Yedit.get_entry(self.yaml_dict, key, self.separator)
  435. except KeyError:
  436. entry = None
  437. return entry
  438. def pop(self, path, key_or_item):
  439. ''' remove a key, value pair from a dict or an item for a list'''
  440. try:
  441. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  442. except KeyError:
  443. entry = None
  444. if entry is None:
  445. return (False, self.yaml_dict)
  446. if isinstance(entry, dict):
  447. # AUDIT:maybe-no-member makes sense due to fuzzy types
  448. # pylint: disable=maybe-no-member
  449. if key_or_item in entry:
  450. entry.pop(key_or_item)
  451. return (True, self.yaml_dict)
  452. return (False, self.yaml_dict)
  453. elif isinstance(entry, list):
  454. # AUDIT:maybe-no-member makes sense due to fuzzy types
  455. # pylint: disable=maybe-no-member
  456. ind = None
  457. try:
  458. ind = entry.index(key_or_item)
  459. except ValueError:
  460. return (False, self.yaml_dict)
  461. entry.pop(ind)
  462. return (True, self.yaml_dict)
  463. return (False, self.yaml_dict)
  464. def delete(self, path, index=None, value=None):
  465. ''' remove path from a dict'''
  466. try:
  467. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  468. except KeyError:
  469. entry = None
  470. if entry is None:
  471. return (False, self.yaml_dict)
  472. result = Yedit.remove_entry(self.yaml_dict, path, index, value, self.separator)
  473. if not result:
  474. return (False, self.yaml_dict)
  475. return (True, self.yaml_dict)
  476. def exists(self, path, value):
  477. ''' check if value exists at path'''
  478. try:
  479. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  480. except KeyError:
  481. entry = None
  482. if isinstance(entry, list):
  483. if value in entry:
  484. return True
  485. return False
  486. elif isinstance(entry, dict):
  487. if isinstance(value, dict):
  488. rval = False
  489. for key, val in value.items():
  490. if entry[key] != val:
  491. rval = False
  492. break
  493. else:
  494. rval = True
  495. return rval
  496. return value in entry
  497. return entry == value
  498. def append(self, path, value):
  499. '''append value to a list'''
  500. try:
  501. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  502. except KeyError:
  503. entry = None
  504. if entry is None:
  505. self.put(path, [])
  506. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  507. if not isinstance(entry, list):
  508. return (False, self.yaml_dict)
  509. # AUDIT:maybe-no-member makes sense due to loading data from
  510. # a serialized format.
  511. # pylint: disable=maybe-no-member
  512. entry.append(value)
  513. return (True, self.yaml_dict)
  514. # pylint: disable=too-many-arguments
  515. def update(self, path, value, index=None, curr_value=None):
  516. ''' put path, value into a dict '''
  517. try:
  518. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  519. except KeyError:
  520. entry = None
  521. if isinstance(entry, dict):
  522. # AUDIT:maybe-no-member makes sense due to fuzzy types
  523. # pylint: disable=maybe-no-member
  524. if not isinstance(value, dict):
  525. raise YeditException('Cannot replace key, value entry in dict with non-dict type. ' +
  526. 'value=[{}] type=[{}]'.format(value, type(value)))
  527. entry.update(value)
  528. return (True, self.yaml_dict)
  529. elif isinstance(entry, list):
  530. # AUDIT:maybe-no-member makes sense due to fuzzy types
  531. # pylint: disable=maybe-no-member
  532. ind = None
  533. if curr_value:
  534. try:
  535. ind = entry.index(curr_value)
  536. except ValueError:
  537. return (False, self.yaml_dict)
  538. elif index is not None:
  539. ind = index
  540. if ind is not None and entry[ind] != value:
  541. entry[ind] = value
  542. return (True, self.yaml_dict)
  543. # see if it exists in the list
  544. try:
  545. ind = entry.index(value)
  546. except ValueError:
  547. # doesn't exist, append it
  548. entry.append(value)
  549. return (True, self.yaml_dict)
  550. # already exists, return
  551. if ind is not None:
  552. return (False, self.yaml_dict)
  553. return (False, self.yaml_dict)
  554. def put(self, path, value):
  555. ''' put path, value into a dict '''
  556. try:
  557. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  558. except KeyError:
  559. entry = None
  560. if entry == value:
  561. return (False, self.yaml_dict)
  562. # deepcopy didn't work
  563. # Try to use ruamel.yaml and fallback to pyyaml
  564. try:
  565. tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict,
  566. default_flow_style=False),
  567. yaml.RoundTripLoader)
  568. except AttributeError:
  569. tmp_copy = copy.deepcopy(self.yaml_dict)
  570. # set the format attributes if available
  571. try:
  572. tmp_copy.fa.set_block_style()
  573. except AttributeError:
  574. pass
  575. result = Yedit.add_entry(tmp_copy, path, value, self.separator)
  576. if result is None:
  577. return (False, self.yaml_dict)
  578. # When path equals "" it is a special case.
  579. # "" refers to the root of the document
  580. # Only update the root path (entire document) when its a list or dict
  581. if path == '':
  582. if isinstance(result, list) or isinstance(result, dict):
  583. self.yaml_dict = result
  584. return (True, self.yaml_dict)
  585. return (False, self.yaml_dict)
  586. self.yaml_dict = tmp_copy
  587. return (True, self.yaml_dict)
  588. def create(self, path, value):
  589. ''' create a yaml file '''
  590. if not self.file_exists():
  591. # deepcopy didn't work
  592. # Try to use ruamel.yaml and fallback to pyyaml
  593. try:
  594. tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict,
  595. default_flow_style=False),
  596. yaml.RoundTripLoader)
  597. except AttributeError:
  598. tmp_copy = copy.deepcopy(self.yaml_dict)
  599. # set the format attributes if available
  600. try:
  601. tmp_copy.fa.set_block_style()
  602. except AttributeError:
  603. pass
  604. result = Yedit.add_entry(tmp_copy, path, value, self.separator)
  605. if result is not None:
  606. self.yaml_dict = tmp_copy
  607. return (True, self.yaml_dict)
  608. return (False, self.yaml_dict)
  609. @staticmethod
  610. def get_curr_value(invalue, val_type):
  611. '''return the current value'''
  612. if invalue is None:
  613. return None
  614. curr_value = invalue
  615. if val_type == 'yaml':
  616. curr_value = yaml.safe_load(str(invalue))
  617. elif val_type == 'json':
  618. curr_value = json.loads(invalue)
  619. return curr_value
  620. @staticmethod
  621. def parse_value(inc_value, vtype=''):
  622. '''determine value type passed'''
  623. true_bools = ['y', 'Y', 'yes', 'Yes', 'YES', 'true', 'True', 'TRUE',
  624. 'on', 'On', 'ON', ]
  625. false_bools = ['n', 'N', 'no', 'No', 'NO', 'false', 'False', 'FALSE',
  626. 'off', 'Off', 'OFF']
  627. # It came in as a string but you didn't specify value_type as string
  628. # we will convert to bool if it matches any of the above cases
  629. if isinstance(inc_value, str) and 'bool' in vtype:
  630. if inc_value not in true_bools and inc_value not in false_bools:
  631. raise YeditException('Not a boolean type. str=[{}] vtype=[{}]'.format(inc_value, vtype))
  632. elif isinstance(inc_value, bool) and 'str' in vtype:
  633. inc_value = str(inc_value)
  634. # There is a special case where '' will turn into None after yaml loading it so skip
  635. if isinstance(inc_value, str) and inc_value == '':
  636. pass
  637. # If vtype is not str then go ahead and attempt to yaml load it.
  638. elif isinstance(inc_value, str) and 'str' not in vtype:
  639. try:
  640. inc_value = yaml.safe_load(inc_value)
  641. except Exception:
  642. raise YeditException('Could not determine type of incoming value. ' +
  643. 'value=[{}] vtype=[{}]'.format(type(inc_value), vtype))
  644. return inc_value
  645. @staticmethod
  646. def process_edits(edits, yamlfile):
  647. '''run through a list of edits and process them one-by-one'''
  648. results = []
  649. for edit in edits:
  650. value = Yedit.parse_value(edit['value'], edit.get('value_type', ''))
  651. if edit.get('action') == 'update':
  652. # pylint: disable=line-too-long
  653. curr_value = Yedit.get_curr_value(
  654. Yedit.parse_value(edit.get('curr_value')),
  655. edit.get('curr_value_format'))
  656. rval = yamlfile.update(edit['key'],
  657. value,
  658. edit.get('index'),
  659. curr_value)
  660. elif edit.get('action') == 'append':
  661. rval = yamlfile.append(edit['key'], value)
  662. else:
  663. rval = yamlfile.put(edit['key'], value)
  664. if rval[0]:
  665. results.append({'key': edit['key'], 'edit': rval[1]})
  666. return {'changed': len(results) > 0, 'results': results}
  667. # pylint: disable=too-many-return-statements,too-many-branches
  668. @staticmethod
  669. def run_ansible(params):
  670. '''perform the idempotent crud operations'''
  671. yamlfile = Yedit(filename=params['src'],
  672. backup=params['backup'],
  673. content_type=params['content_type'],
  674. backup_ext=params['backup_ext'],
  675. separator=params['separator'])
  676. state = params['state']
  677. if params['src']:
  678. rval = yamlfile.load()
  679. if yamlfile.yaml_dict is None and state != 'present':
  680. return {'failed': True,
  681. 'msg': 'Error opening file [{}]. Verify that the '.format(params['src']) +
  682. 'file exists, that it is has correct permissions, and is valid yaml.'}
  683. if state == 'list':
  684. if params['content']:
  685. content = Yedit.parse_value(params['content'], params['content_type'])
  686. yamlfile.yaml_dict = content
  687. if params['key']:
  688. rval = yamlfile.get(params['key'])
  689. return {'changed': False, 'result': rval, 'state': state}
  690. elif state == 'absent':
  691. if params['content']:
  692. content = Yedit.parse_value(params['content'], params['content_type'])
  693. yamlfile.yaml_dict = content
  694. if params['update']:
  695. rval = yamlfile.pop(params['key'], params['value'])
  696. else:
  697. rval = yamlfile.delete(params['key'], params['index'], params['value'])
  698. if rval[0] and params['src']:
  699. yamlfile.write()
  700. return {'changed': rval[0], 'result': rval[1], 'state': state}
  701. elif state == 'present':
  702. # check if content is different than what is in the file
  703. if params['content']:
  704. content = Yedit.parse_value(params['content'], params['content_type'])
  705. # We had no edits to make and the contents are the same
  706. if yamlfile.yaml_dict == content and \
  707. params['value'] is None:
  708. return {'changed': False, 'result': yamlfile.yaml_dict, 'state': state}
  709. yamlfile.yaml_dict = content
  710. # If we were passed a key, value then
  711. # we enapsulate it in a list and process it
  712. # Key, Value passed to the module : Converted to Edits list #
  713. edits = []
  714. _edit = {}
  715. if params['value'] is not None:
  716. _edit['value'] = params['value']
  717. _edit['value_type'] = params['value_type']
  718. _edit['key'] = params['key']
  719. if params['update']:
  720. _edit['action'] = 'update'
  721. _edit['curr_value'] = params['curr_value']
  722. _edit['curr_value_format'] = params['curr_value_format']
  723. _edit['index'] = params['index']
  724. elif params['append']:
  725. _edit['action'] = 'append'
  726. edits.append(_edit)
  727. elif params['edits'] is not None:
  728. edits = params['edits']
  729. if edits:
  730. results = Yedit.process_edits(edits, yamlfile)
  731. # if there were changes and a src provided to us we need to write
  732. if results['changed'] and params['src']:
  733. yamlfile.write()
  734. return {'changed': results['changed'], 'result': results['results'], 'state': state}
  735. # no edits to make
  736. if params['src']:
  737. # pylint: disable=redefined-variable-type
  738. rval = yamlfile.write()
  739. return {'changed': rval[0],
  740. 'result': rval[1],
  741. 'state': state}
  742. # We were passed content but no src, key or value, or edits. Return contents in memory
  743. return {'changed': False, 'result': yamlfile.yaml_dict, 'state': state}
  744. return {'failed': True, 'msg': 'Unkown state passed'}
  745. # -*- -*- -*- End included fragment: ../../lib_utils/src/class/yedit.py -*- -*- -*-
  746. # -*- -*- -*- Begin included fragment: lib/base.py -*- -*- -*-
  747. # pylint: disable=too-many-lines
  748. # noqa: E301,E302,E303,T001
  749. class OpenShiftCLIError(Exception):
  750. '''Exception class for openshiftcli'''
  751. pass
  752. ADDITIONAL_PATH_LOOKUPS = ['/usr/local/bin', os.path.expanduser('~/bin')]
  753. def locate_oc_binary():
  754. ''' Find and return oc binary file '''
  755. # https://github.com/openshift/openshift-ansible/issues/3410
  756. # oc can be in /usr/local/bin in some cases, but that may not
  757. # be in $PATH due to ansible/sudo
  758. paths = os.environ.get("PATH", os.defpath).split(os.pathsep) + ADDITIONAL_PATH_LOOKUPS
  759. oc_binary = 'oc'
  760. # Use shutil.which if it is available, otherwise fallback to a naive path search
  761. try:
  762. which_result = shutil.which(oc_binary, path=os.pathsep.join(paths))
  763. if which_result is not None:
  764. oc_binary = which_result
  765. except AttributeError:
  766. for path in paths:
  767. if os.path.exists(os.path.join(path, oc_binary)):
  768. oc_binary = os.path.join(path, oc_binary)
  769. break
  770. return oc_binary
  771. # pylint: disable=too-few-public-methods
  772. class OpenShiftCLI(object):
  773. ''' Class to wrap the command line tools '''
  774. def __init__(self,
  775. namespace,
  776. kubeconfig='/etc/origin/master/admin.kubeconfig',
  777. verbose=False,
  778. all_namespaces=False):
  779. ''' Constructor for OpenshiftCLI '''
  780. self.namespace = namespace
  781. self.verbose = verbose
  782. self.kubeconfig = Utils.create_tmpfile_copy(kubeconfig)
  783. self.all_namespaces = all_namespaces
  784. self.oc_binary = locate_oc_binary()
  785. # Pylint allows only 5 arguments to be passed.
  786. # pylint: disable=too-many-arguments
  787. def _replace_content(self, resource, rname, content, edits=None, force=False, sep='.'):
  788. ''' replace the current object with the content '''
  789. res = self._get(resource, rname)
  790. if not res['results']:
  791. return res
  792. fname = Utils.create_tmpfile(rname + '-')
  793. yed = Yedit(fname, res['results'][0], separator=sep)
  794. updated = False
  795. if content is not None:
  796. changes = []
  797. for key, value in content.items():
  798. changes.append(yed.put(key, value))
  799. if any([change[0] for change in changes]):
  800. updated = True
  801. elif edits is not None:
  802. results = Yedit.process_edits(edits, yed)
  803. if results['changed']:
  804. updated = True
  805. if updated:
  806. yed.write()
  807. atexit.register(Utils.cleanup, [fname])
  808. return self._replace(fname, force)
  809. return {'returncode': 0, 'updated': False}
  810. def _replace(self, fname, force=False):
  811. '''replace the current object with oc replace'''
  812. # We are removing the 'resourceVersion' to handle
  813. # a race condition when modifying oc objects
  814. yed = Yedit(fname)
  815. results = yed.delete('metadata.resourceVersion')
  816. if results[0]:
  817. yed.write()
  818. cmd = ['replace', '-f', fname]
  819. if force:
  820. cmd.append('--force')
  821. return self.openshift_cmd(cmd)
  822. def _create_from_content(self, rname, content):
  823. '''create a temporary file and then call oc create on it'''
  824. fname = Utils.create_tmpfile(rname + '-')
  825. yed = Yedit(fname, content=content)
  826. yed.write()
  827. atexit.register(Utils.cleanup, [fname])
  828. return self._create(fname)
  829. def _create(self, fname):
  830. '''call oc create on a filename'''
  831. return self.openshift_cmd(['create', '-f', fname])
  832. def _delete(self, resource, name=None, selector=None):
  833. '''call oc delete on a resource'''
  834. cmd = ['delete', resource]
  835. if selector is not None:
  836. cmd.append('--selector={}'.format(selector))
  837. elif name is not None:
  838. cmd.append(name)
  839. else:
  840. raise OpenShiftCLIError('Either name or selector is required when calling delete.')
  841. return self.openshift_cmd(cmd)
  842. def _process(self, template_name, create=False, params=None, template_data=None): # noqa: E501
  843. '''process a template
  844. template_name: the name of the template to process
  845. create: whether to send to oc create after processing
  846. params: the parameters for the template
  847. template_data: the incoming template's data; instead of a file
  848. '''
  849. cmd = ['process']
  850. if template_data:
  851. cmd.extend(['-f', '-'])
  852. else:
  853. cmd.append(template_name)
  854. if params:
  855. param_str = ["{}={}".format(key, str(value).replace("'", r'"')) for key, value in params.items()]
  856. cmd.append('-p')
  857. cmd.extend(param_str)
  858. results = self.openshift_cmd(cmd, output=True, input_data=template_data)
  859. if results['returncode'] != 0 or not create:
  860. return results
  861. fname = Utils.create_tmpfile(template_name + '-')
  862. yed = Yedit(fname, results['results'])
  863. yed.write()
  864. atexit.register(Utils.cleanup, [fname])
  865. return self.openshift_cmd(['create', '-f', fname])
  866. def _get(self, resource, name=None, selector=None, field_selector=None):
  867. '''return a resource by name '''
  868. cmd = ['get', resource]
  869. if selector is not None:
  870. cmd.append('--selector={}'.format(selector))
  871. if field_selector is not None:
  872. cmd.append('--field-selector={}'.format(field_selector))
  873. # Name cannot be used with selector or field_selector.
  874. if selector is None and field_selector is None and name is not None:
  875. cmd.append(name)
  876. cmd.extend(['-o', 'json'])
  877. rval = self.openshift_cmd(cmd, output=True)
  878. # Ensure results are retuned in an array
  879. if 'items' in rval:
  880. rval['results'] = rval['items']
  881. elif not isinstance(rval['results'], list):
  882. rval['results'] = [rval['results']]
  883. return rval
  884. def _schedulable(self, node=None, selector=None, schedulable=True):
  885. ''' perform oadm manage-node scheduable '''
  886. cmd = ['manage-node']
  887. if node:
  888. cmd.extend(node)
  889. else:
  890. cmd.append('--selector={}'.format(selector))
  891. cmd.append('--schedulable={}'.format(schedulable))
  892. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw') # noqa: E501
  893. def _list_pods(self, node=None, selector=None, pod_selector=None):
  894. ''' perform oadm list pods
  895. node: the node in which to list pods
  896. selector: the label selector filter if provided
  897. pod_selector: the pod selector filter if provided
  898. '''
  899. cmd = ['manage-node']
  900. if node:
  901. cmd.extend(node)
  902. else:
  903. cmd.append('--selector={}'.format(selector))
  904. if pod_selector:
  905. cmd.append('--pod-selector={}'.format(pod_selector))
  906. cmd.extend(['--list-pods', '-o', 'json'])
  907. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  908. # pylint: disable=too-many-arguments
  909. def _evacuate(self, node=None, selector=None, pod_selector=None, dry_run=False, grace_period=None, force=False):
  910. ''' perform oadm manage-node evacuate '''
  911. cmd = ['manage-node']
  912. if node:
  913. cmd.extend(node)
  914. else:
  915. cmd.append('--selector={}'.format(selector))
  916. if dry_run:
  917. cmd.append('--dry-run')
  918. if pod_selector:
  919. cmd.append('--pod-selector={}'.format(pod_selector))
  920. if grace_period:
  921. cmd.append('--grace-period={}'.format(int(grace_period)))
  922. if force:
  923. cmd.append('--force')
  924. cmd.append('--evacuate')
  925. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  926. def _version(self):
  927. ''' return the openshift version'''
  928. return self.openshift_cmd(['version'], output=True, output_type='raw')
  929. def _import_image(self, url=None, name=None, tag=None):
  930. ''' perform image import '''
  931. cmd = ['import-image']
  932. image = '{0}'.format(name)
  933. if tag:
  934. image += ':{0}'.format(tag)
  935. cmd.append(image)
  936. if url:
  937. cmd.append('--from={0}/{1}'.format(url, image))
  938. cmd.append('-n{0}'.format(self.namespace))
  939. cmd.append('--confirm')
  940. return self.openshift_cmd(cmd)
  941. def _run(self, cmds, input_data):
  942. ''' Actually executes the command. This makes mocking easier. '''
  943. curr_env = os.environ.copy()
  944. curr_env.update({'KUBECONFIG': self.kubeconfig})
  945. proc = subprocess.Popen(cmds,
  946. stdin=subprocess.PIPE,
  947. stdout=subprocess.PIPE,
  948. stderr=subprocess.PIPE,
  949. env=curr_env)
  950. stdout, stderr = proc.communicate(input_data)
  951. return proc.returncode, stdout.decode('utf-8'), stderr.decode('utf-8')
  952. # pylint: disable=too-many-arguments,too-many-branches
  953. def openshift_cmd(self, cmd, oadm=False, output=False, output_type='json', input_data=None):
  954. '''Base command for oc '''
  955. cmds = [self.oc_binary]
  956. if oadm:
  957. cmds.append('adm')
  958. cmds.extend(cmd)
  959. if self.all_namespaces:
  960. cmds.extend(['--all-namespaces'])
  961. elif self.namespace is not None and self.namespace.lower() not in ['none', 'emtpy']: # E501
  962. cmds.extend(['-n', self.namespace])
  963. if self.verbose:
  964. print(' '.join(cmds))
  965. try:
  966. returncode, stdout, stderr = self._run(cmds, input_data)
  967. except OSError as ex:
  968. returncode, stdout, stderr = 1, '', 'Failed to execute {}: {}'.format(subprocess.list2cmdline(cmds), ex)
  969. rval = {"returncode": returncode,
  970. "cmd": ' '.join(cmds)}
  971. if output_type == 'json':
  972. rval['results'] = {}
  973. if output and stdout:
  974. try:
  975. rval['results'] = json.loads(stdout)
  976. except ValueError as verr:
  977. if "No JSON object could be decoded" in verr.args:
  978. rval['err'] = verr.args
  979. elif output_type == 'raw':
  980. rval['results'] = stdout if output else ''
  981. if self.verbose:
  982. print("STDOUT: {0}".format(stdout))
  983. print("STDERR: {0}".format(stderr))
  984. if 'err' in rval or returncode != 0:
  985. rval.update({"stderr": stderr,
  986. "stdout": stdout})
  987. return rval
  988. class Utils(object): # pragma: no cover
  989. ''' utilities for openshiftcli modules '''
  990. @staticmethod
  991. def _write(filename, contents):
  992. ''' Actually write the file contents to disk. This helps with mocking. '''
  993. with open(filename, 'w') as sfd:
  994. sfd.write(str(contents))
  995. @staticmethod
  996. def create_tmp_file_from_contents(rname, data, ftype='yaml'):
  997. ''' create a file in tmp with name and contents'''
  998. tmp = Utils.create_tmpfile(prefix=rname)
  999. if ftype == 'yaml':
  1000. # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage
  1001. # pylint: disable=no-member
  1002. if hasattr(yaml, 'RoundTripDumper'):
  1003. Utils._write(tmp, yaml.dump(data, Dumper=yaml.RoundTripDumper))
  1004. else:
  1005. Utils._write(tmp, yaml.safe_dump(data, default_flow_style=False))
  1006. elif ftype == 'json':
  1007. Utils._write(tmp, json.dumps(data))
  1008. else:
  1009. Utils._write(tmp, data)
  1010. # Register cleanup when module is done
  1011. atexit.register(Utils.cleanup, [tmp])
  1012. return tmp
  1013. @staticmethod
  1014. def create_tmpfile_copy(inc_file):
  1015. '''create a temporary copy of a file'''
  1016. tmpfile = Utils.create_tmpfile('lib_openshift-')
  1017. Utils._write(tmpfile, open(inc_file).read())
  1018. # Cleanup the tmpfile
  1019. atexit.register(Utils.cleanup, [tmpfile])
  1020. return tmpfile
  1021. @staticmethod
  1022. def create_tmpfile(prefix='tmp'):
  1023. ''' Generates and returns a temporary file name '''
  1024. with tempfile.NamedTemporaryFile(prefix=prefix, delete=False) as tmp:
  1025. return tmp.name
  1026. @staticmethod
  1027. def create_tmp_files_from_contents(content, content_type=None):
  1028. '''Turn an array of dict: filename, content into a files array'''
  1029. if not isinstance(content, list):
  1030. content = [content]
  1031. files = []
  1032. for item in content:
  1033. path = Utils.create_tmp_file_from_contents(item['path'] + '-',
  1034. item['data'],
  1035. ftype=content_type)
  1036. files.append({'name': os.path.basename(item['path']),
  1037. 'path': path})
  1038. return files
  1039. @staticmethod
  1040. def cleanup(files):
  1041. '''Clean up on exit '''
  1042. for sfile in files:
  1043. if os.path.exists(sfile):
  1044. if os.path.isdir(sfile):
  1045. shutil.rmtree(sfile)
  1046. elif os.path.isfile(sfile):
  1047. os.remove(sfile)
  1048. @staticmethod
  1049. def exists(results, _name):
  1050. ''' Check to see if the results include the name '''
  1051. if not results:
  1052. return False
  1053. if Utils.find_result(results, _name):
  1054. return True
  1055. return False
  1056. @staticmethod
  1057. def find_result(results, _name):
  1058. ''' Find the specified result by name'''
  1059. rval = None
  1060. for result in results:
  1061. if 'metadata' in result and result['metadata']['name'] == _name:
  1062. rval = result
  1063. break
  1064. return rval
  1065. @staticmethod
  1066. def get_resource_file(sfile, sfile_type='yaml'):
  1067. ''' return the service file '''
  1068. contents = None
  1069. with open(sfile) as sfd:
  1070. contents = sfd.read()
  1071. if sfile_type == 'yaml':
  1072. # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage
  1073. # pylint: disable=no-member
  1074. if hasattr(yaml, 'RoundTripLoader'):
  1075. contents = yaml.load(contents, yaml.RoundTripLoader)
  1076. else:
  1077. contents = yaml.safe_load(contents)
  1078. elif sfile_type == 'json':
  1079. contents = json.loads(contents)
  1080. return contents
  1081. @staticmethod
  1082. def filter_versions(stdout):
  1083. ''' filter the oc version output '''
  1084. version_dict = {}
  1085. version_search = ['oc', 'openshift', 'kubernetes']
  1086. for line in stdout.strip().split('\n'):
  1087. for term in version_search:
  1088. if not line:
  1089. continue
  1090. if line.startswith(term):
  1091. version_dict[term] = line.split()[-1]
  1092. # horrible hack to get openshift version in Openshift 3.2
  1093. # By default "oc version in 3.2 does not return an "openshift" version
  1094. if "openshift" not in version_dict:
  1095. version_dict["openshift"] = version_dict["oc"]
  1096. return version_dict
  1097. @staticmethod
  1098. def add_custom_versions(versions):
  1099. ''' create custom versions strings '''
  1100. versions_dict = {}
  1101. for tech, version in versions.items():
  1102. # clean up "-" from version
  1103. if "-" in version:
  1104. version = version.split("-")[0]
  1105. if version.startswith('v'):
  1106. version = version[1:] # Remove the 'v' prefix
  1107. versions_dict[tech + '_numeric'] = version.split('+')[0]
  1108. # "3.3.0.33" is what we have, we want "3.3"
  1109. versions_dict[tech + '_short'] = "{}.{}".format(*version.split('.'))
  1110. return versions_dict
  1111. @staticmethod
  1112. def openshift_installed():
  1113. ''' check if openshift is installed '''
  1114. import rpm
  1115. transaction_set = rpm.TransactionSet()
  1116. rpmquery = transaction_set.dbMatch("name", "atomic-openshift")
  1117. return rpmquery.count() > 0
  1118. # Disabling too-many-branches. This is a yaml dictionary comparison function
  1119. # pylint: disable=too-many-branches,too-many-return-statements,too-many-statements
  1120. @staticmethod
  1121. def check_def_equal(user_def, result_def, skip_keys=None, debug=False):
  1122. ''' Given a user defined definition, compare it with the results given back by our query. '''
  1123. # Currently these values are autogenerated and we do not need to check them
  1124. skip = ['metadata', 'status']
  1125. if skip_keys:
  1126. skip.extend(skip_keys)
  1127. for key, value in result_def.items():
  1128. if key in skip:
  1129. continue
  1130. # Both are lists
  1131. if isinstance(value, list):
  1132. if key not in user_def:
  1133. if debug:
  1134. print('User data does not have key [%s]' % key)
  1135. print('User data: %s' % user_def)
  1136. return False
  1137. if not isinstance(user_def[key], list):
  1138. if debug:
  1139. print('user_def[key] is not a list key=[%s] user_def[key]=%s' % (key, user_def[key]))
  1140. return False
  1141. if len(user_def[key]) != len(value):
  1142. if debug:
  1143. print("List lengths are not equal.")
  1144. print("key=[%s]: user_def[%s] != value[%s]" % (key, len(user_def[key]), len(value)))
  1145. print("user_def: %s" % user_def[key])
  1146. print("value: %s" % value)
  1147. return False
  1148. for values in zip(user_def[key], value):
  1149. if isinstance(values[0], dict) and isinstance(values[1], dict):
  1150. if debug:
  1151. print('sending list - list')
  1152. print(type(values[0]))
  1153. print(type(values[1]))
  1154. result = Utils.check_def_equal(values[0], values[1], skip_keys=skip_keys, debug=debug)
  1155. if not result:
  1156. print('list compare returned false')
  1157. return False
  1158. elif value != user_def[key]:
  1159. if debug:
  1160. print('value should be identical')
  1161. print(user_def[key])
  1162. print(value)
  1163. return False
  1164. # recurse on a dictionary
  1165. elif isinstance(value, dict):
  1166. if key not in user_def:
  1167. if debug:
  1168. print("user_def does not have key [%s]" % key)
  1169. return False
  1170. if not isinstance(user_def[key], dict):
  1171. if debug:
  1172. print("dict returned false: not instance of dict")
  1173. return False
  1174. # before passing ensure keys match
  1175. api_values = set(value.keys()) - set(skip)
  1176. user_values = set(user_def[key].keys()) - set(skip)
  1177. if api_values != user_values:
  1178. if debug:
  1179. print("keys are not equal in dict")
  1180. print(user_values)
  1181. print(api_values)
  1182. return False
  1183. result = Utils.check_def_equal(user_def[key], value, skip_keys=skip_keys, debug=debug)
  1184. if not result:
  1185. if debug:
  1186. print("dict returned false")
  1187. print(result)
  1188. return False
  1189. # Verify each key, value pair is the same
  1190. else:
  1191. if key not in user_def or value != user_def[key]:
  1192. if debug:
  1193. print("value not equal; user_def does not have key")
  1194. print(key)
  1195. print(value)
  1196. if key in user_def:
  1197. print(user_def[key])
  1198. return False
  1199. if debug:
  1200. print('returning true')
  1201. return True
  1202. class OpenShiftCLIConfig(object):
  1203. '''Generic Config'''
  1204. def __init__(self, rname, namespace, kubeconfig, options):
  1205. self.kubeconfig = kubeconfig
  1206. self.name = rname
  1207. self.namespace = namespace
  1208. self._options = options
  1209. @property
  1210. def config_options(self):
  1211. ''' return config options '''
  1212. return self._options
  1213. def to_option_list(self, ascommalist=''):
  1214. '''return all options as a string
  1215. if ascommalist is set to the name of a key, and
  1216. the value of that key is a dict, format the dict
  1217. as a list of comma delimited key=value pairs'''
  1218. return self.stringify(ascommalist)
  1219. def stringify(self, ascommalist=''):
  1220. ''' return the options hash as cli params in a string
  1221. if ascommalist is set to the name of a key, and
  1222. the value of that key is a dict, format the dict
  1223. as a list of comma delimited key=value pairs '''
  1224. rval = []
  1225. for key in sorted(self.config_options.keys()):
  1226. data = self.config_options[key]
  1227. if data['include'] \
  1228. and (data['value'] is not None or isinstance(data['value'], int)):
  1229. if key == ascommalist:
  1230. val = ','.join(['{}={}'.format(kk, vv) for kk, vv in sorted(data['value'].items())])
  1231. else:
  1232. val = data['value']
  1233. rval.append('--{}={}'.format(key.replace('_', '-'), val))
  1234. return rval
  1235. # -*- -*- -*- End included fragment: lib/base.py -*- -*- -*-
  1236. # -*- -*- -*- Begin included fragment: lib/secret.py -*- -*- -*-
  1237. # pylint: disable=too-many-instance-attributes
  1238. class SecretConfig(object):
  1239. ''' Handle secret options '''
  1240. # pylint: disable=too-many-arguments
  1241. def __init__(self,
  1242. sname,
  1243. namespace,
  1244. kubeconfig,
  1245. secrets=None,
  1246. stype=None,
  1247. annotations=None):
  1248. ''' constructor for handling secret options '''
  1249. self.kubeconfig = kubeconfig
  1250. self.name = sname
  1251. self.type = stype
  1252. self.namespace = namespace
  1253. self.secrets = secrets
  1254. self.annotations = annotations
  1255. self.data = {}
  1256. self.create_dict()
  1257. def create_dict(self):
  1258. ''' assign the correct properties for a secret dict '''
  1259. self.data['apiVersion'] = 'v1'
  1260. self.data['kind'] = 'Secret'
  1261. self.data['type'] = self.type
  1262. self.data['metadata'] = {}
  1263. self.data['metadata']['name'] = self.name
  1264. self.data['metadata']['namespace'] = self.namespace
  1265. self.data['data'] = {}
  1266. if self.secrets:
  1267. for key, value in self.secrets.items():
  1268. self.data['data'][key] = value
  1269. if self.annotations:
  1270. self.data['metadata']['annotations'] = self.annotations
  1271. # pylint: disable=too-many-instance-attributes
  1272. class Secret(Yedit):
  1273. ''' Class to wrap the oc command line tools '''
  1274. secret_path = "data"
  1275. kind = 'secret'
  1276. def __init__(self, content):
  1277. '''secret constructor'''
  1278. super(Secret, self).__init__(content=content)
  1279. self._secrets = None
  1280. @property
  1281. def secrets(self):
  1282. '''secret property getter'''
  1283. if self._secrets is None:
  1284. self._secrets = self.get_secrets()
  1285. return self._secrets
  1286. @secrets.setter
  1287. def secrets(self):
  1288. '''secret property setter'''
  1289. if self._secrets is None:
  1290. self._secrets = self.get_secrets()
  1291. return self._secrets
  1292. def get_secrets(self):
  1293. ''' returns all of the defined secrets '''
  1294. return self.get(Secret.secret_path) or {}
  1295. def add_secret(self, key, value):
  1296. ''' add a secret '''
  1297. if self.secrets:
  1298. self.secrets[key] = value
  1299. else:
  1300. self.put(Secret.secret_path, {key: value})
  1301. return True
  1302. def delete_secret(self, key):
  1303. ''' delete secret'''
  1304. try:
  1305. del self.secrets[key]
  1306. except KeyError as _:
  1307. return False
  1308. return True
  1309. def find_secret(self, key):
  1310. ''' find secret'''
  1311. rval = None
  1312. try:
  1313. rval = self.secrets[key]
  1314. except KeyError as _:
  1315. return None
  1316. return {'key': key, 'value': rval}
  1317. def update_secret(self, key, value):
  1318. ''' update a secret'''
  1319. if key in self.secrets:
  1320. self.secrets[key] = value
  1321. else:
  1322. self.add_secret(key, value)
  1323. return True
  1324. # -*- -*- -*- End included fragment: lib/secret.py -*- -*- -*-
  1325. # -*- -*- -*- Begin included fragment: class/oc_secret.py -*- -*- -*-
  1326. # pylint: disable=wrong-import-position,wrong-import-order
  1327. import base64
  1328. # pylint: disable=too-many-arguments
  1329. class OCSecret(OpenShiftCLI):
  1330. ''' Class to wrap the oc command line tools
  1331. '''
  1332. def __init__(self,
  1333. namespace,
  1334. secret_name=None,
  1335. secret_type=None,
  1336. decode=False,
  1337. kubeconfig='/etc/origin/master/admin.kubeconfig',
  1338. verbose=False):
  1339. ''' Constructor for OpenshiftOC '''
  1340. super(OCSecret, self).__init__(namespace, kubeconfig=kubeconfig, verbose=verbose)
  1341. self.name = secret_name
  1342. self.type = secret_type
  1343. self.decode = decode
  1344. def get(self):
  1345. '''return a secret by name '''
  1346. results = self._get('secrets', self.name)
  1347. results['decoded'] = {}
  1348. results['exists'] = False
  1349. if results['returncode'] == 0 and results['results'][0]:
  1350. results['exists'] = True
  1351. if self.decode:
  1352. if 'data' in results['results'][0]:
  1353. for sname, value in results['results'][0]['data'].items():
  1354. results['decoded'][sname] = base64.b64decode(value)
  1355. if results['returncode'] != 0 and '"%s" not found' % self.name in results['stderr']:
  1356. results['returncode'] = 0
  1357. return results
  1358. def delete(self):
  1359. '''delete a secret by name'''
  1360. return self._delete('secrets', self.name)
  1361. def create(self, files=None, contents=None, force=False):
  1362. '''Create a secret '''
  1363. if not files:
  1364. files = Utils.create_tmp_files_from_contents(contents)
  1365. secrets = ["%s=%s" % (sfile['name'], sfile['path']) for sfile in files]
  1366. cmd = ['secrets', 'new', self.name]
  1367. if self.type is not None:
  1368. cmd.append("--type=%s" % (self.type))
  1369. if force:
  1370. cmd.append('--confirm')
  1371. cmd.extend(secrets)
  1372. results = self.openshift_cmd(cmd)
  1373. return results
  1374. def update(self, files, force=False):
  1375. '''run update secret
  1376. This receives a list of file names and converts it into a secret.
  1377. The secret is then written to disk and passed into the `oc replace` command.
  1378. '''
  1379. secret = self.prep_secret(files, force=force)
  1380. if secret['returncode'] != 0:
  1381. return secret
  1382. sfile_path = '/tmp/%s' % self.name
  1383. with open(sfile_path, 'w') as sfd:
  1384. sfd.write(json.dumps(secret['results']))
  1385. atexit.register(Utils.cleanup, [sfile_path])
  1386. return self._replace(sfile_path, force=force)
  1387. def prep_secret(self, files=None, contents=None, force=False):
  1388. ''' return what the secret would look like if created
  1389. This is accomplished by passing -ojson. This will most likely change in the future
  1390. '''
  1391. if not files:
  1392. files = Utils.create_tmp_files_from_contents(contents)
  1393. secrets = ["%s=%s" % (sfile['name'], sfile['path']) for sfile in files]
  1394. cmd = ['-ojson', 'secrets', 'new', self.name]
  1395. if self.type is not None:
  1396. cmd.extend(["--type=%s" % (self.type)])
  1397. if force:
  1398. cmd.append('--confirm')
  1399. cmd.extend(secrets)
  1400. return self.openshift_cmd(cmd, output=True)
  1401. @staticmethod
  1402. # pylint: disable=too-many-return-statements,too-many-branches
  1403. # TODO: This function should be refactored into its individual parts.
  1404. def run_ansible(params, check_mode):
  1405. '''run the oc_secret module'''
  1406. ocsecret = OCSecret(params['namespace'],
  1407. params['name'],
  1408. params['type'],
  1409. params['decode'],
  1410. kubeconfig=params['kubeconfig'],
  1411. verbose=params['debug'])
  1412. state = params['state']
  1413. api_rval = ocsecret.get()
  1414. #####
  1415. # Get
  1416. #####
  1417. if state == 'list':
  1418. return {'changed': False, 'results': api_rval, state: 'list'}
  1419. if not params['name']:
  1420. return {'failed': True,
  1421. 'msg': 'Please specify a name when state is absent|present.'}
  1422. ########
  1423. # Delete
  1424. ########
  1425. if state == 'absent':
  1426. if not Utils.exists(api_rval['results'], params['name']):
  1427. return {'changed': False, 'state': 'absent'}
  1428. if check_mode:
  1429. return {'changed': True, 'msg': 'Would have performed a delete.'}
  1430. api_rval = ocsecret.delete()
  1431. return {'changed': True, 'results': api_rval, 'state': 'absent'}
  1432. if state == 'present':
  1433. if params['files']:
  1434. files = params['files']
  1435. elif params['contents']:
  1436. files = Utils.create_tmp_files_from_contents(params['contents'])
  1437. else:
  1438. files = [{'name': 'null', 'path': os.devnull}]
  1439. ########
  1440. # Create
  1441. ########
  1442. if not Utils.exists(api_rval['results'], params['name']):
  1443. if check_mode:
  1444. return {'changed': True,
  1445. 'msg': 'Would have performed a create.'}
  1446. api_rval = ocsecret.create(files, params['contents'], force=params['force'])
  1447. # Remove files
  1448. if files and params['delete_after']:
  1449. Utils.cleanup([ftmp['path'] for ftmp in files])
  1450. if api_rval['returncode'] != 0:
  1451. return {'failed': True,
  1452. 'msg': api_rval}
  1453. return {'changed': True,
  1454. 'results': api_rval,
  1455. 'state': 'present'}
  1456. ########
  1457. # Update
  1458. ########
  1459. secret = ocsecret.prep_secret(params['files'], params['contents'], force=params['force'])
  1460. if secret['returncode'] != 0:
  1461. return {'failed': True, 'msg': secret}
  1462. if Utils.check_def_equal(secret['results'], api_rval['results'][0]):
  1463. # Remove files
  1464. if files and params['delete_after']:
  1465. Utils.cleanup([ftmp['path'] for ftmp in files])
  1466. return {'changed': False,
  1467. 'results': secret['results'],
  1468. 'state': 'present'}
  1469. if check_mode:
  1470. return {'changed': True,
  1471. 'msg': 'Would have performed an update.'}
  1472. api_rval = ocsecret.update(files, force=params['force'])
  1473. # Remove files
  1474. if secret and params['delete_after']:
  1475. Utils.cleanup([ftmp['path'] for ftmp in files])
  1476. if api_rval['returncode'] != 0:
  1477. return {'failed': True,
  1478. 'msg': api_rval}
  1479. return {'changed': True,
  1480. 'results': api_rval,
  1481. 'state': 'present'}
  1482. return {'failed': True,
  1483. 'changed': False,
  1484. 'msg': 'Unknown state passed. %s' % state,
  1485. 'state': 'unknown'}
  1486. # -*- -*- -*- End included fragment: class/oc_secret.py -*- -*- -*-
  1487. # -*- -*- -*- Begin included fragment: ansible/oc_secret.py -*- -*- -*-
  1488. def main():
  1489. '''
  1490. ansible oc module for managing OpenShift Secrets
  1491. '''
  1492. module = AnsibleModule(
  1493. argument_spec=dict(
  1494. kubeconfig=dict(default='/etc/origin/master/admin.kubeconfig', type='str'),
  1495. state=dict(default='present', type='str',
  1496. choices=['present', 'absent', 'list']),
  1497. debug=dict(default=False, type='bool'),
  1498. namespace=dict(default='default', type='str'),
  1499. name=dict(default=None, type='str'),
  1500. annotations=dict(default=None, type='dict'),
  1501. type=dict(default=None, type='str'),
  1502. files=dict(default=None, type='list'),
  1503. delete_after=dict(default=False, type='bool'),
  1504. contents=dict(default=None, type='list'),
  1505. force=dict(default=False, type='bool'),
  1506. decode=dict(default=False, type='bool'),
  1507. ),
  1508. mutually_exclusive=[["contents", "files"]],
  1509. supports_check_mode=True,
  1510. )
  1511. rval = OCSecret.run_ansible(module.params, module.check_mode)
  1512. if 'failed' in rval:
  1513. module.fail_json(**rval)
  1514. module.exit_json(**rval)
  1515. if __name__ == '__main__':
  1516. main()
  1517. # -*- -*- -*- End included fragment: ansible/oc_secret.py -*- -*- -*-