oc_env.py 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896
  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 collections
  35. import copy
  36. import json
  37. import os
  38. import re
  39. import shutil
  40. import subprocess
  41. import tempfile
  42. # pylint: disable=import-error
  43. try:
  44. import ruamel.yaml as yaml
  45. except ImportError:
  46. import yaml
  47. from ansible.module_utils.basic import AnsibleModule
  48. # -*- -*- -*- End included fragment: lib/import.py -*- -*- -*-
  49. # -*- -*- -*- Begin included fragment: doc/env -*- -*- -*-
  50. DOCUMENTATION = '''
  51. ---
  52. module: oc_env
  53. short_description: Modify, and idempotently manage openshift environment variables on pods, deploymentconfigs, and replication controllers.
  54. description:
  55. - Modify openshift environment variables programmatically.
  56. options:
  57. state:
  58. description:
  59. - Supported states, present, absent, list
  60. - present - will ensure object is created or updated to the value specified
  61. - list - will return a list of environment variables
  62. - absent - will remove the environment varibale from the object
  63. required: False
  64. default: present
  65. choices: ["present", 'absent', 'list']
  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. name:
  80. description:
  81. - Name of the object that is being queried.
  82. required: false
  83. default: None
  84. aliases: []
  85. namespace:
  86. description:
  87. - The namespace where the object lives.
  88. required: false
  89. default: str
  90. aliases: []
  91. kind:
  92. description:
  93. - The kind attribute of the object.
  94. required: False
  95. default: dc
  96. choices:
  97. - rc
  98. - dc
  99. - pods
  100. aliases: []
  101. env_vars:
  102. description:
  103. - The environment variables to insert. The format is a dict of value pairs.
  104. - e.g. {key1: value1, key2: value2})
  105. required: False
  106. default: None
  107. aliases: []
  108. author:
  109. - "Kenny Woodson <kwoodson@redhat.com>"
  110. extends_documentation_fragment: []
  111. '''
  112. EXAMPLES = '''
  113. - name: query a list of env vars on dc
  114. oc_env:
  115. kind: dc
  116. name: myawesomedc
  117. namespace: phpapp
  118. - name: Set the following variables.
  119. oc_env:
  120. kind: dc
  121. name: myawesomedc
  122. namespace: phpapp
  123. env_vars:
  124. SUPER_TURBO_MODE: 'true'
  125. ENABLE_PORTS: 'false'
  126. SERVICE_PORT: 9999
  127. '''
  128. # -*- -*- -*- End included fragment: doc/env -*- -*- -*-
  129. # -*- -*- -*- Begin included fragment: ../../lib_utils/src/class/yedit.py -*- -*- -*-
  130. # pylint: disable=undefined-variable,missing-docstring
  131. # noqa: E301,E302
  132. class YeditException(Exception):
  133. ''' Exception class for Yedit '''
  134. pass
  135. # pylint: disable=too-many-public-methods
  136. class Yedit(object):
  137. ''' Class to modify yaml files '''
  138. re_valid_key = r"(((\[-?\d+\])|([0-9a-zA-Z%s/_-]+)).?)+$"
  139. re_key = r"(?:\[(-?\d+)\])|([0-9a-zA-Z%s/_-]+)"
  140. com_sep = set(['.', '#', '|', ':'])
  141. # pylint: disable=too-many-arguments
  142. def __init__(self,
  143. filename=None,
  144. content=None,
  145. content_type='yaml',
  146. separator='.',
  147. backup=False):
  148. self.content = content
  149. self._separator = separator
  150. self.filename = filename
  151. self.__yaml_dict = content
  152. self.content_type = content_type
  153. self.backup = backup
  154. self.load(content_type=self.content_type)
  155. if self.__yaml_dict is None:
  156. self.__yaml_dict = {}
  157. @property
  158. def separator(self):
  159. ''' getter method for yaml_dict '''
  160. return self._separator
  161. @separator.setter
  162. def separator(self):
  163. ''' getter method for yaml_dict '''
  164. return self._separator
  165. @property
  166. def yaml_dict(self):
  167. ''' getter method for yaml_dict '''
  168. return self.__yaml_dict
  169. @yaml_dict.setter
  170. def yaml_dict(self, value):
  171. ''' setter method for yaml_dict '''
  172. self.__yaml_dict = value
  173. @staticmethod
  174. def parse_key(key, sep='.'):
  175. '''parse the key allowing the appropriate separator'''
  176. common_separators = list(Yedit.com_sep - set([sep]))
  177. return re.findall(Yedit.re_key % ''.join(common_separators), key)
  178. @staticmethod
  179. def valid_key(key, sep='.'):
  180. '''validate the incoming key'''
  181. common_separators = list(Yedit.com_sep - set([sep]))
  182. if not re.match(Yedit.re_valid_key % ''.join(common_separators), key):
  183. return False
  184. return True
  185. @staticmethod
  186. def remove_entry(data, key, sep='.'):
  187. ''' remove data at location key '''
  188. if key == '' and isinstance(data, dict):
  189. data.clear()
  190. return True
  191. elif key == '' and isinstance(data, list):
  192. del data[:]
  193. return True
  194. if not (key and Yedit.valid_key(key, sep)) and \
  195. isinstance(data, (list, dict)):
  196. return None
  197. key_indexes = Yedit.parse_key(key, sep)
  198. for arr_ind, dict_key in key_indexes[:-1]:
  199. if dict_key and isinstance(data, dict):
  200. data = data.get(dict_key, None)
  201. elif (arr_ind and isinstance(data, list) and
  202. int(arr_ind) <= len(data) - 1):
  203. data = data[int(arr_ind)]
  204. else:
  205. return None
  206. # process last index for remove
  207. # expected list entry
  208. if key_indexes[-1][0]:
  209. if isinstance(data, list) and int(key_indexes[-1][0]) <= len(data) - 1: # noqa: E501
  210. del data[int(key_indexes[-1][0])]
  211. return True
  212. # expected dict entry
  213. elif key_indexes[-1][1]:
  214. if isinstance(data, dict):
  215. del data[key_indexes[-1][1]]
  216. return True
  217. @staticmethod
  218. def add_entry(data, key, item=None, sep='.'):
  219. ''' Get an item from a dictionary with key notation a.b.c
  220. d = {'a': {'b': 'c'}}}
  221. key = a#b
  222. return c
  223. '''
  224. if key == '':
  225. pass
  226. elif (not (key and Yedit.valid_key(key, sep)) and
  227. isinstance(data, (list, dict))):
  228. return None
  229. key_indexes = Yedit.parse_key(key, sep)
  230. for arr_ind, dict_key in key_indexes[:-1]:
  231. if dict_key:
  232. if isinstance(data, dict) and dict_key in data and data[dict_key]: # noqa: E501
  233. data = data[dict_key]
  234. continue
  235. elif data and not isinstance(data, dict):
  236. raise YeditException("Unexpected item type found while going through key " +
  237. "path: {} (at key: {})".format(key, dict_key))
  238. data[dict_key] = {}
  239. data = data[dict_key]
  240. elif (arr_ind and isinstance(data, list) and
  241. int(arr_ind) <= len(data) - 1):
  242. data = data[int(arr_ind)]
  243. else:
  244. raise YeditException("Unexpected item type found while going through key path: {}".format(key))
  245. if key == '':
  246. data = item
  247. # process last index for add
  248. # expected list entry
  249. elif key_indexes[-1][0] and isinstance(data, list) and int(key_indexes[-1][0]) <= len(data) - 1: # noqa: E501
  250. data[int(key_indexes[-1][0])] = item
  251. # expected dict entry
  252. elif key_indexes[-1][1] and isinstance(data, dict):
  253. data[key_indexes[-1][1]] = item
  254. # didn't add/update to an existing list, nor add/update key to a dict
  255. # so we must have been provided some syntax like a.b.c[<int>] = "data" for a
  256. # non-existent array
  257. else:
  258. raise YeditException("Error adding to object at path: {}".format(key))
  259. return data
  260. @staticmethod
  261. def get_entry(data, key, sep='.'):
  262. ''' Get an item from a dictionary with key notation a.b.c
  263. d = {'a': {'b': 'c'}}}
  264. key = a.b
  265. return c
  266. '''
  267. if key == '':
  268. pass
  269. elif (not (key and Yedit.valid_key(key, sep)) and
  270. isinstance(data, (list, dict))):
  271. return None
  272. key_indexes = Yedit.parse_key(key, sep)
  273. for arr_ind, dict_key in key_indexes:
  274. if dict_key and isinstance(data, dict):
  275. data = data.get(dict_key, None)
  276. elif (arr_ind and isinstance(data, list) and
  277. int(arr_ind) <= len(data) - 1):
  278. data = data[int(arr_ind)]
  279. else:
  280. return None
  281. return data
  282. @staticmethod
  283. def _write(filename, contents):
  284. ''' Actually write the file contents to disk. This helps with mocking. '''
  285. tmp_filename = filename + '.yedit'
  286. with open(tmp_filename, 'w') as yfd:
  287. yfd.write(contents)
  288. os.rename(tmp_filename, filename)
  289. def write(self):
  290. ''' write to file '''
  291. if not self.filename:
  292. raise YeditException('Please specify a filename.')
  293. if self.backup and self.file_exists():
  294. shutil.copy(self.filename, self.filename + '.orig')
  295. # Try to set format attributes if supported
  296. try:
  297. self.yaml_dict.fa.set_block_style()
  298. except AttributeError:
  299. pass
  300. # Try to use RoundTripDumper if supported.
  301. try:
  302. Yedit._write(self.filename, yaml.dump(self.yaml_dict, Dumper=yaml.RoundTripDumper))
  303. except AttributeError:
  304. Yedit._write(self.filename, yaml.safe_dump(self.yaml_dict, default_flow_style=False))
  305. return (True, self.yaml_dict)
  306. def read(self):
  307. ''' read from file '''
  308. # check if it exists
  309. if self.filename is None or not self.file_exists():
  310. return None
  311. contents = None
  312. with open(self.filename) as yfd:
  313. contents = yfd.read()
  314. return contents
  315. def file_exists(self):
  316. ''' return whether file exists '''
  317. if os.path.exists(self.filename):
  318. return True
  319. return False
  320. def load(self, content_type='yaml'):
  321. ''' return yaml file '''
  322. contents = self.read()
  323. if not contents and not self.content:
  324. return None
  325. if self.content:
  326. if isinstance(self.content, dict):
  327. self.yaml_dict = self.content
  328. return self.yaml_dict
  329. elif isinstance(self.content, str):
  330. contents = self.content
  331. # check if it is yaml
  332. try:
  333. if content_type == 'yaml' and contents:
  334. # Try to set format attributes if supported
  335. try:
  336. self.yaml_dict.fa.set_block_style()
  337. except AttributeError:
  338. pass
  339. # Try to use RoundTripLoader if supported.
  340. try:
  341. self.yaml_dict = yaml.safe_load(contents, yaml.RoundTripLoader)
  342. except AttributeError:
  343. self.yaml_dict = yaml.safe_load(contents)
  344. # Try to set format attributes if supported
  345. try:
  346. self.yaml_dict.fa.set_block_style()
  347. except AttributeError:
  348. pass
  349. elif content_type == 'json' and contents:
  350. self.yaml_dict = json.loads(contents)
  351. except yaml.YAMLError as err:
  352. # Error loading yaml or json
  353. raise YeditException('Problem with loading yaml file. %s' % err)
  354. return self.yaml_dict
  355. def get(self, key):
  356. ''' get a specified key'''
  357. try:
  358. entry = Yedit.get_entry(self.yaml_dict, key, self.separator)
  359. except KeyError:
  360. entry = None
  361. return entry
  362. def pop(self, path, key_or_item):
  363. ''' remove a key, value pair from a dict or an item for a list'''
  364. try:
  365. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  366. except KeyError:
  367. entry = None
  368. if entry is None:
  369. return (False, self.yaml_dict)
  370. if isinstance(entry, dict):
  371. # AUDIT:maybe-no-member makes sense due to fuzzy types
  372. # pylint: disable=maybe-no-member
  373. if key_or_item in entry:
  374. entry.pop(key_or_item)
  375. return (True, self.yaml_dict)
  376. return (False, self.yaml_dict)
  377. elif isinstance(entry, list):
  378. # AUDIT:maybe-no-member makes sense due to fuzzy types
  379. # pylint: disable=maybe-no-member
  380. ind = None
  381. try:
  382. ind = entry.index(key_or_item)
  383. except ValueError:
  384. return (False, self.yaml_dict)
  385. entry.pop(ind)
  386. return (True, self.yaml_dict)
  387. return (False, self.yaml_dict)
  388. def delete(self, path):
  389. ''' remove path from a dict'''
  390. try:
  391. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  392. except KeyError:
  393. entry = None
  394. if entry is None:
  395. return (False, self.yaml_dict)
  396. result = Yedit.remove_entry(self.yaml_dict, path, self.separator)
  397. if not result:
  398. return (False, self.yaml_dict)
  399. return (True, self.yaml_dict)
  400. def exists(self, path, value):
  401. ''' check if value exists at path'''
  402. try:
  403. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  404. except KeyError:
  405. entry = None
  406. if isinstance(entry, list):
  407. if value in entry:
  408. return True
  409. return False
  410. elif isinstance(entry, dict):
  411. if isinstance(value, dict):
  412. rval = False
  413. for key, val in value.items():
  414. if entry[key] != val:
  415. rval = False
  416. break
  417. else:
  418. rval = True
  419. return rval
  420. return value in entry
  421. return entry == value
  422. def append(self, path, value):
  423. '''append value to a list'''
  424. try:
  425. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  426. except KeyError:
  427. entry = None
  428. if entry is None:
  429. self.put(path, [])
  430. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  431. if not isinstance(entry, list):
  432. return (False, self.yaml_dict)
  433. # AUDIT:maybe-no-member makes sense due to loading data from
  434. # a serialized format.
  435. # pylint: disable=maybe-no-member
  436. entry.append(value)
  437. return (True, self.yaml_dict)
  438. # pylint: disable=too-many-arguments
  439. def update(self, path, value, index=None, curr_value=None):
  440. ''' put path, value into a dict '''
  441. try:
  442. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  443. except KeyError:
  444. entry = None
  445. if isinstance(entry, dict):
  446. # AUDIT:maybe-no-member makes sense due to fuzzy types
  447. # pylint: disable=maybe-no-member
  448. if not isinstance(value, dict):
  449. raise YeditException('Cannot replace key, value entry in ' +
  450. 'dict with non-dict type. value=[%s] [%s]' % (value, type(value))) # noqa: E501
  451. entry.update(value)
  452. return (True, self.yaml_dict)
  453. elif isinstance(entry, list):
  454. # AUDIT:maybe-no-member makes sense due to fuzzy types
  455. # pylint: disable=maybe-no-member
  456. ind = None
  457. if curr_value:
  458. try:
  459. ind = entry.index(curr_value)
  460. except ValueError:
  461. return (False, self.yaml_dict)
  462. elif index is not None:
  463. ind = index
  464. if ind is not None and entry[ind] != value:
  465. entry[ind] = value
  466. return (True, self.yaml_dict)
  467. # see if it exists in the list
  468. try:
  469. ind = entry.index(value)
  470. except ValueError:
  471. # doesn't exist, append it
  472. entry.append(value)
  473. return (True, self.yaml_dict)
  474. # already exists, return
  475. if ind is not None:
  476. return (False, self.yaml_dict)
  477. return (False, self.yaml_dict)
  478. def put(self, path, value):
  479. ''' put path, value into a dict '''
  480. try:
  481. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  482. except KeyError:
  483. entry = None
  484. if entry == value:
  485. return (False, self.yaml_dict)
  486. # deepcopy didn't work
  487. # Try to use ruamel.yaml and fallback to pyyaml
  488. try:
  489. tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict,
  490. default_flow_style=False),
  491. yaml.RoundTripLoader)
  492. except AttributeError:
  493. tmp_copy = copy.deepcopy(self.yaml_dict)
  494. # set the format attributes if available
  495. try:
  496. tmp_copy.fa.set_block_style()
  497. except AttributeError:
  498. pass
  499. result = Yedit.add_entry(tmp_copy, path, value, self.separator)
  500. if not result:
  501. return (False, self.yaml_dict)
  502. self.yaml_dict = tmp_copy
  503. return (True, self.yaml_dict)
  504. def create(self, path, value):
  505. ''' create a yaml file '''
  506. if not self.file_exists():
  507. # deepcopy didn't work
  508. # Try to use ruamel.yaml and fallback to pyyaml
  509. try:
  510. tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict,
  511. default_flow_style=False),
  512. yaml.RoundTripLoader)
  513. except AttributeError:
  514. tmp_copy = copy.deepcopy(self.yaml_dict)
  515. # set the format attributes if available
  516. try:
  517. tmp_copy.fa.set_block_style()
  518. except AttributeError:
  519. pass
  520. result = Yedit.add_entry(tmp_copy, path, value, self.separator)
  521. if result:
  522. self.yaml_dict = tmp_copy
  523. return (True, self.yaml_dict)
  524. return (False, self.yaml_dict)
  525. @staticmethod
  526. def get_curr_value(invalue, val_type):
  527. '''return the current value'''
  528. if invalue is None:
  529. return None
  530. curr_value = invalue
  531. if val_type == 'yaml':
  532. curr_value = yaml.load(invalue)
  533. elif val_type == 'json':
  534. curr_value = json.loads(invalue)
  535. return curr_value
  536. @staticmethod
  537. def parse_value(inc_value, vtype=''):
  538. '''determine value type passed'''
  539. true_bools = ['y', 'Y', 'yes', 'Yes', 'YES', 'true', 'True', 'TRUE',
  540. 'on', 'On', 'ON', ]
  541. false_bools = ['n', 'N', 'no', 'No', 'NO', 'false', 'False', 'FALSE',
  542. 'off', 'Off', 'OFF']
  543. # It came in as a string but you didn't specify value_type as string
  544. # we will convert to bool if it matches any of the above cases
  545. if isinstance(inc_value, str) and 'bool' in vtype:
  546. if inc_value not in true_bools and inc_value not in false_bools:
  547. raise YeditException('Not a boolean type. str=[%s] vtype=[%s]'
  548. % (inc_value, vtype))
  549. elif isinstance(inc_value, bool) and 'str' in vtype:
  550. inc_value = str(inc_value)
  551. # If vtype is not str then go ahead and attempt to yaml load it.
  552. if isinstance(inc_value, str) and 'str' not in vtype:
  553. try:
  554. inc_value = yaml.load(inc_value)
  555. except Exception:
  556. raise YeditException('Could not determine type of incoming ' +
  557. 'value. value=[%s] vtype=[%s]'
  558. % (type(inc_value), vtype))
  559. return inc_value
  560. # pylint: disable=too-many-return-statements,too-many-branches
  561. @staticmethod
  562. def run_ansible(module):
  563. '''perform the idempotent crud operations'''
  564. yamlfile = Yedit(filename=module.params['src'],
  565. backup=module.params['backup'],
  566. separator=module.params['separator'])
  567. if module.params['src']:
  568. rval = yamlfile.load()
  569. if yamlfile.yaml_dict is None and \
  570. module.params['state'] != 'present':
  571. return {'failed': True,
  572. 'msg': 'Error opening file [%s]. Verify that the ' +
  573. 'file exists, that it is has correct' +
  574. ' permissions, and is valid yaml.'}
  575. if module.params['state'] == 'list':
  576. if module.params['content']:
  577. content = Yedit.parse_value(module.params['content'],
  578. module.params['content_type'])
  579. yamlfile.yaml_dict = content
  580. if module.params['key']:
  581. rval = yamlfile.get(module.params['key']) or {}
  582. return {'changed': False, 'result': rval, 'state': "list"}
  583. elif module.params['state'] == 'absent':
  584. if module.params['content']:
  585. content = Yedit.parse_value(module.params['content'],
  586. module.params['content_type'])
  587. yamlfile.yaml_dict = content
  588. if module.params['update']:
  589. rval = yamlfile.pop(module.params['key'],
  590. module.params['value'])
  591. else:
  592. rval = yamlfile.delete(module.params['key'])
  593. if rval[0] and module.params['src']:
  594. yamlfile.write()
  595. return {'changed': rval[0], 'result': rval[1], 'state': "absent"}
  596. elif module.params['state'] == 'present':
  597. # check if content is different than what is in the file
  598. if module.params['content']:
  599. content = Yedit.parse_value(module.params['content'],
  600. module.params['content_type'])
  601. # We had no edits to make and the contents are the same
  602. if yamlfile.yaml_dict == content and \
  603. module.params['value'] is None:
  604. return {'changed': False,
  605. 'result': yamlfile.yaml_dict,
  606. 'state': "present"}
  607. yamlfile.yaml_dict = content
  608. # we were passed a value; parse it
  609. if module.params['value']:
  610. value = Yedit.parse_value(module.params['value'],
  611. module.params['value_type'])
  612. key = module.params['key']
  613. if module.params['update']:
  614. # pylint: disable=line-too-long
  615. curr_value = Yedit.get_curr_value(Yedit.parse_value(module.params['curr_value']), # noqa: E501
  616. module.params['curr_value_format']) # noqa: E501
  617. rval = yamlfile.update(key, value, module.params['index'], curr_value) # noqa: E501
  618. elif module.params['append']:
  619. rval = yamlfile.append(key, value)
  620. else:
  621. rval = yamlfile.put(key, value)
  622. if rval[0] and module.params['src']:
  623. yamlfile.write()
  624. return {'changed': rval[0],
  625. 'result': rval[1], 'state': "present"}
  626. # no edits to make
  627. if module.params['src']:
  628. # pylint: disable=redefined-variable-type
  629. rval = yamlfile.write()
  630. return {'changed': rval[0],
  631. 'result': rval[1],
  632. 'state': "present"}
  633. return {'failed': True, 'msg': 'Unkown state passed'}
  634. # -*- -*- -*- End included fragment: ../../lib_utils/src/class/yedit.py -*- -*- -*-
  635. # -*- -*- -*- Begin included fragment: lib/base.py -*- -*- -*-
  636. # pylint: disable=too-many-lines
  637. # noqa: E301,E302,E303,T001
  638. class OpenShiftCLIError(Exception):
  639. '''Exception class for openshiftcli'''
  640. pass
  641. ADDITIONAL_PATH_LOOKUPS = ['/usr/local/bin', os.path.expanduser('~/bin')]
  642. def locate_oc_binary():
  643. ''' Find and return oc binary file '''
  644. # https://github.com/openshift/openshift-ansible/issues/3410
  645. # oc can be in /usr/local/bin in some cases, but that may not
  646. # be in $PATH due to ansible/sudo
  647. paths = os.environ.get("PATH", os.defpath).split(os.pathsep) + ADDITIONAL_PATH_LOOKUPS
  648. oc_binary = 'oc'
  649. # Use shutil.which if it is available, otherwise fallback to a naive path search
  650. try:
  651. which_result = shutil.which(oc_binary, path=os.pathsep.join(paths))
  652. if which_result is not None:
  653. oc_binary = which_result
  654. except AttributeError:
  655. for path in paths:
  656. if os.path.exists(os.path.join(path, oc_binary)):
  657. oc_binary = os.path.join(path, oc_binary)
  658. break
  659. return oc_binary
  660. # pylint: disable=too-few-public-methods
  661. class OpenShiftCLI(object):
  662. ''' Class to wrap the command line tools '''
  663. def __init__(self,
  664. namespace,
  665. kubeconfig='/etc/origin/master/admin.kubeconfig',
  666. verbose=False,
  667. all_namespaces=False):
  668. ''' Constructor for OpenshiftCLI '''
  669. self.namespace = namespace
  670. self.verbose = verbose
  671. self.kubeconfig = Utils.create_tmpfile_copy(kubeconfig)
  672. self.all_namespaces = all_namespaces
  673. self.oc_binary = locate_oc_binary()
  674. # Pylint allows only 5 arguments to be passed.
  675. # pylint: disable=too-many-arguments
  676. def _replace_content(self, resource, rname, content, force=False, sep='.'):
  677. ''' replace the current object with the content '''
  678. res = self._get(resource, rname)
  679. if not res['results']:
  680. return res
  681. fname = Utils.create_tmpfile(rname + '-')
  682. yed = Yedit(fname, res['results'][0], separator=sep)
  683. changes = []
  684. for key, value in content.items():
  685. changes.append(yed.put(key, value))
  686. if any([change[0] for change in changes]):
  687. yed.write()
  688. atexit.register(Utils.cleanup, [fname])
  689. return self._replace(fname, force)
  690. return {'returncode': 0, 'updated': False}
  691. def _replace(self, fname, force=False):
  692. '''replace the current object with oc replace'''
  693. cmd = ['replace', '-f', fname]
  694. if force:
  695. cmd.append('--force')
  696. return self.openshift_cmd(cmd)
  697. def _create_from_content(self, rname, content):
  698. '''create a temporary file and then call oc create on it'''
  699. fname = Utils.create_tmpfile(rname + '-')
  700. yed = Yedit(fname, content=content)
  701. yed.write()
  702. atexit.register(Utils.cleanup, [fname])
  703. return self._create(fname)
  704. def _create(self, fname):
  705. '''call oc create on a filename'''
  706. return self.openshift_cmd(['create', '-f', fname])
  707. def _delete(self, resource, rname, selector=None):
  708. '''call oc delete on a resource'''
  709. cmd = ['delete', resource, rname]
  710. if selector:
  711. cmd.append('--selector=%s' % selector)
  712. return self.openshift_cmd(cmd)
  713. def _process(self, template_name, create=False, params=None, template_data=None): # noqa: E501
  714. '''process a template
  715. template_name: the name of the template to process
  716. create: whether to send to oc create after processing
  717. params: the parameters for the template
  718. template_data: the incoming template's data; instead of a file
  719. '''
  720. cmd = ['process']
  721. if template_data:
  722. cmd.extend(['-f', '-'])
  723. else:
  724. cmd.append(template_name)
  725. if params:
  726. param_str = ["%s=%s" % (key, value) for key, value in params.items()]
  727. cmd.append('-v')
  728. cmd.extend(param_str)
  729. results = self.openshift_cmd(cmd, output=True, input_data=template_data)
  730. if results['returncode'] != 0 or not create:
  731. return results
  732. fname = Utils.create_tmpfile(template_name + '-')
  733. yed = Yedit(fname, results['results'])
  734. yed.write()
  735. atexit.register(Utils.cleanup, [fname])
  736. return self.openshift_cmd(['create', '-f', fname])
  737. def _get(self, resource, rname=None, selector=None):
  738. '''return a resource by name '''
  739. cmd = ['get', resource]
  740. if selector:
  741. cmd.append('--selector=%s' % selector)
  742. elif rname:
  743. cmd.append(rname)
  744. cmd.extend(['-o', 'json'])
  745. rval = self.openshift_cmd(cmd, output=True)
  746. # Ensure results are retuned in an array
  747. if 'items' in rval:
  748. rval['results'] = rval['items']
  749. elif not isinstance(rval['results'], list):
  750. rval['results'] = [rval['results']]
  751. return rval
  752. def _schedulable(self, node=None, selector=None, schedulable=True):
  753. ''' perform oadm manage-node scheduable '''
  754. cmd = ['manage-node']
  755. if node:
  756. cmd.extend(node)
  757. else:
  758. cmd.append('--selector=%s' % selector)
  759. cmd.append('--schedulable=%s' % schedulable)
  760. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw') # noqa: E501
  761. def _list_pods(self, node=None, selector=None, pod_selector=None):
  762. ''' perform oadm list pods
  763. node: the node in which to list pods
  764. selector: the label selector filter if provided
  765. pod_selector: the pod selector filter if provided
  766. '''
  767. cmd = ['manage-node']
  768. if node:
  769. cmd.extend(node)
  770. else:
  771. cmd.append('--selector=%s' % selector)
  772. if pod_selector:
  773. cmd.append('--pod-selector=%s' % pod_selector)
  774. cmd.extend(['--list-pods', '-o', 'json'])
  775. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  776. # pylint: disable=too-many-arguments
  777. def _evacuate(self, node=None, selector=None, pod_selector=None, dry_run=False, grace_period=None, force=False):
  778. ''' perform oadm manage-node evacuate '''
  779. cmd = ['manage-node']
  780. if node:
  781. cmd.extend(node)
  782. else:
  783. cmd.append('--selector=%s' % selector)
  784. if dry_run:
  785. cmd.append('--dry-run')
  786. if pod_selector:
  787. cmd.append('--pod-selector=%s' % pod_selector)
  788. if grace_period:
  789. cmd.append('--grace-period=%s' % int(grace_period))
  790. if force:
  791. cmd.append('--force')
  792. cmd.append('--evacuate')
  793. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  794. def _version(self):
  795. ''' return the openshift version'''
  796. return self.openshift_cmd(['version'], output=True, output_type='raw')
  797. def _import_image(self, url=None, name=None, tag=None):
  798. ''' perform image import '''
  799. cmd = ['import-image']
  800. image = '{0}'.format(name)
  801. if tag:
  802. image += ':{0}'.format(tag)
  803. cmd.append(image)
  804. if url:
  805. cmd.append('--from={0}/{1}'.format(url, image))
  806. cmd.append('-n{0}'.format(self.namespace))
  807. cmd.append('--confirm')
  808. return self.openshift_cmd(cmd)
  809. def _run(self, cmds, input_data):
  810. ''' Actually executes the command. This makes mocking easier. '''
  811. curr_env = os.environ.copy()
  812. curr_env.update({'KUBECONFIG': self.kubeconfig})
  813. proc = subprocess.Popen(cmds,
  814. stdin=subprocess.PIPE,
  815. stdout=subprocess.PIPE,
  816. stderr=subprocess.PIPE,
  817. env=curr_env)
  818. stdout, stderr = proc.communicate(input_data)
  819. return proc.returncode, stdout.decode(), stderr.decode()
  820. # pylint: disable=too-many-arguments,too-many-branches
  821. def openshift_cmd(self, cmd, oadm=False, output=False, output_type='json', input_data=None):
  822. '''Base command for oc '''
  823. cmds = [self.oc_binary]
  824. if oadm:
  825. cmds.append('adm')
  826. cmds.extend(cmd)
  827. if self.all_namespaces:
  828. cmds.extend(['--all-namespaces'])
  829. elif self.namespace is not None and self.namespace.lower() not in ['none', 'emtpy']: # E501
  830. cmds.extend(['-n', self.namespace])
  831. rval = {}
  832. results = ''
  833. err = None
  834. if self.verbose:
  835. print(' '.join(cmds))
  836. try:
  837. returncode, stdout, stderr = self._run(cmds, input_data)
  838. except OSError as ex:
  839. returncode, stdout, stderr = 1, '', 'Failed to execute {}: {}'.format(subprocess.list2cmdline(cmds), ex)
  840. rval = {"returncode": returncode,
  841. "results": results,
  842. "cmd": ' '.join(cmds)}
  843. if returncode == 0:
  844. if output:
  845. if output_type == 'json':
  846. try:
  847. rval['results'] = json.loads(stdout)
  848. except ValueError as err:
  849. if "No JSON object could be decoded" in err.args:
  850. err = err.args
  851. elif output_type == 'raw':
  852. rval['results'] = stdout
  853. if self.verbose:
  854. print("STDOUT: {0}".format(stdout))
  855. print("STDERR: {0}".format(stderr))
  856. if err:
  857. rval.update({"err": err,
  858. "stderr": stderr,
  859. "stdout": stdout,
  860. "cmd": cmds})
  861. else:
  862. rval.update({"stderr": stderr,
  863. "stdout": stdout,
  864. "results": {}})
  865. return rval
  866. class Utils(object):
  867. ''' utilities for openshiftcli modules '''
  868. @staticmethod
  869. def _write(filename, contents):
  870. ''' Actually write the file contents to disk. This helps with mocking. '''
  871. with open(filename, 'w') as sfd:
  872. sfd.write(contents)
  873. @staticmethod
  874. def create_tmp_file_from_contents(rname, data, ftype='yaml'):
  875. ''' create a file in tmp with name and contents'''
  876. tmp = Utils.create_tmpfile(prefix=rname)
  877. if ftype == 'yaml':
  878. # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage
  879. # pylint: disable=no-member
  880. if hasattr(yaml, 'RoundTripDumper'):
  881. Utils._write(tmp, yaml.dump(data, Dumper=yaml.RoundTripDumper))
  882. else:
  883. Utils._write(tmp, yaml.safe_dump(data, default_flow_style=False))
  884. elif ftype == 'json':
  885. Utils._write(tmp, json.dumps(data))
  886. else:
  887. Utils._write(tmp, data)
  888. # Register cleanup when module is done
  889. atexit.register(Utils.cleanup, [tmp])
  890. return tmp
  891. @staticmethod
  892. def create_tmpfile_copy(inc_file):
  893. '''create a temporary copy of a file'''
  894. tmpfile = Utils.create_tmpfile('lib_openshift-')
  895. Utils._write(tmpfile, open(inc_file).read())
  896. # Cleanup the tmpfile
  897. atexit.register(Utils.cleanup, [tmpfile])
  898. return tmpfile
  899. @staticmethod
  900. def create_tmpfile(prefix='tmp'):
  901. ''' Generates and returns a temporary file name '''
  902. with tempfile.NamedTemporaryFile(prefix=prefix, delete=False) as tmp:
  903. return tmp.name
  904. @staticmethod
  905. def create_tmp_files_from_contents(content, content_type=None):
  906. '''Turn an array of dict: filename, content into a files array'''
  907. if not isinstance(content, list):
  908. content = [content]
  909. files = []
  910. for item in content:
  911. path = Utils.create_tmp_file_from_contents(item['path'] + '-',
  912. item['data'],
  913. ftype=content_type)
  914. files.append({'name': os.path.basename(item['path']),
  915. 'path': path})
  916. return files
  917. @staticmethod
  918. def cleanup(files):
  919. '''Clean up on exit '''
  920. for sfile in files:
  921. if os.path.exists(sfile):
  922. if os.path.isdir(sfile):
  923. shutil.rmtree(sfile)
  924. elif os.path.isfile(sfile):
  925. os.remove(sfile)
  926. @staticmethod
  927. def exists(results, _name):
  928. ''' Check to see if the results include the name '''
  929. if not results:
  930. return False
  931. if Utils.find_result(results, _name):
  932. return True
  933. return False
  934. @staticmethod
  935. def find_result(results, _name):
  936. ''' Find the specified result by name'''
  937. rval = None
  938. for result in results:
  939. if 'metadata' in result and result['metadata']['name'] == _name:
  940. rval = result
  941. break
  942. return rval
  943. @staticmethod
  944. def get_resource_file(sfile, sfile_type='yaml'):
  945. ''' return the service file '''
  946. contents = None
  947. with open(sfile) as sfd:
  948. contents = sfd.read()
  949. if sfile_type == 'yaml':
  950. # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage
  951. # pylint: disable=no-member
  952. if hasattr(yaml, 'RoundTripLoader'):
  953. contents = yaml.load(contents, yaml.RoundTripLoader)
  954. else:
  955. contents = yaml.safe_load(contents)
  956. elif sfile_type == 'json':
  957. contents = json.loads(contents)
  958. return contents
  959. @staticmethod
  960. def filter_versions(stdout):
  961. ''' filter the oc version output '''
  962. version_dict = {}
  963. version_search = ['oc', 'openshift', 'kubernetes']
  964. for line in stdout.strip().split('\n'):
  965. for term in version_search:
  966. if not line:
  967. continue
  968. if line.startswith(term):
  969. version_dict[term] = line.split()[-1]
  970. # horrible hack to get openshift version in Openshift 3.2
  971. # By default "oc version in 3.2 does not return an "openshift" version
  972. if "openshift" not in version_dict:
  973. version_dict["openshift"] = version_dict["oc"]
  974. return version_dict
  975. @staticmethod
  976. def add_custom_versions(versions):
  977. ''' create custom versions strings '''
  978. versions_dict = {}
  979. for tech, version in versions.items():
  980. # clean up "-" from version
  981. if "-" in version:
  982. version = version.split("-")[0]
  983. if version.startswith('v'):
  984. versions_dict[tech + '_numeric'] = version[1:].split('+')[0]
  985. # "v3.3.0.33" is what we have, we want "3.3"
  986. versions_dict[tech + '_short'] = version[1:4]
  987. return versions_dict
  988. @staticmethod
  989. def openshift_installed():
  990. ''' check if openshift is installed '''
  991. import yum
  992. yum_base = yum.YumBase()
  993. if yum_base.rpmdb.searchNevra(name='atomic-openshift'):
  994. return True
  995. return False
  996. # Disabling too-many-branches. This is a yaml dictionary comparison function
  997. # pylint: disable=too-many-branches,too-many-return-statements,too-many-statements
  998. @staticmethod
  999. def check_def_equal(user_def, result_def, skip_keys=None, debug=False):
  1000. ''' Given a user defined definition, compare it with the results given back by our query. '''
  1001. # Currently these values are autogenerated and we do not need to check them
  1002. skip = ['metadata', 'status']
  1003. if skip_keys:
  1004. skip.extend(skip_keys)
  1005. for key, value in result_def.items():
  1006. if key in skip:
  1007. continue
  1008. # Both are lists
  1009. if isinstance(value, list):
  1010. if key not in user_def:
  1011. if debug:
  1012. print('User data does not have key [%s]' % key)
  1013. print('User data: %s' % user_def)
  1014. return False
  1015. if not isinstance(user_def[key], list):
  1016. if debug:
  1017. print('user_def[key] is not a list key=[%s] user_def[key]=%s' % (key, user_def[key]))
  1018. return False
  1019. if len(user_def[key]) != len(value):
  1020. if debug:
  1021. print("List lengths are not equal.")
  1022. print("key=[%s]: user_def[%s] != value[%s]" % (key, len(user_def[key]), len(value)))
  1023. print("user_def: %s" % user_def[key])
  1024. print("value: %s" % value)
  1025. return False
  1026. for values in zip(user_def[key], value):
  1027. if isinstance(values[0], dict) and isinstance(values[1], dict):
  1028. if debug:
  1029. print('sending list - list')
  1030. print(type(values[0]))
  1031. print(type(values[1]))
  1032. result = Utils.check_def_equal(values[0], values[1], skip_keys=skip_keys, debug=debug)
  1033. if not result:
  1034. print('list compare returned false')
  1035. return False
  1036. elif value != user_def[key]:
  1037. if debug:
  1038. print('value should be identical')
  1039. print(user_def[key])
  1040. print(value)
  1041. return False
  1042. # recurse on a dictionary
  1043. elif isinstance(value, dict):
  1044. if key not in user_def:
  1045. if debug:
  1046. print("user_def does not have key [%s]" % key)
  1047. return False
  1048. if not isinstance(user_def[key], dict):
  1049. if debug:
  1050. print("dict returned false: not instance of dict")
  1051. return False
  1052. # before passing ensure keys match
  1053. api_values = set(value.keys()) - set(skip)
  1054. user_values = set(user_def[key].keys()) - set(skip)
  1055. if api_values != user_values:
  1056. if debug:
  1057. print("keys are not equal in dict")
  1058. print(user_values)
  1059. print(api_values)
  1060. return False
  1061. result = Utils.check_def_equal(user_def[key], value, skip_keys=skip_keys, debug=debug)
  1062. if not result:
  1063. if debug:
  1064. print("dict returned false")
  1065. print(result)
  1066. return False
  1067. # Verify each key, value pair is the same
  1068. else:
  1069. if key not in user_def or value != user_def[key]:
  1070. if debug:
  1071. print("value not equal; user_def does not have key")
  1072. print(key)
  1073. print(value)
  1074. if key in user_def:
  1075. print(user_def[key])
  1076. return False
  1077. if debug:
  1078. print('returning true')
  1079. return True
  1080. class OpenShiftCLIConfig(object):
  1081. '''Generic Config'''
  1082. def __init__(self, rname, namespace, kubeconfig, options):
  1083. self.kubeconfig = kubeconfig
  1084. self.name = rname
  1085. self.namespace = namespace
  1086. self._options = collections.OrderedDict(options)
  1087. @property
  1088. def config_options(self):
  1089. ''' return config options '''
  1090. return self._options
  1091. def to_option_list(self):
  1092. '''return all options as a string'''
  1093. return self.stringify()
  1094. def stringify(self):
  1095. ''' return the options hash as cli params in a string '''
  1096. rval = []
  1097. for key, data in self.config_options.items():
  1098. if data['include'] \
  1099. and (data['value'] or isinstance(data['value'], int)):
  1100. rval.append('--%s=%s' % (key.replace('_', '-'), data['value']))
  1101. return rval
  1102. # -*- -*- -*- End included fragment: lib/base.py -*- -*- -*-
  1103. # -*- -*- -*- Begin included fragment: lib/deploymentconfig.py -*- -*- -*-
  1104. # pylint: disable=too-many-public-methods
  1105. class DeploymentConfig(Yedit):
  1106. ''' Class to model an openshift DeploymentConfig'''
  1107. default_deployment_config = '''
  1108. apiVersion: v1
  1109. kind: DeploymentConfig
  1110. metadata:
  1111. name: default_dc
  1112. namespace: default
  1113. spec:
  1114. replicas: 0
  1115. selector:
  1116. default_dc: default_dc
  1117. strategy:
  1118. resources: {}
  1119. rollingParams:
  1120. intervalSeconds: 1
  1121. maxSurge: 0
  1122. maxUnavailable: 25%
  1123. timeoutSeconds: 600
  1124. updatePercent: -25
  1125. updatePeriodSeconds: 1
  1126. type: Rolling
  1127. template:
  1128. metadata:
  1129. spec:
  1130. containers:
  1131. - env:
  1132. - name: default
  1133. value: default
  1134. image: default
  1135. imagePullPolicy: IfNotPresent
  1136. name: default_dc
  1137. ports:
  1138. - containerPort: 8000
  1139. hostPort: 8000
  1140. protocol: TCP
  1141. name: default_port
  1142. resources: {}
  1143. terminationMessagePath: /dev/termination-log
  1144. dnsPolicy: ClusterFirst
  1145. hostNetwork: true
  1146. nodeSelector:
  1147. type: compute
  1148. restartPolicy: Always
  1149. securityContext: {}
  1150. serviceAccount: default
  1151. serviceAccountName: default
  1152. terminationGracePeriodSeconds: 30
  1153. triggers:
  1154. - type: ConfigChange
  1155. '''
  1156. replicas_path = "spec.replicas"
  1157. env_path = "spec.template.spec.containers[0].env"
  1158. volumes_path = "spec.template.spec.volumes"
  1159. container_path = "spec.template.spec.containers"
  1160. volume_mounts_path = "spec.template.spec.containers[0].volumeMounts"
  1161. def __init__(self, content=None):
  1162. ''' Constructor for deploymentconfig '''
  1163. if not content:
  1164. content = DeploymentConfig.default_deployment_config
  1165. super(DeploymentConfig, self).__init__(content=content)
  1166. def add_env_value(self, key, value):
  1167. ''' add key, value pair to env array '''
  1168. rval = False
  1169. env = self.get_env_vars()
  1170. if env:
  1171. env.append({'name': key, 'value': value})
  1172. rval = True
  1173. else:
  1174. result = self.put(DeploymentConfig.env_path, {'name': key, 'value': value})
  1175. rval = result[0]
  1176. return rval
  1177. def exists_env_value(self, key, value):
  1178. ''' return whether a key, value pair exists '''
  1179. results = self.get_env_vars()
  1180. if not results:
  1181. return False
  1182. for result in results:
  1183. if result['name'] == key and result['value'] == value:
  1184. return True
  1185. return False
  1186. def exists_env_key(self, key):
  1187. ''' return whether a key, value pair exists '''
  1188. results = self.get_env_vars()
  1189. if not results:
  1190. return False
  1191. for result in results:
  1192. if result['name'] == key:
  1193. return True
  1194. return False
  1195. def get_env_var(self, key):
  1196. '''return a environment variables '''
  1197. results = self.get(DeploymentConfig.env_path) or []
  1198. if not results:
  1199. return None
  1200. for env_var in results:
  1201. if env_var['name'] == key:
  1202. return env_var
  1203. return None
  1204. def get_env_vars(self):
  1205. '''return a environment variables '''
  1206. return self.get(DeploymentConfig.env_path) or []
  1207. def delete_env_var(self, keys):
  1208. '''delete a list of keys '''
  1209. if not isinstance(keys, list):
  1210. keys = [keys]
  1211. env_vars_array = self.get_env_vars()
  1212. modified = False
  1213. idx = None
  1214. for key in keys:
  1215. for env_idx, env_var in enumerate(env_vars_array):
  1216. if env_var['name'] == key:
  1217. idx = env_idx
  1218. break
  1219. if idx:
  1220. modified = True
  1221. del env_vars_array[idx]
  1222. if modified:
  1223. return True
  1224. return False
  1225. def update_env_var(self, key, value):
  1226. '''place an env in the env var list'''
  1227. env_vars_array = self.get_env_vars()
  1228. idx = None
  1229. for env_idx, env_var in enumerate(env_vars_array):
  1230. if env_var['name'] == key:
  1231. idx = env_idx
  1232. break
  1233. if idx:
  1234. env_vars_array[idx]['value'] = value
  1235. else:
  1236. self.add_env_value(key, value)
  1237. return True
  1238. def exists_volume_mount(self, volume_mount):
  1239. ''' return whether a volume mount exists '''
  1240. exist_volume_mounts = self.get_volume_mounts()
  1241. if not exist_volume_mounts:
  1242. return False
  1243. volume_mount_found = False
  1244. for exist_volume_mount in exist_volume_mounts:
  1245. if exist_volume_mount['name'] == volume_mount['name']:
  1246. volume_mount_found = True
  1247. break
  1248. return volume_mount_found
  1249. def exists_volume(self, volume):
  1250. ''' return whether a volume exists '''
  1251. exist_volumes = self.get_volumes()
  1252. volume_found = False
  1253. for exist_volume in exist_volumes:
  1254. if exist_volume['name'] == volume['name']:
  1255. volume_found = True
  1256. break
  1257. return volume_found
  1258. def find_volume_by_name(self, volume, mounts=False):
  1259. ''' return the index of a volume '''
  1260. volumes = []
  1261. if mounts:
  1262. volumes = self.get_volume_mounts()
  1263. else:
  1264. volumes = self.get_volumes()
  1265. for exist_volume in volumes:
  1266. if exist_volume['name'] == volume['name']:
  1267. return exist_volume
  1268. return None
  1269. def get_replicas(self):
  1270. ''' return replicas setting '''
  1271. return self.get(DeploymentConfig.replicas_path)
  1272. def get_volume_mounts(self):
  1273. '''return volume mount information '''
  1274. return self.get_volumes(mounts=True)
  1275. def get_volumes(self, mounts=False):
  1276. '''return volume mount information '''
  1277. if mounts:
  1278. return self.get(DeploymentConfig.volume_mounts_path) or []
  1279. return self.get(DeploymentConfig.volumes_path) or []
  1280. def delete_volume_by_name(self, volume):
  1281. '''delete a volume '''
  1282. modified = False
  1283. exist_volume_mounts = self.get_volume_mounts()
  1284. exist_volumes = self.get_volumes()
  1285. del_idx = None
  1286. for idx, exist_volume in enumerate(exist_volumes):
  1287. if 'name' in exist_volume and exist_volume['name'] == volume['name']:
  1288. del_idx = idx
  1289. break
  1290. if del_idx != None:
  1291. del exist_volumes[del_idx]
  1292. modified = True
  1293. del_idx = None
  1294. for idx, exist_volume_mount in enumerate(exist_volume_mounts):
  1295. if 'name' in exist_volume_mount and exist_volume_mount['name'] == volume['name']:
  1296. del_idx = idx
  1297. break
  1298. if del_idx != None:
  1299. del exist_volume_mounts[idx]
  1300. modified = True
  1301. return modified
  1302. def add_volume_mount(self, volume_mount):
  1303. ''' add a volume or volume mount to the proper location '''
  1304. exist_volume_mounts = self.get_volume_mounts()
  1305. if not exist_volume_mounts and volume_mount:
  1306. self.put(DeploymentConfig.volume_mounts_path, [volume_mount])
  1307. else:
  1308. exist_volume_mounts.append(volume_mount)
  1309. def add_volume(self, volume):
  1310. ''' add a volume or volume mount to the proper location '''
  1311. exist_volumes = self.get_volumes()
  1312. if not volume:
  1313. return
  1314. if not exist_volumes:
  1315. self.put(DeploymentConfig.volumes_path, [volume])
  1316. else:
  1317. exist_volumes.append(volume)
  1318. def update_replicas(self, replicas):
  1319. ''' update replicas value '''
  1320. self.put(DeploymentConfig.replicas_path, replicas)
  1321. def update_volume(self, volume):
  1322. '''place an env in the env var list'''
  1323. exist_volumes = self.get_volumes()
  1324. if not volume:
  1325. return False
  1326. # update the volume
  1327. update_idx = None
  1328. for idx, exist_vol in enumerate(exist_volumes):
  1329. if exist_vol['name'] == volume['name']:
  1330. update_idx = idx
  1331. break
  1332. if update_idx != None:
  1333. exist_volumes[update_idx] = volume
  1334. else:
  1335. self.add_volume(volume)
  1336. return True
  1337. def update_volume_mount(self, volume_mount):
  1338. '''place an env in the env var list'''
  1339. modified = False
  1340. exist_volume_mounts = self.get_volume_mounts()
  1341. if not volume_mount:
  1342. return False
  1343. # update the volume mount
  1344. for exist_vol_mount in exist_volume_mounts:
  1345. if exist_vol_mount['name'] == volume_mount['name']:
  1346. if 'mountPath' in exist_vol_mount and \
  1347. str(exist_vol_mount['mountPath']) != str(volume_mount['mountPath']):
  1348. exist_vol_mount['mountPath'] = volume_mount['mountPath']
  1349. modified = True
  1350. break
  1351. if not modified:
  1352. self.add_volume_mount(volume_mount)
  1353. modified = True
  1354. return modified
  1355. def needs_update_volume(self, volume, volume_mount):
  1356. ''' verify a volume update is needed '''
  1357. exist_volume = self.find_volume_by_name(volume)
  1358. exist_volume_mount = self.find_volume_by_name(volume, mounts=True)
  1359. results = []
  1360. results.append(exist_volume['name'] == volume['name'])
  1361. if 'secret' in volume:
  1362. results.append('secret' in exist_volume)
  1363. results.append(exist_volume['secret']['secretName'] == volume['secret']['secretName'])
  1364. results.append(exist_volume_mount['name'] == volume_mount['name'])
  1365. results.append(exist_volume_mount['mountPath'] == volume_mount['mountPath'])
  1366. elif 'emptyDir' in volume:
  1367. results.append(exist_volume_mount['name'] == volume['name'])
  1368. results.append(exist_volume_mount['mountPath'] == volume_mount['mountPath'])
  1369. elif 'persistentVolumeClaim' in volume:
  1370. pvc = 'persistentVolumeClaim'
  1371. results.append(pvc in exist_volume)
  1372. if results[-1]:
  1373. results.append(exist_volume[pvc]['claimName'] == volume[pvc]['claimName'])
  1374. if 'claimSize' in volume[pvc]:
  1375. results.append(exist_volume[pvc]['claimSize'] == volume[pvc]['claimSize'])
  1376. elif 'hostpath' in volume:
  1377. results.append('hostPath' in exist_volume)
  1378. results.append(exist_volume['hostPath']['path'] == volume_mount['mountPath'])
  1379. return not all(results)
  1380. def needs_update_replicas(self, replicas):
  1381. ''' verify whether a replica update is needed '''
  1382. current_reps = self.get(DeploymentConfig.replicas_path)
  1383. return not current_reps == replicas
  1384. # -*- -*- -*- End included fragment: lib/deploymentconfig.py -*- -*- -*-
  1385. # -*- -*- -*- Begin included fragment: class/oc_env.py -*- -*- -*-
  1386. # pylint: disable=too-many-instance-attributes
  1387. class OCEnv(OpenShiftCLI):
  1388. ''' Class to wrap the oc command line tools '''
  1389. container_path = {"pod": "spec.containers[0].env",
  1390. "dc": "spec.template.spec.containers[0].env",
  1391. "rc": "spec.template.spec.containers[0].env",
  1392. }
  1393. # pylint allows 5. we need 6
  1394. # pylint: disable=too-many-arguments
  1395. def __init__(self,
  1396. namespace,
  1397. kind,
  1398. env_vars,
  1399. resource_name=None,
  1400. kubeconfig='/etc/origin/master/admin.kubeconfig',
  1401. verbose=False):
  1402. ''' Constructor for OpenshiftOC '''
  1403. super(OCEnv, self).__init__(namespace, kubeconfig=kubeconfig, verbose=verbose)
  1404. self.kind = kind
  1405. self.name = resource_name
  1406. self.env_vars = env_vars
  1407. self._resource = None
  1408. @property
  1409. def resource(self):
  1410. ''' property function for resource var'''
  1411. if not self._resource:
  1412. self.get()
  1413. return self._resource
  1414. @resource.setter
  1415. def resource(self, data):
  1416. ''' setter function for resource var'''
  1417. self._resource = data
  1418. def key_value_exists(self, key, value):
  1419. ''' return whether a key, value pair exists '''
  1420. return self.resource.exists_env_value(key, value)
  1421. def key_exists(self, key):
  1422. ''' return whether a key exists '''
  1423. return self.resource.exists_env_key(key)
  1424. def get(self):
  1425. '''return environment variables '''
  1426. result = self._get(self.kind, self.name)
  1427. if result['returncode'] == 0:
  1428. if self.kind == 'dc':
  1429. self.resource = DeploymentConfig(content=result['results'][0])
  1430. result['results'] = self.resource.get(OCEnv.container_path[self.kind]) or []
  1431. return result
  1432. def delete(self):
  1433. ''' delete environment variables '''
  1434. if self.resource.delete_env_var(self.env_vars.keys()):
  1435. return self._replace_content(self.kind, self.name, self.resource.yaml_dict)
  1436. return {'returncode': 0, 'changed': False}
  1437. def put(self):
  1438. '''place env vars into dc '''
  1439. for update_key, update_value in self.env_vars.items():
  1440. self.resource.update_env_var(update_key, update_value)
  1441. return self._replace_content(self.kind, self.name, self.resource.yaml_dict)
  1442. # pylint: disable=too-many-return-statements
  1443. @staticmethod
  1444. def run_ansible(params, check_mode):
  1445. '''run the idempotent ansible code'''
  1446. ocenv = OCEnv(params['namespace'],
  1447. params['kind'],
  1448. params['env_vars'],
  1449. resource_name=params['name'],
  1450. kubeconfig=params['kubeconfig'],
  1451. verbose=params['debug'])
  1452. state = params['state']
  1453. api_rval = ocenv.get()
  1454. #####
  1455. # Get
  1456. #####
  1457. if state == 'list':
  1458. return {'changed': False, 'results': api_rval['results'], 'state': "list"}
  1459. ########
  1460. # Delete
  1461. ########
  1462. if state == 'absent':
  1463. for key in params.get('env_vars', {}).keys():
  1464. if ocenv.resource.exists_env_key(key):
  1465. if check_mode:
  1466. return {'changed': False,
  1467. 'msg': 'CHECK_MODE: Would have performed a delete.'}
  1468. api_rval = ocenv.delete()
  1469. return {'changed': True, 'state': 'absent'}
  1470. return {'changed': False, 'state': 'absent'}
  1471. if state == 'present':
  1472. ########
  1473. # Create
  1474. ########
  1475. for key, value in params.get('env_vars', {}).items():
  1476. if not ocenv.key_value_exists(key, value):
  1477. if check_mode:
  1478. return {'changed': False,
  1479. 'msg': 'CHECK_MODE: Would have performed a create.'}
  1480. # Create it here
  1481. api_rval = ocenv.put()
  1482. if api_rval['returncode'] != 0:
  1483. return {'failed': True, 'msg': api_rval}
  1484. # return the created object
  1485. api_rval = ocenv.get()
  1486. if api_rval['returncode'] != 0:
  1487. return {'failed': True, 'msg': api_rval}
  1488. return {'changed': True, 'results': api_rval['results'], 'state': 'present'}
  1489. return {'changed': False, 'results': api_rval['results'], 'state': 'present'}
  1490. return {'failed': True,
  1491. 'changed': False,
  1492. 'msg': 'Unknown state passed. %s' % state}
  1493. # -*- -*- -*- End included fragment: class/oc_env.py -*- -*- -*-
  1494. # -*- -*- -*- Begin included fragment: ansible/oc_env.py -*- -*- -*-
  1495. def main():
  1496. '''
  1497. ansible oc module for environment variables
  1498. '''
  1499. module = AnsibleModule(
  1500. argument_spec=dict(
  1501. kubeconfig=dict(default='/etc/origin/master/admin.kubeconfig', type='str'),
  1502. state=dict(default='present', type='str',
  1503. choices=['present', 'absent', 'list']),
  1504. debug=dict(default=False, type='bool'),
  1505. kind=dict(default='rc', choices=['dc', 'rc', 'pods'], type='str'),
  1506. namespace=dict(default='default', type='str'),
  1507. name=dict(default=None, required=True, type='str'),
  1508. env_vars=dict(default=None, type='dict'),
  1509. ),
  1510. mutually_exclusive=[["content", "files"]],
  1511. supports_check_mode=True,
  1512. )
  1513. results = OCEnv.run_ansible(module.params, module.check_mode)
  1514. if 'failed' in results:
  1515. module.fail_json(**results)
  1516. module.exit_json(**results)
  1517. if __name__ == '__main__':
  1518. main()
  1519. # -*- -*- -*- End included fragment: ansible/oc_env.py -*- -*- -*-