oadm_ca.py 48 KB

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