oc_label.py 51 KB

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