oc_label.py 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538
  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. required: true
  55. default: present
  56. choices: ["present", "absent", "list", "add"]
  57. aliases: []
  58. kubeconfig:
  59. description:
  60. - The path for the kubeconfig file to use for authentication
  61. required: false
  62. default: /etc/origin/master/admin.kubeconfig
  63. aliases: []
  64. debug:
  65. description:
  66. - Turn on debug output.
  67. required: false
  68. default: False
  69. aliases: []
  70. kind:
  71. description:
  72. - The kind of object that can be managed.
  73. required: True
  74. default: None
  75. choices:
  76. - node
  77. - pod
  78. - namespace
  79. aliases: []
  80. labels:
  81. description:
  82. - A list of labels to for the resource.
  83. required: false
  84. default: None
  85. aliases: []
  86. selector:
  87. description:
  88. - The selector to apply to the resource query
  89. required: false
  90. default: None
  91. aliases: []
  92. author:
  93. - "Joel Diaz <jdiaz@redhat.com>"
  94. extends_documentation_fragment: []
  95. '''
  96. EXAMPLES = '''
  97. - name: Add label to node
  98. oc_label:
  99. name: ip-172-31-5-23.ec2.internal
  100. state: add
  101. kind: node
  102. labels:
  103. - key: logging-infra-fluentd
  104. value: 'true'
  105. '''
  106. # -*- -*- -*- End included fragment: doc/label -*- -*- -*-
  107. # -*- -*- -*- Begin included fragment: ../../lib_utils/src/class/yedit.py -*- -*- -*-
  108. # noqa: E301,E302
  109. class YeditException(Exception):
  110. ''' Exception class for Yedit '''
  111. pass
  112. # pylint: disable=too-many-public-methods
  113. class Yedit(object):
  114. ''' Class to modify yaml files '''
  115. re_valid_key = r"(((\[-?\d+\])|([0-9a-zA-Z%s/_-]+)).?)+$"
  116. re_key = r"(?:\[(-?\d+)\])|([0-9a-zA-Z%s/_-]+)"
  117. com_sep = set(['.', '#', '|', ':'])
  118. # pylint: disable=too-many-arguments
  119. def __init__(self,
  120. filename=None,
  121. content=None,
  122. content_type='yaml',
  123. separator='.',
  124. backup=False):
  125. self.content = content
  126. self._separator = separator
  127. self.filename = filename
  128. self.__yaml_dict = content
  129. self.content_type = content_type
  130. self.backup = backup
  131. self.load(content_type=self.content_type)
  132. if self.__yaml_dict is None:
  133. self.__yaml_dict = {}
  134. @property
  135. def separator(self):
  136. ''' getter method for yaml_dict '''
  137. return self._separator
  138. @separator.setter
  139. def separator(self):
  140. ''' getter method for yaml_dict '''
  141. return self._separator
  142. @property
  143. def yaml_dict(self):
  144. ''' getter method for yaml_dict '''
  145. return self.__yaml_dict
  146. @yaml_dict.setter
  147. def yaml_dict(self, value):
  148. ''' setter method for yaml_dict '''
  149. self.__yaml_dict = value
  150. @staticmethod
  151. def parse_key(key, sep='.'):
  152. '''parse the key allowing the appropriate separator'''
  153. common_separators = list(Yedit.com_sep - set([sep]))
  154. return re.findall(Yedit.re_key % ''.join(common_separators), key)
  155. @staticmethod
  156. def valid_key(key, sep='.'):
  157. '''validate the incoming key'''
  158. common_separators = list(Yedit.com_sep - set([sep]))
  159. if not re.match(Yedit.re_valid_key % ''.join(common_separators), key):
  160. return False
  161. return True
  162. @staticmethod
  163. def remove_entry(data, key, sep='.'):
  164. ''' remove data at location key '''
  165. if key == '' and isinstance(data, dict):
  166. data.clear()
  167. return True
  168. elif key == '' and isinstance(data, list):
  169. del data[:]
  170. return True
  171. if not (key and Yedit.valid_key(key, sep)) and \
  172. isinstance(data, (list, dict)):
  173. return None
  174. key_indexes = Yedit.parse_key(key, sep)
  175. for arr_ind, dict_key in key_indexes[:-1]:
  176. if dict_key and isinstance(data, dict):
  177. data = data.get(dict_key, None)
  178. elif (arr_ind and isinstance(data, list) and
  179. int(arr_ind) <= len(data) - 1):
  180. data = data[int(arr_ind)]
  181. else:
  182. return None
  183. # process last index for remove
  184. # expected list entry
  185. if key_indexes[-1][0]:
  186. if isinstance(data, list) and int(key_indexes[-1][0]) <= len(data) - 1: # noqa: E501
  187. del data[int(key_indexes[-1][0])]
  188. return True
  189. # expected dict entry
  190. elif key_indexes[-1][1]:
  191. if isinstance(data, dict):
  192. del data[key_indexes[-1][1]]
  193. return True
  194. @staticmethod
  195. def add_entry(data, key, item=None, sep='.'):
  196. ''' Get an item from a dictionary with key notation a.b.c
  197. d = {'a': {'b': 'c'}}}
  198. key = a#b
  199. return c
  200. '''
  201. if key == '':
  202. pass
  203. elif (not (key and Yedit.valid_key(key, sep)) and
  204. isinstance(data, (list, dict))):
  205. return None
  206. key_indexes = Yedit.parse_key(key, sep)
  207. for arr_ind, dict_key in key_indexes[:-1]:
  208. if dict_key:
  209. if isinstance(data, dict) and dict_key in data and data[dict_key]: # noqa: E501
  210. data = data[dict_key]
  211. continue
  212. elif data and not isinstance(data, dict):
  213. return None
  214. data[dict_key] = {}
  215. data = data[dict_key]
  216. elif (arr_ind and isinstance(data, list) and
  217. int(arr_ind) <= len(data) - 1):
  218. data = data[int(arr_ind)]
  219. else:
  220. return None
  221. if key == '':
  222. data = item
  223. # process last index for add
  224. # expected list entry
  225. elif key_indexes[-1][0] and isinstance(data, list) and int(key_indexes[-1][0]) <= len(data) - 1: # noqa: E501
  226. data[int(key_indexes[-1][0])] = item
  227. # expected dict entry
  228. elif key_indexes[-1][1] and isinstance(data, dict):
  229. data[key_indexes[-1][1]] = item
  230. return data
  231. @staticmethod
  232. def get_entry(data, key, sep='.'):
  233. ''' Get an item from a dictionary with key notation a.b.c
  234. d = {'a': {'b': 'c'}}}
  235. key = a.b
  236. return c
  237. '''
  238. if key == '':
  239. pass
  240. elif (not (key and Yedit.valid_key(key, sep)) and
  241. isinstance(data, (list, dict))):
  242. return None
  243. key_indexes = Yedit.parse_key(key, sep)
  244. for arr_ind, dict_key in key_indexes:
  245. if dict_key and isinstance(data, dict):
  246. data = data.get(dict_key, None)
  247. elif (arr_ind and isinstance(data, list) and
  248. int(arr_ind) <= len(data) - 1):
  249. data = data[int(arr_ind)]
  250. else:
  251. return None
  252. return data
  253. def write(self):
  254. ''' write to file '''
  255. if not self.filename:
  256. raise YeditException('Please specify a filename.')
  257. if self.backup and self.file_exists():
  258. shutil.copy(self.filename, self.filename + '.orig')
  259. tmp_filename = self.filename + '.yedit'
  260. with open(tmp_filename, 'w') as yfd:
  261. # pylint: disable=no-member
  262. if hasattr(self.yaml_dict, 'fa'):
  263. self.yaml_dict.fa.set_block_style()
  264. yfd.write(yaml.dump(self.yaml_dict, Dumper=yaml.RoundTripDumper))
  265. os.rename(tmp_filename, self.filename)
  266. return (True, self.yaml_dict)
  267. def read(self):
  268. ''' read from file '''
  269. # check if it exists
  270. if self.filename is None or not self.file_exists():
  271. return None
  272. contents = None
  273. with open(self.filename) as yfd:
  274. contents = yfd.read()
  275. return contents
  276. def file_exists(self):
  277. ''' return whether file exists '''
  278. if os.path.exists(self.filename):
  279. return True
  280. return False
  281. def load(self, content_type='yaml'):
  282. ''' return yaml file '''
  283. contents = self.read()
  284. if not contents and not self.content:
  285. return None
  286. if self.content:
  287. if isinstance(self.content, dict):
  288. self.yaml_dict = self.content
  289. return self.yaml_dict
  290. elif isinstance(self.content, str):
  291. contents = self.content
  292. # check if it is yaml
  293. try:
  294. if content_type == 'yaml' and contents:
  295. self.yaml_dict = yaml.load(contents, yaml.RoundTripLoader)
  296. # pylint: disable=no-member
  297. if hasattr(self.yaml_dict, 'fa'):
  298. self.yaml_dict.fa.set_block_style()
  299. elif content_type == 'json' and contents:
  300. self.yaml_dict = json.loads(contents)
  301. except yaml.YAMLError as err:
  302. # Error loading yaml or json
  303. raise YeditException('Problem with loading yaml file. %s' % err)
  304. return self.yaml_dict
  305. def get(self, key):
  306. ''' get a specified key'''
  307. try:
  308. entry = Yedit.get_entry(self.yaml_dict, key, self.separator)
  309. except KeyError:
  310. entry = None
  311. return entry
  312. def pop(self, path, key_or_item):
  313. ''' remove a key, value pair from a dict or an item for a list'''
  314. try:
  315. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  316. except KeyError:
  317. entry = None
  318. if entry is None:
  319. return (False, self.yaml_dict)
  320. if isinstance(entry, dict):
  321. # pylint: disable=no-member,maybe-no-member
  322. if key_or_item in entry:
  323. entry.pop(key_or_item)
  324. return (True, self.yaml_dict)
  325. return (False, self.yaml_dict)
  326. elif isinstance(entry, list):
  327. # pylint: disable=no-member,maybe-no-member
  328. ind = None
  329. try:
  330. ind = entry.index(key_or_item)
  331. except ValueError:
  332. return (False, self.yaml_dict)
  333. entry.pop(ind)
  334. return (True, self.yaml_dict)
  335. return (False, self.yaml_dict)
  336. def delete(self, path):
  337. ''' remove path from a dict'''
  338. try:
  339. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  340. except KeyError:
  341. entry = None
  342. if entry is None:
  343. return (False, self.yaml_dict)
  344. result = Yedit.remove_entry(self.yaml_dict, path, self.separator)
  345. if not result:
  346. return (False, self.yaml_dict)
  347. return (True, self.yaml_dict)
  348. def exists(self, path, value):
  349. ''' check if value exists at path'''
  350. try:
  351. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  352. except KeyError:
  353. entry = None
  354. if isinstance(entry, list):
  355. if value in entry:
  356. return True
  357. return False
  358. elif isinstance(entry, dict):
  359. if isinstance(value, dict):
  360. rval = False
  361. for key, val in value.items():
  362. if entry[key] != val:
  363. rval = False
  364. break
  365. else:
  366. rval = True
  367. return rval
  368. return value in entry
  369. return entry == value
  370. def append(self, path, value):
  371. '''append value to a list'''
  372. try:
  373. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  374. except KeyError:
  375. entry = None
  376. if entry is None:
  377. self.put(path, [])
  378. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  379. if not isinstance(entry, list):
  380. return (False, self.yaml_dict)
  381. # pylint: disable=no-member,maybe-no-member
  382. entry.append(value)
  383. return (True, self.yaml_dict)
  384. # pylint: disable=too-many-arguments
  385. def update(self, path, value, index=None, curr_value=None):
  386. ''' put path, value into a dict '''
  387. try:
  388. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  389. except KeyError:
  390. entry = None
  391. if isinstance(entry, dict):
  392. # pylint: disable=no-member,maybe-no-member
  393. if not isinstance(value, dict):
  394. raise YeditException('Cannot replace key, value entry in ' +
  395. 'dict with non-dict type. value=[%s] [%s]' % (value, type(value))) # noqa: E501
  396. entry.update(value)
  397. return (True, self.yaml_dict)
  398. elif isinstance(entry, list):
  399. # pylint: disable=no-member,maybe-no-member
  400. ind = None
  401. if curr_value:
  402. try:
  403. ind = entry.index(curr_value)
  404. except ValueError:
  405. return (False, self.yaml_dict)
  406. elif index is not None:
  407. ind = index
  408. if ind is not None and entry[ind] != value:
  409. entry[ind] = value
  410. return (True, self.yaml_dict)
  411. # see if it exists in the list
  412. try:
  413. ind = entry.index(value)
  414. except ValueError:
  415. # doesn't exist, append it
  416. entry.append(value)
  417. return (True, self.yaml_dict)
  418. # already exists, return
  419. if ind is not None:
  420. return (False, self.yaml_dict)
  421. return (False, self.yaml_dict)
  422. def put(self, path, value):
  423. ''' put path, value into a dict '''
  424. try:
  425. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  426. except KeyError:
  427. entry = None
  428. if entry == value:
  429. return (False, self.yaml_dict)
  430. # deepcopy didn't work
  431. tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict,
  432. default_flow_style=False),
  433. yaml.RoundTripLoader)
  434. # pylint: disable=no-member
  435. if hasattr(self.yaml_dict, 'fa'):
  436. tmp_copy.fa.set_block_style()
  437. result = Yedit.add_entry(tmp_copy, path, value, self.separator)
  438. if not result:
  439. return (False, self.yaml_dict)
  440. self.yaml_dict = tmp_copy
  441. return (True, self.yaml_dict)
  442. def create(self, path, value):
  443. ''' create a yaml file '''
  444. if not self.file_exists():
  445. # deepcopy didn't work
  446. tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict, default_flow_style=False), # noqa: E501
  447. yaml.RoundTripLoader)
  448. # pylint: disable=no-member
  449. if hasattr(self.yaml_dict, 'fa'):
  450. tmp_copy.fa.set_block_style()
  451. result = Yedit.add_entry(tmp_copy, path, value, self.separator)
  452. if result:
  453. self.yaml_dict = tmp_copy
  454. return (True, self.yaml_dict)
  455. return (False, self.yaml_dict)
  456. @staticmethod
  457. def get_curr_value(invalue, val_type):
  458. '''return the current value'''
  459. if invalue is None:
  460. return None
  461. curr_value = invalue
  462. if val_type == 'yaml':
  463. curr_value = yaml.load(invalue)
  464. elif val_type == 'json':
  465. curr_value = json.loads(invalue)
  466. return curr_value
  467. @staticmethod
  468. def parse_value(inc_value, vtype=''):
  469. '''determine value type passed'''
  470. true_bools = ['y', 'Y', 'yes', 'Yes', 'YES', 'true', 'True', 'TRUE',
  471. 'on', 'On', 'ON', ]
  472. false_bools = ['n', 'N', 'no', 'No', 'NO', 'false', 'False', 'FALSE',
  473. 'off', 'Off', 'OFF']
  474. # It came in as a string but you didn't specify value_type as string
  475. # we will convert to bool if it matches any of the above cases
  476. if isinstance(inc_value, str) and 'bool' in vtype:
  477. if inc_value not in true_bools and inc_value not in false_bools:
  478. raise YeditException('Not a boolean type. str=[%s] vtype=[%s]'
  479. % (inc_value, vtype))
  480. elif isinstance(inc_value, bool) and 'str' in vtype:
  481. inc_value = str(inc_value)
  482. # If vtype is not str then go ahead and attempt to yaml load it.
  483. if isinstance(inc_value, str) and 'str' not in vtype:
  484. try:
  485. inc_value = yaml.load(inc_value)
  486. except Exception:
  487. raise YeditException('Could not determine type of incoming ' +
  488. 'value. value=[%s] vtype=[%s]'
  489. % (type(inc_value), vtype))
  490. return inc_value
  491. # pylint: disable=too-many-return-statements,too-many-branches
  492. @staticmethod
  493. def run_ansible(module):
  494. '''perform the idempotent crud operations'''
  495. yamlfile = Yedit(filename=module.params['src'],
  496. backup=module.params['backup'],
  497. separator=module.params['separator'])
  498. if module.params['src']:
  499. rval = yamlfile.load()
  500. if yamlfile.yaml_dict is None and \
  501. module.params['state'] != 'present':
  502. return {'failed': True,
  503. 'msg': 'Error opening file [%s]. Verify that the ' +
  504. 'file exists, that it is has correct' +
  505. ' permissions, and is valid yaml.'}
  506. if module.params['state'] == 'list':
  507. if module.params['content']:
  508. content = Yedit.parse_value(module.params['content'],
  509. module.params['content_type'])
  510. yamlfile.yaml_dict = content
  511. if module.params['key']:
  512. rval = yamlfile.get(module.params['key']) or {}
  513. return {'changed': False, 'result': rval, 'state': "list"}
  514. elif module.params['state'] == 'absent':
  515. if module.params['content']:
  516. content = Yedit.parse_value(module.params['content'],
  517. module.params['content_type'])
  518. yamlfile.yaml_dict = content
  519. if module.params['update']:
  520. rval = yamlfile.pop(module.params['key'],
  521. module.params['value'])
  522. else:
  523. rval = yamlfile.delete(module.params['key'])
  524. if rval[0] and module.params['src']:
  525. yamlfile.write()
  526. return {'changed': rval[0], 'result': rval[1], 'state': "absent"}
  527. elif module.params['state'] == 'present':
  528. # check if content is different than what is in the file
  529. if module.params['content']:
  530. content = Yedit.parse_value(module.params['content'],
  531. module.params['content_type'])
  532. # We had no edits to make and the contents are the same
  533. if yamlfile.yaml_dict == content and \
  534. module.params['value'] is None:
  535. return {'changed': False,
  536. 'result': yamlfile.yaml_dict,
  537. 'state': "present"}
  538. yamlfile.yaml_dict = content
  539. # we were passed a value; parse it
  540. if module.params['value']:
  541. value = Yedit.parse_value(module.params['value'],
  542. module.params['value_type'])
  543. key = module.params['key']
  544. if module.params['update']:
  545. # pylint: disable=line-too-long
  546. curr_value = Yedit.get_curr_value(Yedit.parse_value(module.params['curr_value']), # noqa: E501
  547. module.params['curr_value_format']) # noqa: E501
  548. rval = yamlfile.update(key, value, module.params['index'], curr_value) # noqa: E501
  549. elif module.params['append']:
  550. rval = yamlfile.append(key, value)
  551. else:
  552. rval = yamlfile.put(key, value)
  553. if rval[0] and module.params['src']:
  554. yamlfile.write()
  555. return {'changed': rval[0],
  556. 'result': rval[1], 'state': "present"}
  557. # no edits to make
  558. if module.params['src']:
  559. # pylint: disable=redefined-variable-type
  560. rval = yamlfile.write()
  561. return {'changed': rval[0],
  562. 'result': rval[1],
  563. 'state': "present"}
  564. return {'failed': True, 'msg': 'Unkown state passed'}
  565. # -*- -*- -*- End included fragment: ../../lib_utils/src/class/yedit.py -*- -*- -*-
  566. # -*- -*- -*- Begin included fragment: lib/base.py -*- -*- -*-
  567. # pylint: disable=too-many-lines
  568. # noqa: E301,E302,E303,T001
  569. class OpenShiftCLIError(Exception):
  570. '''Exception class for openshiftcli'''
  571. pass
  572. # pylint: disable=too-few-public-methods
  573. class OpenShiftCLI(object):
  574. ''' Class to wrap the command line tools '''
  575. def __init__(self,
  576. namespace,
  577. kubeconfig='/etc/origin/master/admin.kubeconfig',
  578. verbose=False,
  579. all_namespaces=False):
  580. ''' Constructor for OpenshiftCLI '''
  581. self.namespace = namespace
  582. self.verbose = verbose
  583. self.kubeconfig = kubeconfig
  584. self.all_namespaces = all_namespaces
  585. # Pylint allows only 5 arguments to be passed.
  586. # pylint: disable=too-many-arguments
  587. def _replace_content(self, resource, rname, content, force=False, sep='.'):
  588. ''' replace the current object with the content '''
  589. res = self._get(resource, rname)
  590. if not res['results']:
  591. return res
  592. fname = '/tmp/%s' % rname
  593. yed = Yedit(fname, res['results'][0], separator=sep)
  594. changes = []
  595. for key, value in content.items():
  596. changes.append(yed.put(key, value))
  597. if any([change[0] for change in changes]):
  598. yed.write()
  599. atexit.register(Utils.cleanup, [fname])
  600. return self._replace(fname, force)
  601. return {'returncode': 0, 'updated': False}
  602. def _replace(self, fname, force=False):
  603. '''replace the current object with oc replace'''
  604. cmd = ['replace', '-f', fname]
  605. if force:
  606. cmd.append('--force')
  607. return self.openshift_cmd(cmd)
  608. def _create_from_content(self, rname, content):
  609. '''create a temporary file and then call oc create on it'''
  610. fname = '/tmp/%s' % rname
  611. yed = Yedit(fname, content=content)
  612. yed.write()
  613. atexit.register(Utils.cleanup, [fname])
  614. return self._create(fname)
  615. def _create(self, fname):
  616. '''call oc create on a filename'''
  617. return self.openshift_cmd(['create', '-f', fname])
  618. def _delete(self, resource, rname, selector=None):
  619. '''call oc delete on a resource'''
  620. cmd = ['delete', resource, rname]
  621. if selector:
  622. cmd.append('--selector=%s' % selector)
  623. return self.openshift_cmd(cmd)
  624. def _process(self, template_name, create=False, params=None, template_data=None): # noqa: E501
  625. '''process a template
  626. template_name: the name of the template to process
  627. create: whether to send to oc create after processing
  628. params: the parameters for the template
  629. template_data: the incoming template's data; instead of a file
  630. '''
  631. cmd = ['process']
  632. if template_data:
  633. cmd.extend(['-f', '-'])
  634. else:
  635. cmd.append(template_name)
  636. if params:
  637. param_str = ["%s=%s" % (key, value) for key, value in params.items()]
  638. cmd.append('-v')
  639. cmd.extend(param_str)
  640. results = self.openshift_cmd(cmd, output=True, input_data=template_data)
  641. if results['returncode'] != 0 or not create:
  642. return results
  643. fname = '/tmp/%s' % template_name
  644. yed = Yedit(fname, results['results'])
  645. yed.write()
  646. atexit.register(Utils.cleanup, [fname])
  647. return self.openshift_cmd(['create', '-f', fname])
  648. def _get(self, resource, rname=None, selector=None):
  649. '''return a resource by name '''
  650. cmd = ['get', resource]
  651. if selector:
  652. cmd.append('--selector=%s' % selector)
  653. elif rname:
  654. cmd.append(rname)
  655. cmd.extend(['-o', 'json'])
  656. rval = self.openshift_cmd(cmd, output=True)
  657. # Ensure results are retuned in an array
  658. if 'items' in rval:
  659. rval['results'] = rval['items']
  660. elif not isinstance(rval['results'], list):
  661. rval['results'] = [rval['results']]
  662. return rval
  663. def _schedulable(self, node=None, selector=None, schedulable=True):
  664. ''' perform oadm manage-node scheduable '''
  665. cmd = ['manage-node']
  666. if node:
  667. cmd.extend(node)
  668. else:
  669. cmd.append('--selector=%s' % selector)
  670. cmd.append('--schedulable=%s' % schedulable)
  671. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw') # noqa: E501
  672. def _list_pods(self, node=None, selector=None, pod_selector=None):
  673. ''' perform oadm list pods
  674. node: the node in which to list pods
  675. selector: the label selector filter if provided
  676. pod_selector: the pod selector filter if provided
  677. '''
  678. cmd = ['manage-node']
  679. if node:
  680. cmd.extend(node)
  681. else:
  682. cmd.append('--selector=%s' % selector)
  683. if pod_selector:
  684. cmd.append('--pod-selector=%s' % pod_selector)
  685. cmd.extend(['--list-pods', '-o', 'json'])
  686. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  687. # pylint: disable=too-many-arguments
  688. def _evacuate(self, node=None, selector=None, pod_selector=None, dry_run=False, grace_period=None, force=False):
  689. ''' perform oadm manage-node evacuate '''
  690. cmd = ['manage-node']
  691. if node:
  692. cmd.extend(node)
  693. else:
  694. cmd.append('--selector=%s' % selector)
  695. if dry_run:
  696. cmd.append('--dry-run')
  697. if pod_selector:
  698. cmd.append('--pod-selector=%s' % pod_selector)
  699. if grace_period:
  700. cmd.append('--grace-period=%s' % int(grace_period))
  701. if force:
  702. cmd.append('--force')
  703. cmd.append('--evacuate')
  704. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  705. def _version(self):
  706. ''' return the openshift version'''
  707. return self.openshift_cmd(['version'], output=True, output_type='raw')
  708. def _import_image(self, url=None, name=None, tag=None):
  709. ''' perform image import '''
  710. cmd = ['import-image']
  711. image = '{0}'.format(name)
  712. if tag:
  713. image += ':{0}'.format(tag)
  714. cmd.append(image)
  715. if url:
  716. cmd.append('--from={0}/{1}'.format(url, image))
  717. cmd.append('-n{0}'.format(self.namespace))
  718. cmd.append('--confirm')
  719. return self.openshift_cmd(cmd)
  720. def _run(self, cmds, input_data):
  721. ''' Actually executes the command. This makes mocking easier. '''
  722. proc = subprocess.Popen(cmds,
  723. stdin=subprocess.PIPE,
  724. stdout=subprocess.PIPE,
  725. stderr=subprocess.PIPE,
  726. env={'KUBECONFIG': self.kubeconfig})
  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 = ['/usr/bin/oadm']
  735. else:
  736. cmds = ['/usr/bin/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.selector = selector
  1003. def get_current_labels(self):
  1004. ''' get the current labels on object '''
  1005. return self.get()['results']['labels']
  1006. def compare_labels(self, host_labels):
  1007. ''' compare incoming labels against current labels'''
  1008. for label in self.labels:
  1009. if label['key'] not in host_labels or \
  1010. label['value'] != host_labels[label['key']]:
  1011. return False
  1012. return True
  1013. def all_user_labels_exist(self):
  1014. ''' return whether all the labels already exist '''
  1015. current_labels = self.get_current_labels()
  1016. for current_host_labels in current_labels:
  1017. rbool = self.compare_labels(current_host_labels)
  1018. if rbool == False:
  1019. return False
  1020. return True
  1021. def any_label_exists(self):
  1022. ''' return whether any single label already exists '''
  1023. current_labels = self.get_current_labels()
  1024. for current_host_labels in current_labels:
  1025. for label in self.labels:
  1026. if label['key'] in current_host_labels:
  1027. return True
  1028. return False
  1029. def get_user_keys(self):
  1030. ''' go through list of user key:values and return all keys '''
  1031. user_keys = []
  1032. for label in self.labels:
  1033. user_keys.append(label['key'])
  1034. return user_keys
  1035. def get_current_label_keys(self):
  1036. ''' collect all the current label keys '''
  1037. current_label_keys = []
  1038. current_labels = self.get_current_labels()
  1039. for current_host_labels in current_labels:
  1040. for key in current_host_labels.keys():
  1041. current_label_keys.append(key)
  1042. return list(set(current_label_keys))
  1043. def get_extra_current_labels(self):
  1044. ''' return list of labels that are currently stored, but aren't
  1045. in user-provided list '''
  1046. current_labels = self.get_current_labels()
  1047. extra_labels = []
  1048. user_label_keys = self.get_user_keys()
  1049. current_label_keys = self.get_current_label_keys()
  1050. for current_key in current_label_keys:
  1051. if current_key not in user_label_keys:
  1052. extra_labels.append(current_key)
  1053. return extra_labels
  1054. def extra_current_labels(self):
  1055. ''' return whether there are labels currently stored that user
  1056. hasn't directly provided '''
  1057. extra_labels = self.get_extra_current_labels()
  1058. if len(extra_labels) > 0:
  1059. return True
  1060. else:
  1061. return False
  1062. def replace(self):
  1063. ''' replace currently stored labels with user provided labels '''
  1064. cmd = self.cmd_template()
  1065. # First delete any extra labels
  1066. extra_labels = self.get_extra_current_labels()
  1067. if len(extra_labels) > 0:
  1068. for label in extra_labels:
  1069. cmd.append("{}-".format(label))
  1070. # Now add/modify the user-provided label list
  1071. if len(self.labels) > 0:
  1072. for label in self.labels:
  1073. cmd.append("{}={}".format(label['key'], label['value']))
  1074. # --overwrite for the case where we are updating existing labels
  1075. cmd.append("--overwrite")
  1076. return self.openshift_cmd(cmd)
  1077. def get(self):
  1078. '''return label information '''
  1079. result_dict = {}
  1080. label_list = []
  1081. if self.name:
  1082. result = self._get(resource=self.kind, rname=self.name, selector=self.selector)
  1083. if 'labels' in result['results'][0]['metadata']:
  1084. label_list.append(result['results'][0]['metadata']['labels'])
  1085. else:
  1086. label_list.append({})
  1087. else:
  1088. result = self._get(resource=self.kind, selector=self.selector)
  1089. for item in result['results'][0]['items']:
  1090. if 'labels' in item['metadata']:
  1091. label_list.append(item['metadata']['labels'])
  1092. else:
  1093. label_list.append({})
  1094. result_dict['labels'] = label_list
  1095. result_dict['item_count'] = len(label_list)
  1096. result['results'] = result_dict
  1097. return result
  1098. def cmd_template(self):
  1099. ''' boilerplate oc command for modifying lables on this object '''
  1100. # let's build the cmd with what we have passed in
  1101. cmd = []
  1102. if self.namespace:
  1103. cmd = cmd + ["-n", self.namespace]
  1104. if self.selector:
  1105. cmd = cmd + ["--selector", self.selector]
  1106. cmd = cmd + ["--config", self.kubeconfig, "label", self.kind]
  1107. if self.name:
  1108. cmd = cmd + [self.name]
  1109. return cmd
  1110. def add(self):
  1111. ''' add labels '''
  1112. cmd = self.cmd_template()
  1113. for label in self.labels:
  1114. cmd.append("{}={}".format(label['key'], label['value']))
  1115. cmd.append("--overwrite")
  1116. return self.openshift_cmd(cmd)
  1117. def delete(self):
  1118. '''delete the labels'''
  1119. cmd = self.cmd_template()
  1120. for label in self.labels:
  1121. cmd.append("{}-".format(label['key']))
  1122. return self.openshift_cmd(cmd)
  1123. @staticmethod
  1124. def run_ansible(params, check_mode=False):
  1125. ''' run the idempotent ansible code
  1126. prams comes from the ansible portion of this module
  1127. check_mode: does the module support check mode. (module.check_mode)
  1128. '''
  1129. oc_label = OCLabel(params['name'],
  1130. params['namespace'],
  1131. params['kind'],
  1132. params['kubeconfig'],
  1133. params['labels'],
  1134. params['selector'],
  1135. verbose=params['debug'])
  1136. state = params['state']
  1137. name = params['name']
  1138. selector = params['selector']
  1139. api_rval = oc_label.get()
  1140. #####
  1141. # Get
  1142. #####
  1143. if state == 'list':
  1144. return {'changed': False, 'results': api_rval['results'], 'state': "list"}
  1145. #######
  1146. # Add
  1147. #######
  1148. if state == 'add':
  1149. if not (name or selector):
  1150. return {'failed': True,
  1151. 'msg': "Param 'name' or 'selector' is required if state == 'add'"}
  1152. if not oc_label.all_user_labels_exist():
  1153. if check_mode:
  1154. return {'changed': False, 'msg': 'Would have performed an addition.'}
  1155. api_rval = oc_label.add()
  1156. if api_rval['returncode'] != 0:
  1157. return {'failed': True, 'msg': api_rval}
  1158. return {'changed': True, 'results': api_rval, 'state': "add"}
  1159. return {'changed': False, 'state': "add"}
  1160. ########
  1161. # Delete
  1162. ########
  1163. if state == 'absent':
  1164. if not (name or selector):
  1165. return {'failed': True,
  1166. 'msg': "Param 'name' or 'selector' is required if state == 'absent'"}
  1167. if oc_label.any_label_exists():
  1168. if check_mode:
  1169. return {'changed': False, 'msg': 'Would have performed a delete.'}
  1170. api_rval = oc_label.delete()
  1171. if api_rval['returncode'] != 0:
  1172. return {'failed': True, 'msg': api_rval}
  1173. return {'changed': True, 'results': api_rval, 'state': "absent"}
  1174. return {'changed': False, 'state': "absent"}
  1175. if state == 'present':
  1176. ########
  1177. # Update
  1178. ########
  1179. if not (name or selector):
  1180. return {'failed': True,
  1181. 'msg': "Param 'name' or 'selector' is required if state == 'present'"}
  1182. # if all the labels passed in don't already exist
  1183. # or if there are currently stored labels that haven't
  1184. # been passed in
  1185. if not oc_label.all_user_labels_exist() or \
  1186. oc_label.extra_current_labels():
  1187. if check_mode:
  1188. return {'changed': False, 'msg': 'Would have made changes.'}
  1189. api_rval = oc_label.replace()
  1190. if api_rval['returncode'] != 0:
  1191. return {'failed': True, 'msg': api_rval}
  1192. # return the created object
  1193. api_rval = oc_label.get()
  1194. if api_rval['returncode'] != 0:
  1195. return {'failed': True, 'msg': api_rval}
  1196. return {'changed': True, 'results': api_rval, 'state': "present"}
  1197. return {'changed': False, 'results': api_rval, 'state': "present"}
  1198. return {'failed': True,
  1199. 'changed': False,
  1200. 'results': 'Unknown state passed. %s' % state,
  1201. 'state': "unknown"}
  1202. # -*- -*- -*- End included fragment: class/oc_label.py -*- -*- -*-
  1203. # -*- -*- -*- Begin included fragment: ansible/oc_label.py -*- -*- -*-
  1204. def main():
  1205. ''' ansible oc module for labels '''
  1206. module = AnsibleModule(
  1207. argument_spec=dict(
  1208. kubeconfig=dict(default='/etc/origin/master/admin.kubeconfig', type='str'),
  1209. state=dict(default='present', type='str',
  1210. choices=['present', 'absent', 'list', 'add']),
  1211. debug=dict(default=False, type='bool'),
  1212. kind=dict(default=None, type='str', required=True,
  1213. choices=['node', 'pod', 'namespace']),
  1214. name=dict(default=None, type='str'),
  1215. namespace=dict(default=None, type='str'),
  1216. labels=dict(default=None, type='list'),
  1217. selector=dict(default=None, type='str'),
  1218. ),
  1219. supports_check_mode=True,
  1220. mutually_exclusive = (['name', 'selector']),
  1221. )
  1222. results = OCLabel.run_ansible(module.params, module.check_mode)
  1223. if 'failed' in results:
  1224. module.fail_json(**results)
  1225. module.exit_json(**results)
  1226. if __name__ == '__main__':
  1227. main()
  1228. # -*- -*- -*- End included fragment: ansible/oc_label.py -*- -*- -*-