oc_adm_ca_server_cert.py 53 KB

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