oc_label.py 51 KB

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