oadm_ca.py 49 KB

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