oc_env.py 58 KB

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