oc_secret.py 51 KB

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