oc_adm_ca_server_cert.py 52 KB

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