oc_secret.py 54 KB

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