oc_label.py 50 KB

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