-
Notifications
You must be signed in to change notification settings - Fork 39
/
towerlib.py
executable file
·1948 lines (1565 loc) · 72 KB
/
towerlib.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: towerlib.py
#
# Copyright 2018 Costas Tyfoxylos
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the 'Software'), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
#
# pylint: disable=too-many-lines
"""
Main code for towerlib.
.. _Google Python Style Guide:
http://google.github.io/styleguide/pyguide.html
"""
import concurrent.futures
import json
import logging
import math
import sys
from cachetools import TTLCache, cached
from requests import Session
from towerlib.entities.core import validate_json
from .entities import (Config, # pylint: disable=unused-import # NOQA
LicenseInfo,
LicenseFeatures,
Organization,
User,
Project,
Team,
Group,
Inventory,
Host,
CredentialType,
Credential,
JobTemplate,
VALID_CREDENTIAL_TYPES,
JOB_TYPES,
VERBOSITY_LEVELS,
Cluster,
ClusterInstance,
EntityManager,
Settings)
from .towerlibexceptions import (AuthFailed,
InvalidOrganization,
InvalidInventory,
InvalidVariables,
InvalidUser,
InvalidTeam,
InvalidCredential,
InvalidHost,
InvalidProject,
InvalidGroup,
InvalidCredentialType,
InvalidPlaybook,
InvalidInstanceGroup,
InvalidJobType,
InvalidVerbosity,
InvalidJobTemplate,
InvalidInventoryScript)
__author__ = '''Costas Tyfoxylos <ctyfoxylos@schubergphilis.com>'''
__docformat__ = '''google'''
__date__ = '''2018-01-02'''
__copyright__ = '''Copyright 2018, Costas Tyfoxylos'''
__credits__ = ['Costas Tyfoxylos']
__license__ = '''MIT'''
__maintainer__ = '''Costas Tyfoxylos'''
__email__ = '''<ctyfoxylos@schubergphilis.com>'''
__status__ = '''Development''' # 'Prototype', 'Development', 'Production'.
# This is the main prefix used for logging
LOGGER_BASENAME = 'towerlib'
LOGGER = logging.getLogger(LOGGER_BASENAME)
LOGGER.addHandler(logging.NullHandler())
PAGINATION_LIMIT = 25
CLUSTER_STATE_CACHING_SECONDS = 10
CONFIGURATION_STATE_CACHING_SECONDS = 60
CLUSTER_STATE_CACHE = TTLCache(maxsize=1, ttl=CLUSTER_STATE_CACHING_SECONDS)
CONFIGURATION_STATE_CACHE = TTLCache(maxsize=1, ttl=CONFIGURATION_STATE_CACHING_SECONDS)
class Tower: # pylint: disable=too-many-public-methods
"""Models the api of ansible tower."""
def __init__(self, host, username, password, secure=False, ssl_verify=True): # pylint: disable=too-many-arguments
logger_name = u'{base}.{suffix}'.format(base=LOGGER_BASENAME,
suffix=self.__class__.__name__)
self._logger = logging.getLogger(logger_name)
self.host = self._generate_host_name(host, secure)
self.api = '{host}/api/v2'.format(host=self.host)
self.username = username
self.password = password
self.session = self._get_authenticated_session(secure, ssl_verify)
@staticmethod
def _generate_host_name(host, secure):
protocol = 'https' if secure else 'http'
return '{protocol}://{host}'.format(protocol=protocol, host=host)
def _get_authenticated_session(self, secure, ssl_verify):
session = Session()
if secure:
session.verify = ssl_verify
return self._authenticate(session, self.host, self.username, self.password, self.api)
@staticmethod
def _authenticate(session, host, username, password, api_url):
session.get(host)
session.auth = (username, password)
session.headers.update({'content-type': 'application/json'})
url = '{api}/me/'.format(api=api_url)
response = session.get(url)
if response.status_code == 401:
raise AuthFailed(response.content)
return session
@property
@cached(CONFIGURATION_STATE_CACHE)
def configuration(self):
"""The configuration of the tower instance.
Returns:
Config: The configuration of the tower instance.
"""
url = '{api}/config/'.format(api=self.api)
results = self.session.get(url)
config = results.json()
features = [config.get('license_info',
{}).get('features',
{}).get(key) for key in LicenseFeatures._fields] # noqa
info = [config.get('license_info',
{}).get(key) for key in LicenseInfo._fields] # noqa
# we overwrite the entry of "features" with the namedtuple of it.
info[2] = LicenseFeatures(*features)
configuration = [config.get(key) for key in Config._fields] # noqa
# we overwrite the entry of "license_info" with the namedtuple of it.
configuration[1] = LicenseInfo(*info)
return Config(*configuration)
@property
@cached(CLUSTER_STATE_CACHE)
def cluster(self):
"""The cluster status of tower.
Returns:
Cluster: The information about the state of the cluster.
"""
def get_instance(name, instance_list):
"""Getting an instance nametuple from an instance list."""
node = next((instance for instance in instance_list
if instance.get('node') == name), None)
data = [node.get(key_) for key_ in ('node', 'heartbeat')]
return ClusterInstance(self, *data)
url = '{api}/ping/'.format(api=self.api)
results = self.session.get(url)
ping = results.json()
instance_groups = ping.get('instance_groups', [])[0]
instance_list = ping.get('instances')
capacity = instance_groups.get('capacity', 0)
name = instance_groups.get('name', 'Unset')
ha_enabled = ping.get('ha', False)
version = ping.get('version', 'Unknown')
instances = [get_instance(name_, instance_list)
for name_ in instance_groups.get('instances', [])]
active_node = get_instance(ping.get('active_node'), instance_list)
return Cluster(instances, capacity, name, ha_enabled, version, active_node)
@property
def organizations(self):
"""The organizations configured in tower.
Returns:
EntityManager: The manager object for organizations.
"""
return EntityManager(self,
entity_name='organizations',
entity_object='Organization',
primary_match_field='name')
def get_organization_by_name(self, name):
"""Retrieves an organization by name.
Args:
name: The name of the organization to retrieve.
Returns:
Organization: The organization if a match is found else None.
"""
return next(self.organizations.filter({'name__iexact': name}), None)
def get_organization_by_id(self, id_):
"""Retrieves an organization by id.
Args:
id_: The id of the organization to retrieve.
Returns:
Organization: The organization if a match is found else None.
"""
return next(self.organizations.filter({'id': id_}), None)
def create_organization(self, name, description=""):
"""Creates an organization in tower.
Args:
name: The name of the organization to create.
description: The description of the organization to create.
Returns:
Organization: The organization on success, None otherwise.
"""
url = '{api}/organizations/'.format(api=self.api)
payload = {'name': name,
'description': description}
response = self.session.post(url, json=payload)
if not response.ok:
self._logger.error('Error creating organization, response was: "%s"', response.text)
return Organization(self, response.json()) if response.ok else None
def delete_organization(self, name):
"""Deletes an organization from tower.
Args:
name: The name of the organization to delete.
Returns:
bool: True on success, False otherwise.
Raises:
InvalidOrganization: The organization provided as argument does not exist.
"""
organization = self.get_organization_by_name(name)
if not organization:
raise InvalidOrganization(name)
return organization.delete()
@staticmethod
def add_slash(url):
"""Adds a final slash to a url if there is not any."""
return url + '/' if not url.endswith('/') else url
def _get_first_page(self, url, params=None):
parameters = {'page_size': PAGINATION_LIMIT}
if params:
parameters.update(params)
try:
response = self.session.get(url, params=parameters)
response_data = response.json()
response.close()
except (ValueError, AttributeError, TypeError):
self._logger.exception('Could not retrieve first page, response was %s', response.text)
response_data = {}
return response_data
def _get_paginated_response(self, url, params=None):
url = self.add_slash(url)
response_data = self._get_first_page(url, params)
count = response_data.get('count', 0)
page_count = int(math.ceil(float(count) / PAGINATION_LIMIT))
self._logger.debug('Calculated that there are {} pages to get'.format(page_count))
for result in response_data.get('results', []):
yield result
if page_count:
with concurrent.futures.ThreadPoolExecutor(max_workers=25) as executor:
futures = []
if not params:
params = {}
for index in range(page_count, 1, -1):
params.update({'page': index})
futures.append(executor.submit(self.session.get, url, params=params.copy()))
for future in concurrent.futures.as_completed(futures):
try:
response = future.result()
response_data = response.json()
response.close()
for result in response_data.get('results'):
yield result
except Exception: # pylint: disable=broad-except
self._logger.exception('Future failed...')
@property
def external_users(self):
"""Retrieves only users created by an external system.
Returns:
users (Generator): Users created by external system in tower.
"""
return self.users.filter({'social_auth__isnull': False})
@property
def local_users(self):
"""Retrieves only users created locally in tower.
Returns:
users (Generator): Users created locally in tower.
"""
return self.users.filter({'social_auth__isnull': True})
@property
def users(self):
"""A manager object for the users in tower.
Returns:
EntityManager: The manager object for users.
"""
return EntityManager(self,
entity_name='users',
entity_object='User',
primary_match_field='username')
def get_user_by_username(self, name):
"""Retrieves user by name.
Args:
name: The name of the user to retrieve.
Returns:
user (User): The user if a match is found else None.
"""
return next(self.users.filter({'username__iexact': name}), None)
def get_user_by_id(self, id_):
"""Retrieves a user by id.
Args:
id_: The id of the user to retrieve.
Returns:
User: The user if a match is found else None.
"""
return next(self.users.filter({'id': id_}), None)
def create_user(self, # pylint: disable=too-many-arguments
username,
password,
first_name="",
last_name="",
email="",
is_superuser=False,
is_system_auditor=False,
):
"""Creates a user in AWX/Tower.
Args:
username: The username to create for the user.
password: The password to set for the user.
first_name: The first name of the user.
last_name: The last name of the user.
email: The email of the user.
is_superuser: Is the user a super user
is_system_auditor: Is the user an auditor
Returns:
User: The created User object on success, None otherwise.
"""
url = '{api}/users/'.format(api=self.api)
payload = {
'username': username,
'first_name': first_name,
'last_name': last_name,
'email': email,
'password': password,
'is_superuser': is_superuser,
'is_system_auditor': is_system_auditor}
response = self.session.post(url, json=payload)
if not response.ok:
self._logger.error('Error creating user, response was: "%s"', response.text)
return User(self, response.json()) if response.ok else None
def delete_user(self, username):
"""Deletes a user by username.
Args:
username: The username of the user to delete.
Returns:
bool: True on success, False otherwise.
Raises:
InvalidUser: The username provided as argument does not exist.
"""
user = self.get_user_by_username(username)
if not user:
raise InvalidUser(username)
return user.delete()
def create_user_in_organization(self, # pylint: disable=too-many-arguments
organization,
username,
password,
first_name,
last_name,
email):
"""Creates a user in an organization.
Args:
organization: The name of the organization to create the user under.
username: The user's username.
password: The user's password.
first_name: The user's first name.
last_name: The user's last name.
email: The user's email.
Returns:
User: The user on success, None otherwise.
Raises:
InvalidOrganization: The organization provided as argument does not exist.
"""
organization_ = self.get_organization_by_name(organization)
if not organization_:
raise InvalidOrganization(organization)
user = self.create_user(username,
password,
first_name=first_name,
last_name=last_name,
email=email)
if not user:
return False
user.associate_with_organization_role(organization, Organization.DEFAULT_MEMBER_ROLE)
return user
@property
def projects(self):
"""The projects configured in tower.
Returns:
EntityManager: The manager object for projects.
"""
return EntityManager(self,
entity_name='projects',
entity_object='Project',
primary_match_field='name')
def get_projects_by_name(self, name):
"""Retrieves projects by name.
Args:
name: The name of the projects to retrieve.
Returns:
projects (Generator): A generator with the matching projects
"""
return self.projects.filter({'name__iexact': name})
def get_organization_project_by_name(self, organization, name):
"""Retrieves a project by name.
Args:
organization: The name of the organization the project belongs to.
name: The name of the project to retrieve.
Returns:
Project: The project if a match is found else None.
"""
organization_ = self.get_organization_by_name(organization)
if not organization_:
raise InvalidOrganization(organization)
return organization_.get_project_by_name(name)
def get_project_by_id(self, id_):
"""Retrieves a project by id.
Args:
id_: The id of the project to retrieve.
Returns:
Project: The project if a match is found else None.
"""
return next(self.projects.filter({'id': id_}), None)
def create_project_in_organization(self, # pylint: disable=too-many-locals,too-many-arguments
organization,
name,
description,
credential,
scm_url,
local_path='',
custom_virtualenv='',
scm_branch='master',
scm_type='git',
scm_clean=True,
scm_delete_on_update=False,
scm_update_on_launch=True,
scm_update_cache_timeout=0):
"""Creates a project in an organization.
Args:
organization (str): The name of the organization to create the project under.
name (str): The name of the project.
description (str): The description of the project.
credential (str): The name of the credential to use for the project.
scm_url (str): The url of the scm.
local_path (str): Local path (relative to PROJECTS_ROOT) containing playbooks and files for this project.
custom_virtualenv (str): Local absolute file path containing a custom Python virtualenv to use.
scm_branch (str): The default branch of the scm.
scm_type (str): The type of the scm.
scm_clean (bool): Clean scm or not.
scm_delete_on_update (bool): Delete scm on update.
scm_update_on_launch (bool): Update scm on launch.
scm_update_cache_timeout (int): Scm cache update.
Returns:
Project: The created project on success, None otherwise.
Raises:
InvalidOrganization: The organization provided as argument does not exist.
"""
organization_ = self.get_organization_by_name(organization)
if not organization_:
raise InvalidOrganization(organization)
return organization_.create_project(name,
description,
credential,
scm_url,
local_path,
custom_virtualenv,
scm_branch,
scm_type,
scm_clean,
scm_delete_on_update,
scm_update_on_launch,
scm_update_cache_timeout)
def delete_organization_project(self, organization, name):
"""Deletes a project from tower.
Args:
organization: The organization the project belongs to.
name: The name of the project to delete.
Returns:
bool: True on success, False otherwise.
Raises:
InvalidProject: The project provided as argument does not exist.
"""
organization_ = self.get_organization_by_name(organization)
if not organization_:
raise InvalidOrganization(organization_)
project = organization_.get_project_by_name(name)
if not project:
raise InvalidProject(name)
return project.delete()
@property
def teams(self):
"""The teams configured in tower.
Returns:
EntityManager: The manager object for teams.
"""
return EntityManager(self,
entity_name='teams',
entity_object='Team',
primary_match_field='name')
def get_teams_by_name(self, name):
"""Retrieves teams by name.
Args:
name: The name of the teams to retrieve.
Returns:
teams (Generator): A generator with the matching teams
"""
return self.teams.filter({'name__iexact': name})
def get_organization_team_by_name(self, organization, name):
"""Retrieves a team by name.
Args:
organization: The name of the organization the team belongs to.
name: The name of the team to retrieve.
Returns:
Team: The team if a match is found else None.
Raises:
InvalidOrganization: The organization provided as argument does not exist.
"""
organization_ = self.get_organization_by_name(organization)
if not organization_:
raise InvalidOrganization(organization)
return organization_.get_team_by_name(name)
def get_team_by_id(self, id_):
"""Retrieves a team by id.
Args:
id_: The id of the team to retrieve.
Returns:
Team: The team if a match is found else None.
"""
return next(self.teams.filter({'id': id_}), None)
def create_team_in_organization(self, organization, team_name, description=""):
"""Creates a team under an organization.
Args:
organization: The name of the organization to create the team under.
team_name: The name of the team to create.
description: The description of the team to create.
Returns:
Team: The created team on success, None otherwise.
Raises:
InvalidOrganization: The organization provided as argument does not exist.
"""
organization_ = self.get_organization_by_name(organization)
if not organization_:
raise InvalidOrganization(organization)
return organization_.create_team(team_name, description)
def delete_team_in_organization(self, organization, name):
"""Deletes a team from tower.
Args:
organization: The name of the organization the team belongs to.
name: The name of the team to delete.
Returns:
bool: True on success, False otherwise.
Raises:
InvalidTeam: The team provided as argument does not exist.
"""
team = self.get_organization_team_by_name(organization, name)
if not team:
raise InvalidTeam(team)
return team.delete()
@property
def groups(self):
"""The groups configured in tower.
Returns:
EntityManager: The manager object for groups.
"""
return EntityManager(self,
entity_name='groups',
entity_object='Group',
primary_match_field='name')
def get_inventory_group_by_name(self, organization, inventory, name):
"""Retrieves a group by name.
Args:
organization: The name of the organization the inventory belongs to.
inventory: The inventory to retrieve the group from.
name: The name of the group to retrieve.
Returns:
Group: The group if a match is found else None.
Raises:
InvalidOrganization: The organisation provided as an argument does not exist.
InvalidInventory: The inventory name provided as an argument does not exist.
"""
organization_ = self.get_organization_by_name(organization)
if not organization_:
raise InvalidOrganization(organization_)
inventory_ = organization_.get_inventory_by_name(inventory)
if not inventory_:
raise InvalidInventory(inventory_)
return inventory_.get_group_by_name(name)
def get_group_by_id(self, id_):
"""Retrieves a group by id.
Args:
id_: The id of the group to retrieve.
Returns:
Group: The group if a match is found else None.
"""
return next(self.groups.filter({'id': id_}), None)
def create_inventory_group(self, organization, inventory, name, description, variables='{}'): # pylint: disable=too-many-arguments
"""Creates a group in an inventory in tower.
Args:
organization: The organization the inventory belongs to.
inventory: The name of the inventory to create the group in.
name: The name of the group to create.
description (str): The description of the group to create.
variables (str): The Variables of the group in a json string format.
Returns:
bool: True on success, False otherwise.
Raises:
InvalidGroup: The group provided as argument does not exist.
"""
inventory_ = self.get_organization_inventory_by_name(organization, inventory)
if not inventory_:
raise InvalidInventory(inventory)
return inventory_.create_group(name, description, variables)
def delete_inventory_group(self, organization, inventory, name):
"""Deletes a group from tower.
Args:
organization: The organization the inventory belongs to.
inventory: The name of the inventory to retrieve the group from.
name: The name of the group to delete.
Returns:
bool: True on success, False otherwise.
Raises:
InvalidGroup: The group provided as argument does not exist.
"""
group = self.get_inventory_group_by_name(organization, inventory, name)
if not group:
raise InvalidGroup(name)
return group.delete()
@property
def inventories(self):
"""The inventories configured in tower.
Returns:
list of Inventory: The inventories configured in tower.`
"""
return EntityManager(self,
entity_name='inventories',
entity_object='Inventory',
primary_match_field='name')
def get_inventories_by_name(self, name):
"""Retrieves inventories by name.
Args:
name: The name of the inventories to retrieve.
Returns:
inventories (Generator): A generator with the matching inventories
"""
return self.inventories.filter({'name__iexact': name})
def get_organization_inventory_by_name(self, organization, name):
"""Retrieves an inventory by name from an organization.
Args:
organization: The name of the organization to retrieve the inventory from.
name: The name of the inventory to retrieve.
Returns:
Inventory: The inventory if a match is found else None.
Raises:
InvalidOrganization: The organization provided as argument does not exist.
"""
organization_ = self.get_organization_by_name(organization)
if not organization_:
raise InvalidOrganization(organization)
return organization_.get_inventory_by_name(name)
def get_inventory_by_id(self, id_):
"""Retrieves an inventory by id.
Args:
id_: The id of the inventory to retrieve.
Returns:
Inventory: The inventory if a match is found else None.
"""
return next(self.inventories.filter({'id': id_}), None)
def create_organization_inventory(self,
organization,
name,
description,
variables='{}'):
"""Creates an inventory under an organization.
Args:
organization: The name of the organization to create the inventory under
name: The name of the inventory
description: The description of the inventory
variables: A json of the variables to be set on the inventory
Returns:
Inventory: The created inventory on success, None otherwise
Raises:
InvalidOrganization: The organization provided as argument does not exist.
"""
organization_ = self.get_organization_by_name(organization)
if not organization_:
raise InvalidOrganization(organization)
return organization_.create_inventory(name, description, variables)
@property
def inventory_scripts(self):
"""The inventories configured in tower.
Returns:
list of Inventory: The inventories configured in tower.`
"""
return EntityManager(self,
entity_name='inventory_scripts',
entity_object='InventoryScript',
primary_match_field='name')
def create_organization_inventory_script(self,
organization,
name,
description,
script):
"""Creates a custom inventory script.
Args:
organization: The organization the inventory script is part of.
name: Name of the inventory script.
description: The description of the inventory script.
script: The script of the inventory script.
Returns:
Inventory_script: The created inventory script is successful, None otherwise.
"""
organization_ = self.get_organization_by_name(organization)
if not organization_:
raise InvalidOrganization(organization)
return organization_.create_inventory_script(name, description, script)
def get_organization_inventory_script_by_name(self, organization, name):
"""Retrieves an custom inventory script by name from an organization.
Args:
organization: The name of the organization to retrieve the custom inventory script from.
name: The name of the custom inventory script to retrieve.
Returns:
Inventory: The custom inventory script if a match is found else None.
Raises:
InvalidOrganization: The organization provided as argument does not exist.
"""
organization_ = self.get_organization_by_name(organization)
if not organization_:
raise InvalidOrganization(organization)
return organization_.get_inventory_script_by_name(name)
def delete_organization_inventory_script(self, organization, name):
"""Deletes an custom inventory script from tower.
Args:
organization: The organization the custom inventory script is a member of.
name: The name of the custom inventory script to delete.
Returns:
bool: True on success, False otherwise.
Raises:
InvalidInventory: The custom inventory script provided as argument does not exist.
"""
inventory_script = self.get_organization_inventory_script_by_name(organization, name)
if not inventory_script:
raise InvalidInventoryScript(name)
return inventory_script.delete()
def delete_organization_inventory(self, organization, name):
"""Deletes an inventory from tower.
Args:
organization: The organization the inventory is a member of.
name: The name of the inventory to delete.
Returns:
bool: True on success, False otherwise.
Raises:
InvalidInventory: The inventory provided as argument does not exist.
"""
inventory = self.get_organization_inventory_by_name(organization, name)
if not inventory:
raise InvalidInventory(name)
return inventory.delete()
@property
def hosts(self):
"""The hosts configured in tower.
Returns:
EntityManager: The manager object for hosts
"""
return EntityManager(self,
entity_name='hosts',
entity_object='Host',
primary_match_field='name')
def get_hosts_by_name(self, name):
"""Retrieves hosts by name.
Args:
name: The name of the hosts to retrieve.
Returns:
hosts (Generator): A generator with the matching hosts
"""
return self.hosts.filter({'name__iexact': name})
def get_inventory_host_by_name(self, organization, inventory, name):
"""Retrieves a host by name from an inventory.
Args:
organization: The name of the organization the inventory belongs to.
inventory: The name of the inventory to search for a host.
name: The name of the host to retrieve.
Returns:
Host: The host if a match is found else None.
"""
inventory_ = self.get_organization_inventory_by_name(organization, inventory)
if not inventory_:
raise InvalidInventory(inventory)
return inventory_.get_host_by_name(name)
def get_host_by_id(self, id_):
"""Retrieves a host by id.
Args:
id_: The id of the host to retrieve.
Returns:
Host: The host if a match is found else None.