oc_adm_ca_server_cert.py 50 KB

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