oc_secret.py 55 KB

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