oc_secret.py 52 KB

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