oc_adm_ca_server_cert.py 51 KB

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