1
0
Fork 0
mirror of https://github.com/ansible-collections/community.general.git synced 2024-09-14 20:13:21 +02:00

use dict comprehension in plugins, part 2 (#8822)

* use dict comprehension in plugins

* add changelog frag
This commit is contained in:
Alexei Znamensky 2024-09-06 07:47:28 +12:00 committed by GitHub
parent ecc048bc12
commit 7e978c77b4
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
21 changed files with 76 additions and 68 deletions

View file

@ -0,0 +1,21 @@
minor_changes:
- credstash lookup plugin - replace Python 2.6 construct with dict comprehensions (https://github.com/ansible-collections/community.general/pull/8822).
- keycloak module utils - replace Python 2.6 construct with dict comprehensions (https://github.com/ansible-collections/community.general/pull/8822).
- deco MH module utils - replace Python 2.6 construct with dict comprehensions (https://github.com/ansible-collections/community.general/pull/8822).
- redfish_utils module utils - replace Python 2.6 construct with dict comprehensions (https://github.com/ansible-collections/community.general/pull/8822).
- scaleway module utils - replace Python 2.6 construct with dict comprehensions (https://github.com/ansible-collections/community.general/pull/8822).
- etcd3 - replace Python 2.6 construct with dict comprehensions (https://github.com/ansible-collections/community.general/pull/8822).
- gitlab_project - replace Python 2.6 construct with dict comprehensions (https://github.com/ansible-collections/community.general/pull/8822).
- hwc_ecs_instance - replace Python 2.6 construct with dict comprehensions (https://github.com/ansible-collections/community.general/pull/8822).
- hwc_evs_disk - replace Python 2.6 construct with dict comprehensions (https://github.com/ansible-collections/community.general/pull/8822).
- hwc_vpc_eip - replace Python 2.6 construct with dict comprehensions (https://github.com/ansible-collections/community.general/pull/8822).
- hwc_vpc_peering_connect - replace Python 2.6 construct with dict comprehensions (https://github.com/ansible-collections/community.general/pull/8822).
- hwc_vpc_port - replace Python 2.6 construct with dict comprehensions (https://github.com/ansible-collections/community.general/pull/8822).
- hwc_vpc_subnet - replace Python 2.6 construct with dict comprehensions (https://github.com/ansible-collections/community.general/pull/8822).
- ipa_otptoken - replace Python 2.6 construct with dict comprehensions (https://github.com/ansible-collections/community.general/pull/8822).
- keycloak_user_federation - replace Python 2.6 construct with dict comprehensions (https://github.com/ansible-collections/community.general/pull/8822).
- lxc_container - replace Python 2.6 construct with dict comprehensions (https://github.com/ansible-collections/community.general/pull/8822).
- proxmox_kvm - replace Python 2.6 construct with dict comprehensions (https://github.com/ansible-collections/community.general/pull/8822).
- scaleway_security_group - replace Python 2.6 construct with dict comprehensions (https://github.com/ansible-collections/community.general/pull/8822).
- ufw - replace Python 2.6 construct with dict comprehensions (https://github.com/ansible-collections/community.general/pull/8822).
- vmadm - replace Python 2.6 construct with dict comprehensions (https://github.com/ansible-collections/community.general/pull/8822).

View file

@ -120,10 +120,10 @@ class LookupModule(LookupBase):
aws_secret_access_key = self.get_option('aws_secret_access_key') aws_secret_access_key = self.get_option('aws_secret_access_key')
aws_session_token = self.get_option('aws_session_token') aws_session_token = self.get_option('aws_session_token')
context = dict( context = {
(k, v) for k, v in kwargs.items() k: v for k, v in kwargs.items()
if k not in ('version', 'region', 'table', 'profile_name', 'aws_access_key_id', 'aws_secret_access_key', 'aws_session_token') if k not in ('version', 'region', 'table', 'profile_name', 'aws_access_key_id', 'aws_secret_access_key', 'aws_session_token')
) }
kwargs_pass = { kwargs_pass = {
'profile_name': profile_name, 'profile_name': profile_name,

View file

@ -185,8 +185,7 @@ def get_token(module_params):
'password': auth_password, 'password': auth_password,
} }
# Remove empty items, for instance missing client_secret # Remove empty items, for instance missing client_secret
payload = dict( payload = {k: v for k, v in temp_payload.items() if v is not None}
(k, v) for k, v in temp_payload.items() if v is not None)
try: try:
r = json.loads(to_native(open_url(auth_url, method='POST', r = json.loads(to_native(open_url(auth_url, method='POST',
validate_certs=validate_certs, http_agent=http_agent, timeout=connection_timeout, validate_certs=validate_certs, http_agent=http_agent, timeout=connection_timeout,

View file

@ -45,11 +45,11 @@ def module_fails_on_exception(func):
@wraps(func) @wraps(func)
def wrapper(self, *args, **kwargs): def wrapper(self, *args, **kwargs):
def fix_key(k):
return k if k not in conflict_list else "_" + k
def fix_var_conflicts(output): def fix_var_conflicts(output):
result = dict([ result = {fix_key(k): v for k, v in output.items()}
(k if k not in conflict_list else "_" + k, v)
for k, v in output.items()
])
return result return result
try: try:

View file

@ -613,9 +613,11 @@ class RedfishUtils(object):
ai = dict((p['Name'], p) ai = dict((p['Name'], p)
for p in params if 'Name' in p) for p in params if 'Name' in p)
if not ai: if not ai:
ai = dict((k[:-24], ai = {
{'AllowableValues': v}) for k, v in action.items() k[:-24]: {'AllowableValues': v}
if k.endswith('@Redfish.AllowableValues')) for k, v in action.items()
if k.endswith('@Redfish.AllowableValues')
}
return ai return ai
def _get_allowable_values(self, action, name, default_values=None): def _get_allowable_values(self, action, name, default_values=None):
@ -2242,7 +2244,7 @@ class RedfishUtils(object):
continue continue
# If already set to requested value, remove it from PATCH payload # If already set to requested value, remove it from PATCH payload
if data[u'Attributes'][attr_name] == attributes[attr_name]: if data[u'Attributes'][attr_name] == attr_value:
del attrs_to_patch[attr_name] del attrs_to_patch[attr_name]
warning = "" warning = ""
@ -2780,9 +2782,11 @@ class RedfishUtils(object):
def virtual_media_insert_via_patch(self, options, param_map, uri, data, image_only=False): def virtual_media_insert_via_patch(self, options, param_map, uri, data, image_only=False):
# get AllowableValues # get AllowableValues
ai = dict((k[:-24], ai = {
{'AllowableValues': v}) for k, v in data.items() k[:-24]: {'AllowableValues': v}
if k.endswith('@Redfish.AllowableValues')) for k, v in data.items()
if k.endswith('@Redfish.AllowableValues')
}
# construct payload # construct payload
payload = self._insert_virt_media_payload(options, param_map, data, ai) payload = self._insert_virt_media_payload(options, param_map, data, ai)
if 'Inserted' not in payload and not image_only: if 'Inserted' not in payload and not image_only:

View file

@ -51,11 +51,11 @@ def scaleway_waitable_resource_argument_spec():
def payload_from_object(scw_object): def payload_from_object(scw_object):
return dict( return {
(k, v) k: v
for k, v in scw_object.items() for k, v in scw_object.items()
if k != 'id' and v is not None if k != 'id' and v is not None
) }
class ScalewayException(Exception): class ScalewayException(Exception):
@ -117,10 +117,7 @@ class SecretVariables(object):
@staticmethod @staticmethod
def list_to_dict(source_list, hashed=False): def list_to_dict(source_list, hashed=False):
key_value = 'hashed_value' if hashed else 'value' key_value = 'hashed_value' if hashed else 'value'
return dict( return {var['key']: var[key_value] for var in source_list}
(var['key'], var[key_value])
for var in source_list
)
@classmethod @classmethod
def decode(cls, secrets_list, values_list): def decode(cls, secrets_list, values_list):

View file

@ -193,13 +193,8 @@ def run_module():
allowed_keys = ['host', 'port', 'ca_cert', 'cert_cert', 'cert_key', allowed_keys = ['host', 'port', 'ca_cert', 'cert_cert', 'cert_key',
'timeout', 'user', 'password'] 'timeout', 'user', 'password']
# TODO(evrardjp): Move this back to a dict comprehension when python 2.7 is
# the minimum supported version client_params = {key: value for key, value in module.params.items() if key in allowed_keys}
# client_params = {key: value for key, value in module.params.items() if key in allowed_keys}
client_params = dict()
for key, value in module.params.items():
if key in allowed_keys:
client_params[key] = value
try: try:
etcd = etcd3.client(**client_params) etcd = etcd3.client(**client_params)
except Exception as exp: except Exception as exp:

View file

@ -534,11 +534,7 @@ class GitLabProject(object):
@param arguments Attributes of the project @param arguments Attributes of the project
''' '''
def get_options_with_value(self, arguments): def get_options_with_value(self, arguments):
ret_arguments = dict() ret_arguments = {k: v for k, v in arguments.items() if v is not None}
for arg_key, arg_value in arguments.items():
if arguments[arg_key] is not None:
ret_arguments[arg_key] = arg_value
return ret_arguments return ret_arguments
''' '''
@ -549,8 +545,8 @@ class GitLabProject(object):
changed = False changed = False
for arg_key, arg_value in arguments.items(): for arg_key, arg_value in arguments.items():
if arguments[arg_key] is not None: if arg_value is not None:
if getattr(project, arg_key, None) != arguments[arg_key]: if getattr(project, arg_key, None) != arg_value:
if arg_key == 'container_expiration_policy': if arg_key == 'container_expiration_policy':
old_val = getattr(project, arg_key, {}) old_val = getattr(project, arg_key, {})
final_val = {key: value for key, value in arg_value.items() if value is not None} final_val = {key: value for key, value in arg_value.items() if value is not None}

View file

@ -1163,8 +1163,7 @@ def send_delete_volume_request(module, params, client, info):
path_parameters = { path_parameters = {
"volume_id": ["volume_id"], "volume_id": ["volume_id"],
} }
data = dict((key, navigate_value(info, path)) data = {key: navigate_value(info, path) for key, path in path_parameters.items()}
for key, path in path_parameters.items())
url = build_path(module, "cloudservers/{id}/detachvolume/{volume_id}", data) url = build_path(module, "cloudservers/{id}/detachvolume/{volume_id}", data)

View file

@ -771,8 +771,7 @@ def async_wait(config, result, client, timeout):
path_parameters = { path_parameters = {
"job_id": ["job_id"], "job_id": ["job_id"],
} }
data = dict((key, navigate_value(result, path)) data = {key: navigate_value(result, path) for key, path in path_parameters.items()}
for key, path in path_parameters.items())
url = build_path(module, "jobs/{job_id}", data) url = build_path(module, "jobs/{job_id}", data)

View file

@ -547,8 +547,7 @@ def async_wait_create(config, result, client, timeout):
path_parameters = { path_parameters = {
"publicip_id": ["publicip", "id"], "publicip_id": ["publicip", "id"],
} }
data = dict((key, navigate_value(result, path)) data = {key: navigate_value(result, path) for key, path in path_parameters.items()}
for key, path in path_parameters.items())
url = build_path(module, "publicips/{publicip_id}", data) url = build_path(module, "publicips/{publicip_id}", data)

View file

@ -407,8 +407,7 @@ def async_wait_create(config, result, client, timeout):
path_parameters = { path_parameters = {
"peering_id": ["peering", "id"], "peering_id": ["peering", "id"],
} }
data = dict((key, navigate_value(result, path)) data = {key: navigate_value(result, path) for key, path in path_parameters.items()}
for key, path in path_parameters.items())
url = build_path(module, "v2.0/vpc/peerings/{peering_id}", data) url = build_path(module, "v2.0/vpc/peerings/{peering_id}", data)

View file

@ -560,8 +560,7 @@ def async_wait_create(config, result, client, timeout):
path_parameters = { path_parameters = {
"port_id": ["port", "id"], "port_id": ["port", "id"],
} }
data = dict((key, navigate_value(result, path)) data = {key: navigate_value(result, path) for key, path in path_parameters.items()}
for key, path in path_parameters.items())
url = build_path(module, "ports/{port_id}", data) url = build_path(module, "ports/{port_id}", data)

View file

@ -440,8 +440,7 @@ def async_wait_create(config, result, client, timeout):
path_parameters = { path_parameters = {
"subnet_id": ["subnet", "id"], "subnet_id": ["subnet", "id"],
} }
data = dict((key, navigate_value(result, path)) data = {key: navigate_value(result, path) for key, path in path_parameters.items()}
for key, path in path_parameters.items())
url = build_path(module, "subnets/{subnet_id}", data) url = build_path(module, "subnets/{subnet_id}", data)
@ -538,8 +537,7 @@ def async_wait_update(config, result, client, timeout):
path_parameters = { path_parameters = {
"subnet_id": ["subnet", "id"], "subnet_id": ["subnet", "id"],
} }
data = dict((key, navigate_value(result, path)) data = {key: navigate_value(result, path) for key, path in path_parameters.items()}
for key, path in path_parameters.items())
url = build_path(module, "subnets/{subnet_id}", data) url = build_path(module, "subnets/{subnet_id}", data)

View file

@ -392,9 +392,7 @@ def ensure(module, client):
'counter': 'ipatokenhotpcounter'} 'counter': 'ipatokenhotpcounter'}
# Create inverse dictionary for mapping return values # Create inverse dictionary for mapping return values
ipa_to_ansible = {} ipa_to_ansible = {v: k for k, v in ansible_to_ipa.items()}
for (k, v) in ansible_to_ipa.items():
ipa_to_ansible[v] = k
unmodifiable_after_creation = ['otptype', 'secretkey', 'algorithm', unmodifiable_after_creation = ['otptype', 'secretkey', 'algorithm',
'digits', 'offset', 'interval', 'counter'] 'digits', 'offset', 'interval', 'counter']

View file

@ -847,8 +847,11 @@ def main():
# Keycloak API expects config parameters to be arrays containing a single string element # Keycloak API expects config parameters to be arrays containing a single string element
if config is not None: if config is not None:
module.params['config'] = dict((k, [str(v).lower() if not isinstance(v, str) else v]) module.params['config'] = {
for k, v in config.items() if config[k] is not None) k: [str(v).lower() if not isinstance(v, str) else v]
for k, v in config.items()
if config[k] is not None
}
if mappers is not None: if mappers is not None:
for mapper in mappers: for mapper in mappers:

View file

@ -683,11 +683,11 @@ class LxcContainerManagement(object):
variables.pop(v, None) variables.pop(v, None)
false_values = BOOLEANS_FALSE.union([None, '']) false_values = BOOLEANS_FALSE.union([None, ''])
result = dict( result = {
(v, self.module.params[k]) v: self.module.params[k]
for k, v in variables.items() for k, v in variables.items()
if self.module.params[k] not in false_values if self.module.params[k] not in false_values
) }
return result return result
def _config(self): def _config(self):

View file

@ -1032,7 +1032,7 @@ class ProxmoxKvmAnsible(ProxmoxAnsible):
# Sanitize kwargs. Remove not defined args and ensure True and False converted to int. # Sanitize kwargs. Remove not defined args and ensure True and False converted to int.
kwargs = {k: v for k, v in kwargs.items() if v is not None} kwargs = {k: v for k, v in kwargs.items() if v is not None}
kwargs.update(dict([k, int(v)] for k, v in kwargs.items() if isinstance(v, bool))) kwargs.update({k: int(v) for k, v in kwargs.items() if isinstance(v, bool)})
version = self.version() version = self.version()
pve_major_version = 3 if version < LooseVersion('4.0') else version.version[0] pve_major_version = 3 if version < LooseVersion('4.0') else version.version[0]
@ -1163,7 +1163,7 @@ class ProxmoxKvmAnsible(ProxmoxAnsible):
for param in valid_clone_params: for param in valid_clone_params:
if self.module.params[param] is not None: if self.module.params[param] is not None:
clone_params[param] = self.module.params[param] clone_params[param] = self.module.params[param]
clone_params.update(dict([k, int(v)] for k, v in clone_params.items() if isinstance(v, bool))) clone_params.update({k: int(v) for k, v in clone_params.items() if isinstance(v, bool)})
taskid = proxmox_node.qemu(vmid).clone.post(newid=newid, name=name, **clone_params) taskid = proxmox_node.qemu(vmid).clone.post(newid=newid, name=name, **clone_params)
else: else:
taskid = proxmox_node.qemu.create(vmid=vmid, name=name, memory=memory, cpu=cpu, cores=cores, sockets=sockets, **kwargs) taskid = proxmox_node.qemu.create(vmid=vmid, name=name, memory=memory, cpu=cpu, cores=cores, sockets=sockets, **kwargs)

View file

@ -135,11 +135,11 @@ from uuid import uuid4
def payload_from_security_group(security_group): def payload_from_security_group(security_group):
return dict( return {
(k, v) k: v
for k, v in security_group.items() for k, v in security_group.items()
if k != 'id' and v is not None if k != 'id' and v is not None
) }
def present_strategy(api, security_group): def present_strategy(api, security_group):

View file

@ -446,7 +446,7 @@ def main():
params = module.params params = module.params
commands = dict((key, params[key]) for key in command_keys if params[key]) commands = {key: params[key] for key in command_keys if params[key]}
# Ensure ufw is available # Ensure ufw is available
ufw_bin = module.get_bin_path('ufw', True) ufw_bin = module.get_bin_path('ufw', True)

View file

@ -558,9 +558,11 @@ def create_payload(module, uuid):
# Filter out the few options that are not valid VM properties. # Filter out the few options that are not valid VM properties.
module_options = ['force', 'state'] module_options = ['force', 'state']
# @TODO make this a simple {} comprehension as soon as py2 is ditched vmdef = {
# @TODO {k: v for k, v in p.items() if k not in module_options} k: v
vmdef = dict([(k, v) for k, v in module.params.items() if k not in module_options and v]) for k, v in module.params.items()
if k not in module_options and v
}
try: try:
vmdef_json = json.dumps(vmdef) vmdef_json = json.dumps(vmdef)