oc_adm_ca_server_cert.py 52 KB

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