oc_secret.py 54 KB

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