oc_secret.py 55 KB

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