oc_secret.py 53 KB

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