oc_adm_ca_server_cert.py 52 KB

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