1
0
Fork 0
mirror of https://github.com/ansible-collections/community.general.git synced 2026-02-04 07:51:50 +00:00

Reformat everything.

This commit is contained in:
Felix Fontein 2025-11-01 12:08:41 +01:00
parent 3f2213791a
commit 340ff8586d
1008 changed files with 61301 additions and 58309 deletions

View file

@ -21,6 +21,7 @@ from ansible.module_utils.basic import missing_required_lib
CLIENT_IMP_ERR = None
try:
from manageiq_client.api import ManageIQClient
HAS_CLIENT = True
except ImportError:
CLIENT_IMP_ERR = traceback.format_exc()
@ -29,54 +30,61 @@ except ImportError:
def manageiq_argument_spec():
options = dict(
url=dict(default=os.environ.get('MIQ_URL', None)),
username=dict(default=os.environ.get('MIQ_USERNAME', None)),
password=dict(default=os.environ.get('MIQ_PASSWORD', None), no_log=True),
token=dict(default=os.environ.get('MIQ_TOKEN', None), no_log=True),
validate_certs=dict(default=True, type='bool', aliases=['verify_ssl']),
ca_cert=dict(required=False, default=None, aliases=['ca_bundle_path']),
url=dict(default=os.environ.get("MIQ_URL", None)),
username=dict(default=os.environ.get("MIQ_USERNAME", None)),
password=dict(default=os.environ.get("MIQ_PASSWORD", None), no_log=True),
token=dict(default=os.environ.get("MIQ_TOKEN", None), no_log=True),
validate_certs=dict(default=True, type="bool", aliases=["verify_ssl"]),
ca_cert=dict(required=False, default=None, aliases=["ca_bundle_path"]),
)
return dict(
manageiq_connection=dict(type='dict',
apply_defaults=True,
options=options),
manageiq_connection=dict(type="dict", apply_defaults=True, options=options),
)
def check_client(module):
if not HAS_CLIENT:
module.fail_json(msg=missing_required_lib('manageiq-client'), exception=CLIENT_IMP_ERR)
module.fail_json(msg=missing_required_lib("manageiq-client"), exception=CLIENT_IMP_ERR)
def validate_connection_params(module):
params = module.params['manageiq_connection']
params = module.params["manageiq_connection"]
error_str = "missing required argument: manageiq_connection[{}]"
url = params['url']
token = params['token']
username = params['username']
password = params['password']
url = params["url"]
token = params["token"]
username = params["username"]
password = params["password"]
if (url and username and password) or (url and token):
return params
for arg in ['url', 'username', 'password']:
if params[arg] in (None, ''):
for arg in ["url", "username", "password"]:
if params[arg] in (None, ""):
module.fail_json(msg=error_str.format(arg))
def manageiq_entities():
return {
'provider': 'providers', 'host': 'hosts', 'vm': 'vms',
'category': 'categories', 'cluster': 'clusters', 'data store': 'data_stores',
'group': 'groups', 'resource pool': 'resource_pools', 'service': 'services',
'service template': 'service_templates', 'template': 'templates',
'tenant': 'tenants', 'user': 'users', 'blueprint': 'blueprints'
"provider": "providers",
"host": "hosts",
"vm": "vms",
"category": "categories",
"cluster": "clusters",
"data store": "data_stores",
"group": "groups",
"resource pool": "resource_pools",
"service": "services",
"service template": "service_templates",
"template": "templates",
"tenant": "tenants",
"user": "users",
"blueprint": "blueprints",
}
class ManageIQ:
"""
class encapsulating ManageIQ API client.
class encapsulating ManageIQ API client.
"""
def __init__(self, module):
@ -85,24 +93,26 @@ class ManageIQ:
params = validate_connection_params(module)
url = params['url']
username = params['username']
password = params['password']
token = params['token']
verify_ssl = params['validate_certs']
ca_bundle_path = params['ca_cert']
url = params["url"]
username = params["username"]
password = params["password"]
token = params["token"]
verify_ssl = params["validate_certs"]
ca_bundle_path = params["ca_cert"]
self._module = module
self._api_url = f"{url}/api"
self._auth = dict(user=username, password=password, token=token)
try:
self._client = ManageIQClient(self._api_url, self._auth, verify_ssl=verify_ssl, ca_bundle_path=ca_bundle_path)
self._client = ManageIQClient(
self._api_url, self._auth, verify_ssl=verify_ssl, ca_bundle_path=ca_bundle_path
)
except Exception as e:
self.module.fail_json(msg=f"failed to open connection ({url}): {e}")
@property
def module(self):
""" Ansible module module
"""Ansible module module
Returns:
the ansible module
@ -111,7 +121,7 @@ class ManageIQ:
@property
def api_url(self):
""" Base ManageIQ API
"""Base ManageIQ API
Returns:
the base ManageIQ API
@ -120,7 +130,7 @@ class ManageIQ:
@property
def client(self):
""" ManageIQ client
"""ManageIQ client
Returns:
the ManageIQ client
@ -128,7 +138,7 @@ class ManageIQ:
return self._client
def find_collection_resource_by(self, collection_name, **params):
""" Searches the collection resource by the collection name and the param passed.
"""Searches the collection resource by the collection name and the param passed.
Returns:
the resource as an object if it exists in manageiq, None otherwise.
@ -142,7 +152,7 @@ class ManageIQ:
return vars(entity)
def find_collection_resource_or_fail(self, collection_name, **params):
""" Searches the collection resource by the collection name and the param passed.
"""Searches the collection resource by the collection name and the param passed.
Returns:
the resource as an object if it exists in manageiq, Fail otherwise.
@ -159,12 +169,12 @@ class ManageIQ:
# query resource id, fail if resource does not exist
if resource_id is None:
resource_id = manageiq.find_collection_resource_or_fail(resource_type, name=resource_name)['id']
resource_id = manageiq.find_collection_resource_or_fail(resource_type, name=resource_name)["id"]
return ManageIQPolicies(manageiq, resource_type, resource_id)
def query_resource_id(self, resource_type, resource_name):
""" Query the resource name in ManageIQ.
"""Query the resource name in ManageIQ.
Returns:
the resource ID if it exists in ManageIQ, Fail otherwise.
@ -179,7 +189,7 @@ class ManageIQ:
class ManageIQPolicies:
"""
Object to execute policies management operations of manageiq resources.
Object to execute policies management operations of manageiq resources.
"""
def __init__(self, manageiq, resource_type, resource_id):
@ -191,29 +201,27 @@ class ManageIQPolicies:
self.resource_type = resource_type
self.resource_id = resource_id
self.resource_url = f'{self.api_url}/{resource_type}/{resource_id}'
self.resource_url = f"{self.api_url}/{resource_type}/{resource_id}"
def query_profile_href(self, profile):
""" Add or Update the policy_profile href field
"""Add or Update the policy_profile href field
Example:
{name: STR, ...} => {name: STR, href: STR}
"""
resource = self.manageiq.find_collection_resource_or_fail(
"policy_profiles", **profile)
return dict(name=profile['name'], href=resource['href'])
resource = self.manageiq.find_collection_resource_or_fail("policy_profiles", **profile)
return dict(name=profile["name"], href=resource["href"])
def query_resource_profiles(self):
""" Returns a set of the profile objects objects assigned to the resource
"""
url = '{resource_url}/policy_profiles?expand=resources'
"""Returns a set of the profile objects objects assigned to the resource"""
url = "{resource_url}/policy_profiles?expand=resources"
try:
response = self.client.get(url.format(resource_url=self.resource_url))
except Exception as e:
msg = f"Failed to query {self.resource_type} policies: {e}"
self.module.fail_json(msg=msg)
resources = response.get('resources', [])
resources = response.get("resources", [])
# clean the returned rest api profile object to look like:
# {profile_name: STR, profile_description: STR, policies: ARR<POLICIES>}
@ -222,16 +230,15 @@ class ManageIQPolicies:
return profiles
def query_profile_policies(self, profile_id):
""" Returns a set of the policy objects assigned to the resource
"""
url = '{api_url}/policy_profiles/{profile_id}?expand=policies'
"""Returns a set of the policy objects assigned to the resource"""
url = "{api_url}/policy_profiles/{profile_id}?expand=policies"
try:
response = self.client.get(url.format(api_url=self.api_url, profile_id=profile_id))
except Exception as e:
msg = f"Failed to query {self.resource_type} policies: {e}"
self.module.fail_json(msg=msg)
resources = response.get('policies', [])
resources = response.get("policies", [])
# clean the returned rest api policy object to look like:
# {name: STR, description: STR, active: BOOL}
@ -240,42 +247,36 @@ class ManageIQPolicies:
return policies
def clean_policy_object(self, policy):
""" Clean a policy object to have human readable form of:
"""Clean a policy object to have human readable form of:
{
name: STR,
description: STR,
active: BOOL
}
"""
name = policy.get('name')
description = policy.get('description')
active = policy.get('active')
name = policy.get("name")
description = policy.get("description")
active = policy.get("active")
return dict(
name=name,
description=description,
active=active)
return dict(name=name, description=description, active=active)
def clean_profile_object(self, profile):
""" Clean a profile object to have human readable form of:
"""Clean a profile object to have human readable form of:
{
profile_name: STR,
profile_description: STR,
policies: ARR<POLICIES>
}
"""
profile_id = profile['id']
name = profile.get('name')
description = profile.get('description')
profile_id = profile["id"]
name = profile.get("name")
description = profile.get("description")
policies = self.query_profile_policies(profile_id)
return dict(
profile_name=name,
profile_description=description,
policies=policies)
return dict(profile_name=name, profile_description=description, policies=policies)
def profiles_to_update(self, profiles, action):
""" Create a list of policies we need to update in ManageIQ.
"""Create a list of policies we need to update in ManageIQ.
Returns:
Whether or not a change took place and a message describing the
@ -286,12 +287,12 @@ class ManageIQPolicies:
# make a list of assigned full profile names strings
# e.g. ['openscap profile', ...]
assigned_profiles_set = set(profile['profile_name'] for profile in assigned_profiles)
assigned_profiles_set = set(profile["profile_name"] for profile in assigned_profiles)
for profile in profiles:
assigned = profile.get('name') in assigned_profiles_set
assigned = profile.get("name") in assigned_profiles_set
if (action == 'unassign' and assigned) or (action == 'assign' and not assigned):
if (action == "unassign" and assigned) or (action == "assign" and not assigned):
# add/update the policy profile href field
# {name: STR, ...} => {name: STR, href: STR}
profile = self.query_profile_href(profile)
@ -300,17 +301,14 @@ class ManageIQPolicies:
return profiles_to_post
def assign_or_unassign_profiles(self, profiles, action):
""" Perform assign/unassign action
"""
"""Perform assign/unassign action"""
# get a list of profiles needed to be changed
profiles_to_post = self.profiles_to_update(profiles, action)
if not profiles_to_post:
return dict(
changed=False,
msg=f"Profiles {profiles} already {action}ed, nothing to do")
return dict(changed=False, msg=f"Profiles {profiles} already {action}ed, nothing to do")
# try to assign or unassign profiles to resource
url = f'{self.resource_url}/policy_profiles'
url = f"{self.resource_url}/policy_profiles"
try:
response = self.client.post(url, action=action, resources=profiles_to_post)
except Exception as e:
@ -318,20 +316,18 @@ class ManageIQPolicies:
self.module.fail_json(msg=msg)
# check all entities in result to be successful
for result in response['results']:
if not result['success']:
for result in response["results"]:
if not result["success"]:
msg = f"Failed to {action}: {result['message']}"
self.module.fail_json(msg=msg)
# successfully changed all needed profiles
return dict(
changed=True,
msg=f"Successfully {action}ed profiles: {profiles}")
return dict(changed=True, msg=f"Successfully {action}ed profiles: {profiles}")
class ManageIQTags:
"""
Object to execute tags management operations of manageiq resources.
Object to execute tags management operations of manageiq resources.
"""
def __init__(self, manageiq, resource_type, resource_id):
@ -343,15 +339,14 @@ class ManageIQTags:
self.resource_type = resource_type
self.resource_id = resource_id
self.resource_url = f'{self.api_url}/{resource_type}/{resource_id}'
self.resource_url = f"{self.api_url}/{resource_type}/{resource_id}"
def full_tag_name(self, tag):
""" Returns the full tag name in manageiq
"""
"""Returns the full tag name in manageiq"""
return f"/managed/{tag['category']}/{tag['name']}"
def clean_tag_object(self, tag):
""" Clean a tag object to have human readable form of:
"""Clean a tag object to have human readable form of:
{
full_name: STR,
name: STR,
@ -359,26 +354,26 @@ class ManageIQTags:
category: STR
}
"""
full_name = tag.get('name')
categorization = tag.get('categorization', {})
full_name = tag.get("name")
categorization = tag.get("categorization", {})
return dict(
full_name=full_name,
name=categorization.get('name'),
display_name=categorization.get('display_name'),
category=categorization.get('category', {}).get('name'))
name=categorization.get("name"),
display_name=categorization.get("display_name"),
category=categorization.get("category", {}).get("name"),
)
def query_resource_tags(self):
""" Returns a set of the tag objects assigned to the resource
"""
url = '{resource_url}/tags?expand=resources&attributes=categorization'
"""Returns a set of the tag objects assigned to the resource"""
url = "{resource_url}/tags?expand=resources&attributes=categorization"
try:
response = self.client.get(url.format(resource_url=self.resource_url))
except Exception as e:
msg = f"Failed to query {self.resource_type} tags: {e}"
self.module.fail_json(msg=msg)
resources = response.get('resources', [])
resources = response.get("resources", [])
# clean the returned rest api tag object to look like:
# {full_name: STR, name: STR, display_name: STR, category: STR}
@ -387,7 +382,7 @@ class ManageIQTags:
return tags
def tags_to_update(self, tags, action):
""" Create a list of tags we need to update in ManageIQ.
"""Create a list of tags we need to update in ManageIQ.
Returns:
Whether or not a change took place and a message describing the
@ -398,30 +393,27 @@ class ManageIQTags:
# make a list of assigned full tag names strings
# e.g. ['/managed/environment/prod', ...]
assigned_tags_set = set(tag['full_name'] for tag in assigned_tags)
assigned_tags_set = set(tag["full_name"] for tag in assigned_tags)
for tag in tags:
assigned = self.full_tag_name(tag) in assigned_tags_set
if assigned and action == 'unassign':
if assigned and action == "unassign":
tags_to_post.append(tag)
elif (not assigned) and action == 'assign':
elif (not assigned) and action == "assign":
tags_to_post.append(tag)
return tags_to_post
def assign_or_unassign_tags(self, tags, action):
""" Perform assign/unassign action
"""
"""Perform assign/unassign action"""
# get a list of tags needed to be changed
tags_to_post = self.tags_to_update(tags, action)
if not tags_to_post:
return dict(
changed=False,
msg=f"Tags already {action}ed, nothing to do")
return dict(changed=False, msg=f"Tags already {action}ed, nothing to do")
# try to assign or unassign tags to resource
url = f'{self.resource_url}/tags'
url = f"{self.resource_url}/tags"
try:
response = self.client.post(url, action=action, resources=tags)
except Exception as e:
@ -429,12 +421,10 @@ class ManageIQTags:
self.module.fail_json(msg=msg)
# check all entities in result to be successful
for result in response['results']:
if not result['success']:
for result in response["results"]:
if not result["success"]:
msg = f"Failed to {action}: {result['message']}"
self.module.fail_json(msg=msg)
# successfully changed all needed tags
return dict(
changed=True,
msg=f"Successfully {action}ed tags")
return dict(changed=True, msg=f"Successfully {action}ed tags")