Merge pull request #626 from t-woerner/new_IPAAnsibleModule

New IPAAnsibleModule class
This commit is contained in:
Rafael Guterres Jeffman
2021-09-02 18:19:53 -03:00
committed by GitHub
33 changed files with 1063 additions and 1620 deletions

View File

@@ -44,7 +44,7 @@ else:
import netaddr import netaddr
import gssapi import gssapi
from datetime import datetime from datetime import datetime
from pprint import pformat from contextlib import contextmanager
# ansible-freeipa requires locale to be C, IPA requires utf-8. # ansible-freeipa requires locale to be C, IPA requires utf-8.
os.environ["LANGUAGE"] = "C" os.environ["LANGUAGE"] = "C"
@@ -109,22 +109,6 @@ else:
if six.PY3: if six.PY3:
unicode = str unicode = str
# AnsibleModule argument specs for all modules
ipamodule_base_spec = dict(
ipaadmin_principal=dict(type="str", default="admin"),
ipaadmin_password=dict(type="str", required=False, no_log=True),
)
# Get ipamodule common vars as nonlocal
def get_ipamodule_base_vars(module):
ipaadmin_principal = module_params_get(module, "ipaadmin_principal")
ipaadmin_password = module_params_get(module, "ipaadmin_password")
return dict(
ipaadmin_principal=ipaadmin_principal,
ipaadmin_password=ipaadmin_password,
)
def valid_creds(module, principal): # noqa def valid_creds(module, principal): # noqa
"""Get valid credentials matching the princial, try GSSAPI first.""" """Get valid credentials matching the princial, try GSSAPI first."""
if "KRB5CCNAME" in os.environ: if "KRB5CCNAME" in os.environ:
@@ -254,29 +238,6 @@ else:
return operation(version.parse(VERSION), return operation(version.parse(VERSION),
version.parse(requested_version)) version.parse(requested_version))
def execute_api_command(module, principal, password, command, name, args):
"""
Execute an API command.
Get KRB ticket if not already there, initialize api, connect,
execute command and destroy ticket again if it has been created also.
"""
ccache_dir = None
ccache_name = None
try:
if not valid_creds(module, principal):
ccache_dir, ccache_name = temp_kinit(principal, password)
api_connect()
return api_command(module, command, name, args)
except Exception as e:
module.fail_json(msg=str(e))
finally:
temp_kdestroy(ccache_dir, ccache_name)
# fix pylint inconsistent return
return None
def date_format(value): def date_format(value):
accepted_date_formats = [ accepted_date_formats = [
LDAP_GENERALIZED_TIME_FORMAT, # generalized time LDAP_GENERALIZED_TIME_FORMAT, # generalized time
@@ -568,7 +529,260 @@ else:
def __getattr__(self, name): def __getattr__(self, name):
return self.get(name) return self.get(name)
class FreeIPABaseModule(AnsibleModule): class IPAAnsibleModule(AnsibleModule):
"""
IPA Ansible Module.
This class is an extended version of the Ansible Module that provides
IPA specific methods to simplify module generation.
Simple example:
from ansible.module_utils.ansible_freeipa_module import \
IPAAnsibleModule
def main():
ansible_module = IPAAnsibleModule(
argument_spec=dict(
name=dict(type="str", aliases=["cn"], default=None),
state=dict(type="str", default="present",
choices=["present", "absent"]),
),
)
# Get parameters
name = ansible_module.params_get("name")
state = ansible_module.params_get("state")
# Connect to IPA API
with ansible_module.ipa_connect():
# Execute command
if state == "present":
ansible_module.ipa_command(["command_add", name, {}])
else:
ansible_module.ipa_command(["command_del", name, {}])
# Done
ansible_module.exit_json(changed=True)
if __name__ == "__main__":
main()
"""
# IPAAnsibleModule argument specs used for all modules
ipa_module_base_spec = dict(
ipaadmin_principal=dict(type="str", default="admin"),
ipaadmin_password=dict(type="str", required=False, no_log=True),
)
def __init__(self, *args, **kwargs):
# Extend argument_spec with ipa_module_base_spec
if "argument_spec" in kwargs:
_spec = kwargs["argument_spec"]
_spec.update(self.ipa_module_base_spec)
kwargs["argument_spec"] = _spec
# pylint: disable=super-with-arguments
super(IPAAnsibleModule, self).__init__(*args, **kwargs)
@contextmanager
def ipa_connect(self, context=None):
"""
Create a context with a connection to IPA API.
Parameters
----------
context: string
An optional parameter defining which context API
commands will be executed.
"""
# ipaadmin vars
ipaadmin_principal = self.params_get("ipaadmin_principal")
ipaadmin_password = self.params_get("ipaadmin_password")
ccache_dir = None
ccache_name = None
try:
if not valid_creds(self, ipaadmin_principal):
ccache_dir, ccache_name = temp_kinit(
ipaadmin_principal, ipaadmin_password)
api_connect(context)
except Exception as e:
self.fail_json(msg=str(e))
else:
try:
yield ccache_name
except Exception as e:
self.fail_json(msg=str(e))
finally:
temp_kdestroy(ccache_dir, ccache_name)
def params_get(self, name):
"""
Retrieve value set for module parameter.
Parameters
----------
name: string
The name of the parameter to retrieve.
"""
return module_params_get(self, name)
def ipa_command(self, command, name, args):
"""
Execute an IPA API command with a required `name` argument.
Parameters
----------
command: string
The IPA API command to execute.
name: string
The name parameter to pass to the command.
args: dict
The parameters to pass to the command.
"""
return api_command(self, command, name, args)
def ipa_command_no_name(self, command, args):
"""
Execute an IPA API command requiring no `name` argument.
Parameters
----------
command: string
The IPA API command to execute.
args: dict
The parameters to pass to the command.
"""
return api_command_no_name(self, command, args)
@staticmethod
def ipa_get_domain():
"""Retrieve IPA API domain."""
return api_get_domain()
@staticmethod
def ipa_get_realm():
"""Retrieve IPA API realm."""
return api_get_realm()
@staticmethod
def ipa_command_exists(command):
"""
Check if IPA command is supported.
Parameters
----------
command: string
The IPA API command to verify.
"""
return api_check_command(command)
@staticmethod
def ipa_command_param_exists(command, name):
"""
Check if IPA command support a specific parameter.
Parameters
----------
command: string
The IPA API command to test.
name: string
The parameter name to verify.
"""
return api_check_param(command, name)
@staticmethod
def ipa_check_version(oper, requested_version):
"""
Compare available IPA version.
Parameters
----------
oper: string
The relational operator to use.
requested_version: string
The version to compare to.
"""
return api_check_ipa_version(oper, requested_version)
def execute_ipa_commands(self, commands, handle_result=None,
**handle_result_user_args):
"""
Execute IPA API commands from command list.
Parameters
----------
commands: list of string tuple
The list of commands in the form (name, command and args)
For commands that do not require a 'name', None needs be
used.
handle_result: function
The user function to handle results of the single commands
handle_result_user_args: dict (user args mapping)
The user args to pass to handle_result function
Example (ipauser module):
def handle_result(module, result, command, name, args, exit_args):
if "random" in args and command in ["user_add", "user_mod"] \
and "randompassword" in result["result"]:
exit_args.setdefault(name, {})["randompassword"] = \
result["result"]["randompassword"]
exit_args = {}
changed = module.execute_ipa_commands(commands, handle_result,
exit_args=exit_args)
if len(names) == 1:
ansible_module.exit_json(changed=changed,
user=exit_args[names[0]])
else:
ansible_module.exit_json(changed=changed, user=exit_args)
"""
# No commands, report no changes
if commands is None:
return False
# In check_mode return if there are commands to do
if self.check_mode:
return len(commands) > 0
changed = False
for name, command, args in commands:
try:
if name is None:
result = self.ipa_command_no_name(command, args)
else:
result = self.ipa_command(command, name, args)
if "completed" in result:
if result["completed"] > 0:
changed = True
else:
changed = True
if handle_result is not None:
handle_result(self, result, command, name, args,
**handle_result_user_args)
except Exception as e:
self.fail_json(msg="%s: %s: %s" % (command, name, str(e)))
return changed
class FreeIPABaseModule(IPAAnsibleModule):
""" """
Base class for FreeIPA Ansible modules. Base class for FreeIPA Ansible modules.
@@ -641,10 +855,6 @@ else:
# pylint: disable=super-with-arguments # pylint: disable=super-with-arguments
super(FreeIPABaseModule, self).__init__(*args, **kwargs) super(FreeIPABaseModule, self).__init__(*args, **kwargs)
# Attributes to store kerberos credentials (if needed)
self.ccache_dir = None
self.ccache_name = None
# Status of an execution. Will be changed to True # Status of an execution. Will be changed to True
# if something is actually peformed. # if something is actually peformed.
self.changed = False self.changed = False
@@ -723,64 +933,6 @@ else:
"""Define commands that will be run in IPA server.""" """Define commands that will be run in IPA server."""
raise NotImplementedError raise NotImplementedError
def api_command(self, command, name=None, args=None):
"""Execute a single command in IPA server."""
if args is None:
args = {}
if name is None:
return api_command_no_name(self, command, args)
return api_command(self, command, name, args)
def __enter__(self):
"""
Connect to IPA server.
Check the there are working Kerberos credentials to connect to
IPA server. If there are not we perform a temporary kinit
that will be terminated when exiting the context.
If the connection fails ``ipa_connected`` attribute will be set
to False.
"""
principal = self.ipa_params.ipaadmin_principal
password = self.ipa_params.ipaadmin_password
try:
if not valid_creds(self, principal):
self.ccache_dir, self.ccache_name = temp_kinit(
principal, password,
)
api_connect()
except Exception as excpt:
self.fail_json(msg=str(excpt))
else:
self.ipa_connected = True
return self
def __exit__(self, exc_type, exc_val, exc_tb):
"""
Terminate a connection with the IPA server.
Deal with exceptions, destroy temporary kinit credentials and
exit the module with proper arguments.
"""
# TODO: shouldn't we also disconnect from api backend?
temp_kdestroy(self.ccache_dir, self.ccache_name)
if exc_type == SystemExit:
raise
if exc_val:
self.fail_json(msg=str(exc_val))
self.exit_json(changed=self.changed, **self.exit_args)
def get_command_errors(self, command, result): def get_command_errors(self, command, result):
"""Look for erros into command results.""" """Look for erros into command results."""
# Get all errors # Get all errors
@@ -814,7 +966,7 @@ else:
for name, command, args in self.ipa_commands: for name, command, args in self.ipa_commands:
try: try:
result = self.api_command(command, name, args) result = self.ipa_command(command, name, args)
except Exception as excpt: except Exception as excpt:
self.fail_json(msg="%s: %s: %s" % (command, name, self.fail_json(msg="%s: %s: %s" % (command, name,
str(excpt))) str(excpt)))
@@ -846,16 +998,10 @@ else:
equal = compare_args_ipa(self, command_args, ipa_attrs) equal = compare_args_ipa(self, command_args, ipa_attrs)
return not equal return not equal
def pdebug(self, value):
"""Debug with pretty formatting."""
self.debug(pformat(value))
def ipa_run(self): def ipa_run(self):
"""Execute module actions.""" """Execute module actions."""
with self: with self.ipa_connect():
if not self.ipa_connected:
return
self.check_ipa_params() self.check_ipa_params()
self.define_ipa_commands() self.define_ipa_commands()
self._run_ipa_commands() self._run_ipa_commands()
self.exit_json(changed=self.changed, **self.exit_args)

View File

@@ -22,14 +22,6 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
from ansible.module_utils._text import to_text
from ansible.module_utils.ansible_freeipa_module import (
api_command, api_command_no_name, api_connect, compare_args_ipa,
gen_add_del_lists, temp_kdestroy, temp_kinit, valid_creds,
ipalib_errors
)
from ansible.module_utils.basic import AnsibleModule
ANSIBLE_METADATA = { ANSIBLE_METADATA = {
"metadata_version": "1.0", "metadata_version": "1.0",
"supported_by": "community", "supported_by": "community",
@@ -42,13 +34,9 @@ DOCUMENTATION = """
module: ipaautomember module: ipaautomember
short description: Add and delete FreeIPA Auto Membership Rules. short description: Add and delete FreeIPA Auto Membership Rules.
description: Add, modify and delete an IPA Auto Membership Rules. description: Add, modify and delete an IPA Auto Membership Rules.
extends_documentation_fragment:
- ipamodule_base_docs
options: options:
ipaadmin_principal:
description: The admin principal
default: admin
ipaadmin_password:
description: The admin password
required: false
name: name:
description: The automember rule description: The automember rule
required: true required: true
@@ -138,14 +126,19 @@ RETURN = """
""" """
from ansible.module_utils.ansible_freeipa_module import (
IPAAnsibleModule, compare_args_ipa, gen_add_del_lists, ipalib_errors
)
def find_automember(module, name, grouping): def find_automember(module, name, grouping):
_args = { _args = {
"all": True, "all": True,
"type": to_text(grouping) "type": grouping
} }
try: try:
_result = api_command(module, "automember_show", to_text(name), _args) _result = module.ipa_command("automember_show", name, _args)
except ipalib_errors.NotFound: except ipalib_errors.NotFound:
return None return None
return _result["result"] return _result["result"]
@@ -157,13 +150,13 @@ def gen_condition_args(grouping,
exclusiveregex=None): exclusiveregex=None):
_args = {} _args = {}
if grouping is not None: if grouping is not None:
_args['type'] = to_text(grouping) _args['type'] = grouping
if key is not None: if key is not None:
_args['key'] = to_text(key) _args['key'] = key
if inclusiveregex is not None: if inclusiveregex is not None:
_args['automemberinclusiveregex'] = to_text(inclusiveregex) _args['automemberinclusiveregex'] = inclusiveregex
if exclusiveregex is not None: if exclusiveregex is not None:
_args['automemberexclusiveregex'] = to_text(exclusiveregex) _args['automemberexclusiveregex'] = exclusiveregex
return _args return _args
@@ -171,9 +164,9 @@ def gen_condition_args(grouping,
def gen_args(description, grouping): def gen_args(description, grouping):
_args = {} _args = {}
if description is not None: if description is not None:
_args["description"] = to_text(description) _args["description"] = description
if grouping is not None: if grouping is not None:
_args['type'] = to_text(grouping) _args['type'] = grouping
return _args return _args
@@ -195,12 +188,9 @@ def check_condition_keys(ansible_module, conditions, aciattrs):
def main(): def main():
ansible_module = AnsibleModule( ansible_module = IPAAnsibleModule(
argument_spec=dict( argument_spec=dict(
# general # general
ipaadmin_principal=dict(type="str", default="admin"),
ipaadmin_password=dict(type="str", required=False, no_log=True),
inclusive=dict(type="list", inclusive=dict(type="list",
aliases=["automemberinclusiveregex"], default=None, aliases=["automemberinclusiveregex"], default=None,
options=dict( options=dict(
@@ -235,27 +225,25 @@ def main():
# Get parameters # Get parameters
# general # general
ipaadmin_principal = ansible_module.params.get("ipaadmin_principal") names = ansible_module.params_get("name")
ipaadmin_password = ansible_module.params.get("ipaadmin_password")
names = ansible_module.params.get("name")
# present # present
description = ansible_module.params.get("description") description = ansible_module.params_get("description")
# conditions # conditions
inclusive = ansible_module.params.get("inclusive") inclusive = ansible_module.params_get("inclusive")
exclusive = ansible_module.params.get("exclusive") exclusive = ansible_module.params_get("exclusive")
# action # action
action = ansible_module.params.get("action") action = ansible_module.params_get("action")
# state # state
state = ansible_module.params.get("state") state = ansible_module.params_get("state")
# grouping/type # grouping/type
automember_type = ansible_module.params.get("automember_type") automember_type = ansible_module.params_get("automember_type")
rebuild_users = ansible_module.params.get("users") rebuild_users = ansible_module.params_get("users")
rebuild_hosts = ansible_module.params.get("hosts") rebuild_hosts = ansible_module.params_get("hosts")
if (rebuild_hosts or rebuild_users) and state != "rebuild": if (rebuild_hosts or rebuild_users) and state != "rebuild":
ansible_module.fail_json( ansible_module.fail_json(
@@ -267,15 +255,9 @@ def main():
# Init # Init
changed = False changed = False
exit_args = {} exit_args = {}
ccache_dir = None
ccache_name = None
res_find = None res_find = None
try: with ansible_module.ipa_connect():
if not valid_creds(ansible_module, ipaadmin_principal):
ccache_dir, ccache_name = temp_kinit(ipaadmin_principal,
ipaadmin_password)
api_connect()
commands = [] commands = []
@@ -287,16 +269,16 @@ def main():
if inclusive is not None or exclusive is not None: if inclusive is not None or exclusive is not None:
# automember_type is either "group" or "hostgorup" # automember_type is either "group" or "hostgorup"
if automember_type == "group": if automember_type == "group":
_type = "user" _type = u"user"
elif automember_type == "hostgroup": elif automember_type == "hostgroup":
_type = "host" _type = u"host"
else: else:
ansible_module.fail_json( ansible_module.fail_json(
msg="Bad automember type '%s'" % automember_type) msg="Bad automember type '%s'" % automember_type)
try: try:
aciattrs = api_command( aciattrs = ansible_module.ipa_command(
ansible_module, "json_metadata", to_text(_type), {} "json_metadata", _type, {}
)['objects'][_type]['aciattrs'] )['objects'][_type]['aciattrs']
except Exception as ex: except Exception as ex:
ansible_module.fail_json( ansible_module.fail_json(
@@ -372,7 +354,7 @@ def main():
if action == "automember": if action == "automember":
if res_find is not None: if res_find is not None:
commands.append([name, 'automember_del', commands.append([name, 'automember_del',
{'type': to_text(automember_type)}]) {'type': automember_type}])
elif action == "member": elif action == "member":
if res_find is None: if res_find is None:
@@ -400,17 +382,13 @@ def main():
elif state == "rebuild": elif state == "rebuild":
if automember_type: if automember_type:
commands.append([None, 'automember_rebuild', commands.append([None, 'automember_rebuild',
{"type": to_text(automember_type)}]) {"type": automember_type}])
if rebuild_users: if rebuild_users:
commands.append([None, 'automember_rebuild', commands.append([None, 'automember_rebuild',
{"users": [ {"users": rebuild_users}])
to_text(_u)
for _u in rebuild_users]}])
if rebuild_hosts: if rebuild_hosts:
commands.append([None, 'automember_rebuild', commands.append([None, 'automember_rebuild',
{"hosts": [ {"hosts": rebuild_hosts}])
to_text(_h)
for _h in rebuild_hosts]}])
# Check mode exit # Check mode exit
if ansible_module.check_mode: if ansible_module.check_mode:
@@ -419,10 +397,9 @@ def main():
for name, command, args in commands: for name, command, args in commands:
try: try:
if name is None: if name is None:
result = api_command_no_name(ansible_module, command, args) result = ansible_module.ipa_command_no_name(command, args)
else: else:
result = api_command(ansible_module, command, result = ansible_module.ipa_command(command, name, args)
to_text(name), args)
if "completed" in result: if "completed" in result:
if result["completed"] > 0: if result["completed"] > 0:
@@ -440,12 +417,6 @@ def main():
# as exceptions. Therefore the error section is not here as # as exceptions. Therefore the error section is not here as
# in other modules. # in other modules.
except Exception as e:
ansible_module.fail_json(msg=str(e))
finally:
temp_kdestroy(ccache_dir, ccache_name)
# Done # Done
ansible_module.exit_json(changed=changed, **exit_args) ansible_module.exit_json(changed=changed, **exit_args)

View File

@@ -33,13 +33,9 @@ author: chris procter
short_description: Manage FreeIPA autommount locations short_description: Manage FreeIPA autommount locations
description: description:
- Add and delete an IPA automount location - Add and delete an IPA automount location
extends_documentation_fragment:
- ipamodule_base_docs
options: options:
ipaadmin_principal:
description: The admin principal
default: admin
ipaadmin_password:
description: The admin password
required: false
name: name:
description: The automount location to be managed description: The automount location to be managed
required: true required: true
@@ -79,9 +75,9 @@ class AutomountLocation(FreeIPABaseModule):
def get_location(self, location): def get_location(self, location):
try: try:
response = self.api_command("automountlocation_show", response = self.ipa_command(
location, "automountlocation_show", location, {}
{}) )
except ipalib_errors.NotFound: except ipalib_errors.NotFound:
return None return None
else: else:

View File

@@ -34,13 +34,9 @@ author: chris procter
short_description: Modify IPA global config options short_description: Modify IPA global config options
description: description:
- Modify IPA global config options - Modify IPA global config options
extends_documentation_fragment:
- ipamodule_base_docs
options: options:
ipaadmin_principal:
description: The admin principal
default: admin
ipaadmin_password:
description: The admin password
required: false
maxusername: maxusername:
description: Set the maximum username length between 1-255 description: Set the maximum username length between 1-255
required: false required: false
@@ -159,7 +155,7 @@ EXAMPLES = '''
tasks: tasks:
- name: return current values of the global configuration options - name: return current values of the global configuration options
ipaconfig: ipaconfig:
ipaadmin_password: password ipaadmin_password: SomeADMINpassword
register: result register: result
- name: display default login shell - name: display default login shell
debug: debug:
@@ -167,7 +163,7 @@ EXAMPLES = '''
- name: set defaultshell and maxusername - name: set defaultshell and maxusername
ipaconfig: ipaconfig:
ipaadmin_password: password ipaadmin_password: SomeADMINpassword
defaultshell: /bin/bash defaultshell: /bin/bash
maxusername: 64 maxusername: 64
''' '''
@@ -251,14 +247,12 @@ config:
''' '''
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.ansible_freeipa_module import \
from ansible.module_utils.ansible_freeipa_module import temp_kinit, \ IPAAnsibleModule, compare_args_ipa, ipalib_errors
temp_kdestroy, valid_creds, api_connect, api_command_no_name, \
compare_args_ipa, module_params_get, ipalib_errors
def config_show(module): def config_show(module):
_result = api_command_no_name(module, "config_show", {}) _result = module.ipa_command_no_name("config_show", {})
return _result["result"] return _result["result"]
@@ -270,11 +264,9 @@ def gen_args(params):
def main(): def main():
ansible_module = AnsibleModule( ansible_module = IPAAnsibleModule(
argument_spec=dict( argument_spec=dict(
# general # general
ipaadmin_principal=dict(type="str", default="admin"),
ipaadmin_password=dict(type="str", required=False, no_log=True),
maxusername=dict(type="int", required=False, maxusername=dict(type="int", required=False,
aliases=['ipamaxusernamelength']), aliases=['ipamaxusernamelength']),
maxhostname=dict(type="int", required=False, maxhostname=dict(type="int", required=False,
@@ -334,11 +326,6 @@ def main():
# Get parameters # Get parameters
# general # general
ipaadmin_principal = module_params_get(ansible_module,
"ipaadmin_principal")
ipaadmin_password = module_params_get(ansible_module,
"ipaadmin_password")
field_map = { field_map = {
"maxusername": "ipamaxusernamelength", "maxusername": "ipamaxusernamelength",
"maxhostname": "ipamaxhostnamelength", "maxhostname": "ipamaxhostnamelength",
@@ -366,7 +353,7 @@ def main():
params = {} params = {}
for x in field_map: for x in field_map:
val = module_params_get(ansible_module, x) val = ansible_module.params_get(x)
if val is not None: if val is not None:
params[field_map.get(x, x)] = val params[field_map.get(x, x)] = val
@@ -407,14 +394,11 @@ def main():
changed = False changed = False
exit_args = {} exit_args = {}
ccache_dir = None
ccache_name = None
res_show = None res_show = None
try:
if not valid_creds(ansible_module, ipaadmin_principal): # Connect to IPA API
ccache_dir, ccache_name = temp_kinit(ipaadmin_principal, with ansible_module.ipa_connect():
ipaadmin_password)
api_connect()
if params: if params:
res_show = config_show(ansible_module) res_show = config_show(ansible_module)
params = { params = {
@@ -425,10 +409,13 @@ def main():
and not compare_args_ipa(ansible_module, params, res_show): and not compare_args_ipa(ansible_module, params, res_show):
changed = True changed = True
if not ansible_module.check_mode: if not ansible_module.check_mode:
api_command_no_name(ansible_module, "config_mod", params) try:
ansible_module.ipa_command_no_name("config_mod",
params)
except ipalib_errors.EmptyModlist:
changed = False
else: else:
rawresult = api_command_no_name(ansible_module, "config_show", {}) rawresult = ansible_module.ipa_command_no_name("config_show", {})
result = rawresult['result'] result = rawresult['result']
del result['dn'] del result['dn']
for key, value in result.items(): for key, value in result.items():
@@ -460,13 +447,6 @@ def main():
exit_args[k] = (value[0] == "TRUE") exit_args[k] = (value[0] == "TRUE")
else: else:
exit_args[k] = value exit_args[k] = value
except ipalib_errors.EmptyModlist:
changed = False
except Exception as e:
ansible_module.fail_json(msg="%s %s" % (params, str(e)))
finally:
temp_kdestroy(ccache_dir, ccache_name)
# Done # Done
ansible_module.exit_json(changed=changed, config=exit_args) ansible_module.exit_json(changed=changed, config=exit_args)

View File

@@ -31,13 +31,9 @@ DOCUMENTATION = """
module: ipadelegation module: ipadelegation
short description: Manage FreeIPA delegations short description: Manage FreeIPA delegations
description: Manage FreeIPA delegations and delegation attributes description: Manage FreeIPA delegations and delegation attributes
extends_documentation_fragment:
- ipamodule_base_docs
options: options:
ipaadmin_principal:
description: The admin principal.
default: admin
ipaadmin_password:
description: The admin password.
required: false
name: name:
description: The list of delegation name strings. description: The list of delegation name strings.
required: true required: true
@@ -112,21 +108,14 @@ RETURN = """
""" """
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.ansible_freeipa_module import \ from ansible.module_utils.ansible_freeipa_module import \
temp_kinit, temp_kdestroy, valid_creds, api_connect, api_command, \ IPAAnsibleModule, compare_args_ipa
compare_args_ipa, module_params_get
import six
if six.PY3:
unicode = str
def find_delegation(module, name): def find_delegation(module, name):
"""Find if a delegation with the given name already exist.""" """Find if a delegation with the given name already exist."""
try: try:
_result = api_command(module, "delegation_show", name, {"all": True}) _result = module.ipa_command("delegation_show", name, {"all": True})
except Exception: # pylint: disable=broad-except except Exception: # pylint: disable=broad-except
# An exception is raised if delegation name is not found. # An exception is raised if delegation name is not found.
return None return None
@@ -148,12 +137,9 @@ def gen_args(permission, attribute, membergroup, group):
def main(): def main():
ansible_module = AnsibleModule( ansible_module = IPAAnsibleModule(
argument_spec=dict( argument_spec=dict(
# general # general
ipaadmin_principal=dict(type="str", default="admin"),
ipaadmin_password=dict(type="str", required=False, no_log=True),
name=dict(type="list", aliases=["aciname"], default=None, name=dict(type="list", aliases=["aciname"], default=None,
required=True), required=True),
# present # present
@@ -177,19 +163,16 @@ def main():
# Get parameters # Get parameters
# general # general
ipaadmin_principal = module_params_get(ansible_module, names = ansible_module.params_get("name")
"ipaadmin_principal")
ipaadmin_password = module_params_get(ansible_module, "ipaadmin_password")
names = module_params_get(ansible_module, "name")
# present # present
permission = module_params_get(ansible_module, "permission") permission = ansible_module.params_get("permission")
attribute = module_params_get(ansible_module, "attribute") attribute = ansible_module.params_get("attribute")
membergroup = module_params_get(ansible_module, "membergroup") membergroup = ansible_module.params_get("membergroup")
group = module_params_get(ansible_module, "group") group = ansible_module.params_get("group")
action = module_params_get(ansible_module, "action") action = ansible_module.params_get("action")
# state # state
state = module_params_get(ansible_module, "state") state = ansible_module.params_get("state")
# Check parameters # Check parameters
@@ -236,13 +219,9 @@ def main():
changed = False changed = False
exit_args = {} exit_args = {}
ccache_dir = None
ccache_name = None # Connect to IPA API
try: with ansible_module.ipa_connect():
if not valid_creds(ansible_module, ipaadmin_principal):
ccache_dir, ccache_name = temp_kinit(ipaadmin_principal,
ipaadmin_password)
api_connect()
commands = [] commands = []
for name in names: for name in names:
@@ -318,8 +297,7 @@ def main():
for name, command, args in commands: for name, command, args in commands:
try: try:
result = api_command(ansible_module, command, name, result = ansible_module.ipa_command(command, name, args)
args)
if "completed" in result: if "completed" in result:
if result["completed"] > 0: if result["completed"] > 0:
changed = True changed = True
@@ -329,12 +307,6 @@ def main():
ansible_module.fail_json(msg="%s: %s: %s" % (command, name, ansible_module.fail_json(msg="%s: %s: %s" % (command, name,
str(e))) str(e)))
except Exception as e:
ansible_module.fail_json(msg=str(e))
finally:
temp_kdestroy(ccache_dir, ccache_name)
# Done # Done
ansible_module.exit_json(changed=changed, **exit_args) ansible_module.exit_json(changed=changed, **exit_args)

View File

@@ -32,14 +32,9 @@ DOCUMENTATION = """
module: ipadnsconfig module: ipadnsconfig
short description: Manage FreeIPA dnsconfig short description: Manage FreeIPA dnsconfig
description: Manage FreeIPA dnsconfig description: Manage FreeIPA dnsconfig
extends_documentation_fragment:
- ipamodule_base_docs
options: options:
ipaadmin_principal:
description: The admin principal
default: admin
ipaadmin_password:
description: The admin password
required: false
forwarders: forwarders:
description: The list of global DNS forwarders. description: The list of global DNS forwarders.
required: false required: false
@@ -70,6 +65,7 @@ options:
EXAMPLES = """ EXAMPLES = """
# Ensure global DNS forward configuration, allowing PTR record synchronization. # Ensure global DNS forward configuration, allowing PTR record synchronization.
- ipadnsconfig: - ipadnsconfig:
ipaadmin_password: SomeADMINpassword
forwarders: forwarders:
- ip_address: 8.8.4.4 - ip_address: 8.8.4.4
- ip_address: 2001:4860:4860::8888 - ip_address: 2001:4860:4860::8888
@@ -79,6 +75,7 @@ EXAMPLES = """
# Ensure forwarder is absent. # Ensure forwarder is absent.
- ipadnsconfig: - ipadnsconfig:
ipaadmin_password: SomeADMINpassword
forwarders: forwarders:
- ip_address: 2001:4860:4860::8888 - ip_address: 2001:4860:4860::8888
port: 53 port: 53
@@ -86,21 +83,20 @@ EXAMPLES = """
# Disable PTR record synchronization. # Disable PTR record synchronization.
- ipadnsconfig: - ipadnsconfig:
ipaadmin_password: SomeADMINpassword
allow_sync_ptr: no allow_sync_ptr: no
# Disable global forwarders. # Disable global forwarders.
- ipadnsconfig: - ipadnsconfig:
ipaadmin_password: SomeADMINpassword
forward_policy: none forward_policy: none
""" """
RETURN = """ RETURN = """
""" """
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.ansible_freeipa_module import \
from ansible.module_utils.ansible_freeipa_module import temp_kinit, \ IPAAnsibleModule, compare_args_ipa, is_ipv4_addr, is_ipv6_addr
temp_kdestroy, valid_creds, api_connect, \
api_command_no_name, compare_args_ipa, module_params_get, \
is_ipv4_addr, is_ipv6_addr
def find_dnsconfig(module): def find_dnsconfig(module):
@@ -108,7 +104,7 @@ def find_dnsconfig(module):
"all": True, "all": True,
} }
_result = api_command_no_name(module, "dnsconfig_show", _args) _result = module.ipa_command_no_name("dnsconfig_show", _args)
if "result" in _result: if "result" in _result:
if _result["result"].get('idnsforwarders', None) is None: if _result["result"].get('idnsforwarders', None) is None:
@@ -170,12 +166,8 @@ def main():
port=dict(type=int, required=False, default=None) port=dict(type=int, required=False, default=None)
) )
ansible_module = AnsibleModule( ansible_module = IPAAnsibleModule(
argument_spec=dict( argument_spec=dict(
# general
ipaadmin_principal=dict(type='str', default='admin'),
ipaadmin_password=dict(type='str', no_log=True),
# dnsconfig # dnsconfig
forwarders=dict(type='list', default=None, required=False, forwarders=dict(type='list', default=None, required=False,
options=dict(**forwarder_spec)), options=dict(**forwarder_spec)),
@@ -192,17 +184,12 @@ def main():
ansible_module._ansible_debug = True ansible_module._ansible_debug = True
# general # dnsconfig
ipaadmin_principal = module_params_get(ansible_module, forwarders = ansible_module.params_get('forwarders') or []
"ipaadmin_principal") forward_policy = ansible_module.params_get('forward_policy')
ipaadmin_password = module_params_get(ansible_module, allow_sync_ptr = ansible_module.params_get('allow_sync_ptr')
"ipaadmin_password")
forwarders = module_params_get(ansible_module, 'forwarders') or [] state = ansible_module.params_get('state')
forward_policy = module_params_get(ansible_module, 'forward_policy')
allow_sync_ptr = module_params_get(ansible_module, 'allow_sync_ptr')
state = module_params_get(ansible_module, 'state')
# Check parameters. # Check parameters.
invalid = [] invalid = []
@@ -218,13 +205,9 @@ def main():
# Init # Init
changed = False changed = False
ccache_dir = None
ccache_name = None # Connect to IPA API
try: with ansible_module.ipa_connect():
if not valid_creds(ansible_module, ipaadmin_principal):
ccache_dir, ccache_name = temp_kinit(ipaadmin_principal,
ipaadmin_password)
api_connect()
res_find = find_dnsconfig(ansible_module) res_find = find_dnsconfig(ansible_module)
args = gen_args(ansible_module, state, res_find, forwarders, args = gen_args(ansible_module, state, res_find, forwarders,
@@ -234,7 +217,7 @@ def main():
if not compare_args_ipa(ansible_module, args, res_find): if not compare_args_ipa(ansible_module, args, res_find):
try: try:
if not ansible_module.check_mode: if not ansible_module.check_mode:
api_command_no_name(ansible_module, 'dnsconfig_mod', args) ansible_module.ipa_command_no_name('dnsconfig_mod', args)
# If command did not fail, something changed. # If command did not fail, something changed.
changed = True changed = True
@@ -242,12 +225,6 @@ def main():
msg = str(e) msg = str(e)
ansible_module.fail_json(msg="dnsconfig_mod: %s" % msg) ansible_module.fail_json(msg="dnsconfig_mod: %s" % msg)
except Exception as e:
ansible_module.fail_json(msg=str(e))
finally:
temp_kdestroy(ccache_dir, ccache_name)
# Done # Done
ansible_module.exit_json(changed=changed) ansible_module.exit_json(changed=changed)

View File

@@ -34,13 +34,9 @@ author: chris procter
short_description: Manage FreeIPA DNS Forwarder Zones short_description: Manage FreeIPA DNS Forwarder Zones
description: description:
- Add and delete an IPA DNS Forwarder Zones using IPA API - Add and delete an IPA DNS Forwarder Zones using IPA API
extends_documentation_fragment:
- ipamodule_base_docs
options: options:
ipaadmin_principal:
description: The admin principal
default: admin
ipaadmin_password:
description: The admin password
required: false
name: name:
description: description:
- The DNS zone name which needs to be managed. - The DNS zone name which needs to be managed.
@@ -85,7 +81,7 @@ options:
EXAMPLES = ''' EXAMPLES = '''
# Ensure dns zone is present # Ensure dns zone is present
- ipadnsforwardzone: - ipadnsforwardzone:
ipaadmin_password: MyPassword123 ipaadmin_password: SomeADMINpassword
state: present state: present
name: example.com name: example.com
forwarders: forwarders:
@@ -96,7 +92,7 @@ EXAMPLES = '''
# Ensure dns zone is present, with forwarder on non-default port # Ensure dns zone is present, with forwarder on non-default port
- ipadnsforwardzone: - ipadnsforwardzone:
ipaadmin_password: MyPassword123 ipaadmin_password: SomeADMINpassword
state: present state: present
name: example.com name: example.com
forwarders: forwarders:
@@ -107,7 +103,7 @@ EXAMPLES = '''
# Ensure that dns zone is removed # Ensure that dns zone is removed
- ipadnsforwardzone: - ipadnsforwardzone:
ipaadmin_password: MyPassword123 ipaadmin_password: SomeADMINpassword
name: example.com name: example.com
state: absent state: absent
''' '''
@@ -116,11 +112,9 @@ RETURN = '''
''' '''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_text from ansible.module_utils._text import to_text
from ansible.module_utils.ansible_freeipa_module import temp_kinit, \ from ansible.module_utils.ansible_freeipa_module import \
temp_kdestroy, valid_creds, api_connect, api_command, compare_args_ipa, \ IPAAnsibleModule, compare_args_ipa
module_params_get
def find_dnsforwardzone(module, name): def find_dnsforwardzone(module, name):
@@ -128,7 +122,7 @@ def find_dnsforwardzone(module, name):
"all": True, "all": True,
"idnsname": name "idnsname": name
} }
_result = api_command(module, "dnsforwardzone_find", name, _args) _result = module.ipa_command("dnsforwardzone_find", name, _args)
if len(_result["result"]) > 1: if len(_result["result"]) > 1:
module.fail_json( module.fail_json(
@@ -167,11 +161,9 @@ def forwarder_list(forwarders):
def main(): def main():
ansible_module = AnsibleModule( ansible_module = IPAAnsibleModule(
argument_spec=dict( argument_spec=dict(
# general # general
ipaadmin_principal=dict(type="str", default="admin"),
ipaadmin_password=dict(type="str", required=False, no_log=True),
name=dict(type="list", aliases=["cn"], default=None, name=dict(type="list", aliases=["cn"], default=None,
required=True), required=True),
forwarders=dict(type="list", default=None, required=False, forwarders=dict(type="list", default=None, required=False,
@@ -199,19 +191,14 @@ def main():
ansible_module._ansible_debug = True ansible_module._ansible_debug = True
# Get parameters # Get parameters
ipaadmin_principal = module_params_get(ansible_module, names = ansible_module.params_get("name")
"ipaadmin_principal") action = ansible_module.params_get("action")
ipaadmin_password = module_params_get(ansible_module,
"ipaadmin_password")
names = module_params_get(ansible_module, "name")
action = module_params_get(ansible_module, "action")
forwarders = forwarder_list( forwarders = forwarder_list(
module_params_get(ansible_module, "forwarders")) ansible_module.params_get("forwarders"))
forwardpolicy = module_params_get(ansible_module, "forwardpolicy") forwardpolicy = ansible_module.params_get("forwardpolicy")
skip_overlap_check = module_params_get(ansible_module, skip_overlap_check = ansible_module.params_get("skip_overlap_check")
"skip_overlap_check") permission = ansible_module.params_get("permission")
permission = module_params_get(ansible_module, "permission") state = ansible_module.params_get("state")
state = module_params_get(ansible_module, "state")
if state == 'present' and len(names) != 1: if state == 'present' and len(names) != 1:
ansible_module.fail_json( ansible_module.fail_json(
@@ -257,21 +244,17 @@ def main():
changed = False changed = False
exit_args = {} exit_args = {}
args = {} args = {}
ccache_dir = None
ccache_name = None
is_enabled = "IGNORE" is_enabled = "IGNORE"
try:
# Connect to IPA API
with ansible_module.ipa_connect():
# we need to determine 3 variables # we need to determine 3 variables
# args = the values we want to change/set # args = the values we want to change/set
# command = the ipa api command to call del, add, or mod # command = the ipa api command to call del, add, or mod
# is_enabled = is the current resource enabled (True) # is_enabled = is the current resource enabled (True)
# disabled (False) and do we care (IGNORE) # disabled (False) and do we care (IGNORE)
if not valid_creds(ansible_module, ipaadmin_principal):
ccache_dir, ccache_name = temp_kinit(ipaadmin_principal,
ipaadmin_password)
api_connect()
for name in names: for name in names:
commands = [] commands = []
command = None command = None
@@ -387,15 +370,9 @@ def main():
# Execute commands # Execute commands
for _name, command, args in commands: for _name, command, args in commands:
api_command(ansible_module, command, _name, args) ansible_module.ipa_command(command, _name, args)
changed = True changed = True
except Exception as e:
ansible_module.fail_json(msg=str(e))
finally:
temp_kdestroy(ccache_dir, ccache_name)
# Done # Done
ansible_module.exit_json(changed=changed, dnsforwardzone=exit_args) ansible_module.exit_json(changed=changed, dnsforwardzone=exit_args)

View File

@@ -33,13 +33,9 @@ DOCUMENTATION = """
module: ipadnsrecord module: ipadnsrecord
short description: Manage FreeIPA DNS records short description: Manage FreeIPA DNS records
description: Manage FreeIPA DNS records description: Manage FreeIPA DNS records
extends_documentation_fragment:
- ipamodule_base_docs
options: options:
ipaadmin_principal:
description: The admin principal
default: admin
ipaadmin_password:
description: The admin password
required: false
records: records:
description: The list of user dns records dicts description: The list of user dns records dicts
required: false required: false
@@ -864,11 +860,9 @@ RETURN = """
""" """
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_text from ansible.module_utils._text import to_text
from ansible.module_utils.ansible_freeipa_module import temp_kinit, \ from ansible.module_utils.ansible_freeipa_module import \
temp_kdestroy, valid_creds, api_connect, api_command, module_params_get, \ IPAAnsibleModule, is_ipv4_addr, is_ipv6_addr, ipalib_errors
is_ipv4_addr, is_ipv6_addr, ipalib_errors
import dns.reversename import dns.reversename
import dns.resolver import dns.resolver
@@ -1106,12 +1100,9 @@ def configure_module():
uri_weight=dict(type='int', required=False), uri_weight=dict(type='int', required=False),
) )
ansible_module = AnsibleModule( ansible_module = IPAAnsibleModule(
argument_spec=dict( argument_spec=dict(
# general # general
ipaadmin_principal=dict(type="str", default="admin"),
ipaadmin_password=dict(type="str", no_log=True),
name=dict(type="list", aliases=["record_name"], default=None, name=dict(type="list", aliases=["record_name"], default=None,
required=False), required=False),
@@ -1148,8 +1139,8 @@ def find_dnsrecord(module, dnszone, name):
} }
try: try:
_result = api_command( _result = module.ipa_command(
module, "dnsrecord_show", to_text(dnszone), _args) "dnsrecord_show", to_text(dnszone), _args)
except ipalib_errors.NotFound: except ipalib_errors.NotFound:
return None return None
@@ -1217,21 +1208,6 @@ def check_parameters(module, state, zone_name, record):
(x, state)) (x, state))
def connect_to_api(module):
"""Connect to the IPA API."""
ipaadmin_principal = module_params_get(module, "ipaadmin_principal")
ipaadmin_password = module_params_get(module, "ipaadmin_password")
ccache_dir = None
ccache_name = None
if not valid_creds(module, ipaadmin_principal):
ccache_dir, ccache_name = temp_kinit(ipaadmin_principal,
ipaadmin_password)
api_connect()
return ccache_dir, ccache_name
def get_entry_from_module(module, name): def get_entry_from_module(module, name):
"""Create an entry dict from attributes in module.""" """Create an entry dict from attributes in module."""
attrs = [ attrs = [
@@ -1243,9 +1219,9 @@ def get_entry_from_module(module, name):
for key_set in [_RECORD_FIELDS, _PART_MAP, attrs]: for key_set in [_RECORD_FIELDS, _PART_MAP, attrs]:
entry.update({ entry.update({
key: module_params_get(module, key) key: module.params_get(key)
for key in key_set for key in key_set
if module_params_get(module, key) is not None if module.params_get(key) is not None
}) })
return entry return entry
@@ -1436,10 +1412,10 @@ def main():
"""Execute DNS record playbook.""" """Execute DNS record playbook."""
ansible_module = configure_module() ansible_module = configure_module()
global_zone_name = module_params_get(ansible_module, "zone_name") global_zone_name = ansible_module.params_get("zone_name")
names = module_params_get(ansible_module, "name") names = ansible_module.params_get("name")
records = module_params_get(ansible_module, "records") records = ansible_module.params_get("records")
state = module_params_get(ansible_module, "state") state = ansible_module.params_get("state")
# Check parameters # Check parameters
@@ -1459,11 +1435,9 @@ def main():
changed = False changed = False
exit_args = {} exit_args = {}
ccache_dir = None
ccache_name = None
try: # Connect to IPA API
ccache_dir, ccache_name = connect_to_api(ansible_module) with ansible_module.ipa_connect():
commands = [] commands = []
@@ -1501,8 +1475,8 @@ def main():
# Execute commands # Execute commands
for name, command, args in commands: for name, command, args in commands:
try: try:
result = api_command( result = ansible_module.ipa_command(
ansible_module, command, to_text(name), args) command, to_text(name), args)
if "completed" in result: if "completed" in result:
if result["completed"] > 0: if result["completed"] > 0:
changed = True changed = True
@@ -1519,12 +1493,6 @@ def main():
ansible_module.fail_json( ansible_module.fail_json(
msg="%s: %s: %s" % (command, name, error_message)) msg="%s: %s: %s" % (command, name, error_message))
except Exception as e:
ansible_module.fail_json(msg=str(e))
finally:
temp_kdestroy(ccache_dir, ccache_name)
# Done # Done
ansible_module.exit_json(changed=changed, host=exit_args) ansible_module.exit_json(changed=changed, host=exit_args)

View File

@@ -31,13 +31,9 @@ DOCUMENTATION = """
module: ipadnszone module: ipadnszone
short description: Manage FreeIPA dnszone short description: Manage FreeIPA dnszone
description: Manage FreeIPA dnszone description: Manage FreeIPA dnszone
extends_documentation_fragment:
- ipamodule_base_docs
options: options:
ipaadmin_principal:
description: The admin principal
default: admin
ipaadmin_password:
description: The admin password
required: false
name: name:
description: The zone name string. description: The zone name string.
required: true required: true
@@ -408,7 +404,9 @@ class DNSZoneModule(FreeIPABaseModule):
get_zone_args = {"idnsname": zone_name, "all": True} get_zone_args = {"idnsname": zone_name, "all": True}
try: try:
response = self.api_command("dnszone_show", args=get_zone_args) response = self.ipa_command_no_name(
"dnszone_show", args=get_zone_args
)
except ipalib_errors.NotFound: except ipalib_errors.NotFound:
zone = None zone = None
is_zone_active = False is_zone_active = False

View File

@@ -31,13 +31,9 @@ DOCUMENTATION = """
module: ipagroup module: ipagroup
short description: Manage FreeIPA groups short description: Manage FreeIPA groups
description: Manage FreeIPA groups description: Manage FreeIPA groups
extends_documentation_fragment:
- ipamodule_base_docs
options: options:
ipaadmin_principal:
description: The admin principal
default: admin
ipaadmin_password:
description: The admin password
required: false
name: name:
description: The group name description: The group name
required: false required: false
@@ -182,10 +178,8 @@ EXAMPLES = """
RETURN = """ RETURN = """
""" """
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.ansible_freeipa_module import \
from ansible.module_utils.ansible_freeipa_module import temp_kinit, \ IPAAnsibleModule, compare_args_ipa, gen_add_del_lists, \
temp_kdestroy, valid_creds, api_connect, api_command, compare_args_ipa, \
api_check_param, module_params_get, gen_add_del_lists, api_check_command, \
gen_add_list, gen_intersection_list gen_add_list, gen_intersection_list
@@ -195,7 +189,7 @@ def find_group(module, name):
"cn": name, "cn": name,
} }
_result = api_command(module, "group_find", name, _args) _result = module.ipa_command("group_find", name, _args)
if len(_result["result"]) > 1: if len(_result["result"]) > 1:
module.fail_json( module.fail_json(
@@ -278,12 +272,9 @@ def should_modify_group(module, res_find, args, nonposix, posix, external):
def main(): def main():
ansible_module = AnsibleModule( ansible_module = IPAAnsibleModule(
argument_spec=dict( argument_spec=dict(
# general # general
ipaadmin_principal=dict(type="str", default="admin"),
ipaadmin_password=dict(type="str", required=False, no_log=True),
name=dict(type="list", aliases=["cn"], default=None, name=dict(type="list", aliases=["cn"], default=None,
required=True), required=True),
# present # present
@@ -319,31 +310,24 @@ def main():
# Get parameters # Get parameters
# general # general
ipaadmin_principal = module_params_get( names = ansible_module.params_get("name")
ansible_module,
"ipaadmin_principal",
)
ipaadmin_password = module_params_get(ansible_module, "ipaadmin_password")
names = module_params_get(ansible_module, "name")
# present # present
description = module_params_get(ansible_module, "description") description = ansible_module.params_get("description")
gid = module_params_get(ansible_module, "gid") gid = ansible_module.params_get("gid")
nonposix = module_params_get(ansible_module, "nonposix") nonposix = ansible_module.params_get("nonposix")
external = module_params_get(ansible_module, "external") external = ansible_module.params_get("external")
posix = module_params_get(ansible_module, "posix") posix = ansible_module.params_get("posix")
nomembers = module_params_get(ansible_module, "nomembers") nomembers = ansible_module.params_get("nomembers")
user = module_params_get(ansible_module, "user") user = ansible_module.params_get("user")
group = module_params_get(ansible_module, "group") group = ansible_module.params_get("group")
service = module_params_get(ansible_module, "service") service = ansible_module.params_get("service")
membermanager_user = module_params_get(ansible_module, membermanager_user = ansible_module.params_get("membermanager_user")
"membermanager_user") membermanager_group = ansible_module.params_get("membermanager_group")
membermanager_group = module_params_get(ansible_module, externalmember = ansible_module.params_get("externalmember")
"membermanager_group") action = ansible_module.params_get("action")
externalmember = module_params_get(ansible_module, "externalmember")
action = module_params_get(ansible_module, "action")
# state # state
state = module_params_get(ansible_module, "state") state = ansible_module.params_get("state")
# Check parameters # Check parameters
@@ -378,21 +362,19 @@ def main():
changed = False changed = False
exit_args = {} exit_args = {}
ccache_dir = None
ccache_name = None
try:
if not valid_creds(ansible_module, ipaadmin_principal):
ccache_dir, ccache_name = temp_kinit(ipaadmin_principal,
ipaadmin_password)
api_connect()
has_add_member_service = api_check_param("group_add_member", "service") # Connect to IPA API
with ansible_module.ipa_connect():
has_add_member_service = ansible_module.ipa_command_param_exists(
"group_add_member", "service")
if service is not None and not has_add_member_service: if service is not None and not has_add_member_service:
ansible_module.fail_json( ansible_module.fail_json(
msg="Managing a service as part of a group is not supported " msg="Managing a service as part of a group is not supported "
"by your IPA version") "by your IPA version")
has_add_membermanager = api_check_command("group_add_member_manager") has_add_membermanager = ansible_module.ipa_command_exists(
"group_add_member_manager")
if ((membermanager_user is not None or if ((membermanager_user is not None or
membermanager_group is not None) and not has_add_membermanager): membermanager_group is not None) and not has_add_membermanager):
ansible_module.fail_json( ansible_module.fail_json(
@@ -684,8 +666,7 @@ def main():
for name, command, args in commands: for name, command, args in commands:
try: try:
result = api_command(ansible_module, command, name, result = ansible_module.ipa_command(command, name, args)
args)
if "completed" in result: if "completed" in result:
if result["completed"] > 0: if result["completed"] > 0:
changed = True changed = True
@@ -706,12 +687,6 @@ def main():
if len(errors) > 0: if len(errors) > 0:
ansible_module.fail_json(msg=", ".join(errors)) ansible_module.fail_json(msg=", ".join(errors))
except Exception as e:
ansible_module.fail_json(msg=str(e))
finally:
temp_kdestroy(ccache_dir, ccache_name)
# Done # Done
ansible_module.exit_json(changed=changed, **exit_args) ansible_module.exit_json(changed=changed, **exit_args)

View File

@@ -31,13 +31,9 @@ DOCUMENTATION = """
module: ipahbacrule module: ipahbacrule
short description: Manage FreeIPA HBAC rules short description: Manage FreeIPA HBAC rules
description: Manage FreeIPA HBAC rules description: Manage FreeIPA HBAC rules
extends_documentation_fragment:
- ipamodule_base_docs
options: options:
ipaadmin_principal:
description: The admin principal
default: admin
ipaadmin_password:
description: The admin password
required: false
name: name:
description: The hbacrule name description: The hbacrule name
required: true required: true
@@ -156,11 +152,9 @@ EXAMPLES = """
RETURN = """ RETURN = """
""" """
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.ansible_freeipa_module import \
from ansible.module_utils.ansible_freeipa_module import temp_kinit, \ IPAAnsibleModule, compare_args_ipa, gen_add_del_lists, gen_add_list, \
temp_kdestroy, valid_creds, api_connect, api_command, compare_args_ipa, \ gen_intersection_list, ensure_fqdn
module_params_get, gen_add_del_lists, gen_add_list, \
gen_intersection_list, api_get_domain, ensure_fqdn
def find_hbacrule(module, name): def find_hbacrule(module, name):
@@ -169,7 +163,7 @@ def find_hbacrule(module, name):
"cn": name, "cn": name,
} }
_result = api_command(module, "hbacrule_find", name, _args) _result = module.ipa_command("hbacrule_find", name, _args)
if len(_result["result"]) > 1: if len(_result["result"]) > 1:
module.fail_json( module.fail_json(
@@ -198,12 +192,9 @@ def gen_args(description, usercategory, hostcategory, servicecategory,
def main(): def main():
ansible_module = AnsibleModule( ansible_module = IPAAnsibleModule(
argument_spec=dict( argument_spec=dict(
# general # general
ipaadmin_principal=dict(type="str", default="admin"),
ipaadmin_password=dict(type="str", required=False, no_log=True),
name=dict(type="list", aliases=["cn"], default=None, name=dict(type="list", aliases=["cn"], default=None,
required=True), required=True),
# present # present
@@ -236,26 +227,23 @@ def main():
# Get parameters # Get parameters
# general # general
ipaadmin_principal = module_params_get(ansible_module, names = ansible_module.params_get("name")
"ipaadmin_principal")
ipaadmin_password = module_params_get(ansible_module, "ipaadmin_password")
names = module_params_get(ansible_module, "name")
# present # present
description = module_params_get(ansible_module, "description") description = ansible_module.params_get("description")
usercategory = module_params_get(ansible_module, "usercategory") usercategory = ansible_module.params_get("usercategory")
hostcategory = module_params_get(ansible_module, "hostcategory") hostcategory = ansible_module.params_get("hostcategory")
servicecategory = module_params_get(ansible_module, "servicecategory") servicecategory = ansible_module.params_get("servicecategory")
nomembers = module_params_get(ansible_module, "nomembers") nomembers = ansible_module.params_get("nomembers")
host = module_params_get(ansible_module, "host") host = ansible_module.params_get("host")
hostgroup = module_params_get(ansible_module, "hostgroup") hostgroup = ansible_module.params_get("hostgroup")
hbacsvc = module_params_get(ansible_module, "hbacsvc") hbacsvc = ansible_module.params_get("hbacsvc")
hbacsvcgroup = module_params_get(ansible_module, "hbacsvcgroup") hbacsvcgroup = ansible_module.params_get("hbacsvcgroup")
user = module_params_get(ansible_module, "user") user = ansible_module.params_get("user")
group = module_params_get(ansible_module, "group") group = ansible_module.params_get("group")
action = module_params_get(ansible_module, "action") action = ansible_module.params_get("action")
# state # state
state = module_params_get(ansible_module, "state") state = ansible_module.params_get("state")
# Check parameters # Check parameters
@@ -318,16 +306,12 @@ def main():
changed = False changed = False
exit_args = {} exit_args = {}
ccache_dir = None
ccache_name = None # Connect to IPA API
try: with ansible_module.ipa_connect():
if not valid_creds(ansible_module, ipaadmin_principal):
ccache_dir, ccache_name = temp_kinit(ipaadmin_principal,
ipaadmin_password)
api_connect()
# Get default domain # Get default domain
default_domain = api_get_domain() default_domain = ansible_module.ipa_get_domain()
# Ensure fqdn host names, use default domain for simple names # Ensure fqdn host names, use default domain for simple names
if host is not None: if host is not None:
@@ -620,8 +604,7 @@ def main():
errors = [] errors = []
for name, command, args in commands: for name, command, args in commands:
try: try:
result = api_command(ansible_module, command, name, result = ansible_module.ipa_command(command, name, args)
args)
if "completed" in result: if "completed" in result:
if result["completed"] > 0: if result["completed"] > 0:
changed = True changed = True
@@ -642,12 +625,6 @@ def main():
if len(errors) > 0: if len(errors) > 0:
ansible_module.fail_json(msg=", ".join(errors)) ansible_module.fail_json(msg=", ".join(errors))
except Exception as e:
ansible_module.fail_json(msg=str(e))
finally:
temp_kdestroy(ccache_dir, ccache_name)
# Done # Done
ansible_module.exit_json(changed=changed, **exit_args) ansible_module.exit_json(changed=changed, **exit_args)

View File

@@ -31,13 +31,9 @@ DOCUMENTATION = """
module: ipahbacsvc module: ipahbacsvc
short description: Manage FreeIPA HBAC Services short description: Manage FreeIPA HBAC Services
description: Manage FreeIPA HBAC Services description: Manage FreeIPA HBAC Services
extends_documentation_fragment:
- ipamodule_base_docs
options: options:
ipaadmin_principal:
description: The admin principal
default: admin
ipaadmin_password:
description: The admin password
required: false
name: name:
description: The group name description: The group name
required: false required: false
@@ -70,19 +66,17 @@ EXAMPLES = """
RETURN = """ RETURN = """
""" """
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.ansible_freeipa_module import \
from ansible.module_utils._text import to_text IPAAnsibleModule, compare_args_ipa
from ansible.module_utils.ansible_freeipa_module import temp_kinit, \
temp_kdestroy, valid_creds, api_connect, api_command, compare_args_ipa
def find_hbacsvc(module, name): def find_hbacsvc(module, name):
_args = { _args = {
"all": True, "all": True,
"cn": to_text(name), "cn": name,
} }
_result = api_command(module, "hbacsvc_find", to_text(name), _args) _result = module.ipa_command("hbacsvc_find", name, _args)
if len(_result["result"]) > 1: if len(_result["result"]) > 1:
module.fail_json( module.fail_json(
@@ -96,18 +90,15 @@ def find_hbacsvc(module, name):
def gen_args(description): def gen_args(description):
_args = {} _args = {}
if description is not None: if description is not None:
_args["description"] = to_text(description) _args["description"] = description
return _args return _args
def main(): def main():
ansible_module = AnsibleModule( ansible_module = IPAAnsibleModule(
argument_spec=dict( argument_spec=dict(
# general # general
ipaadmin_principal=dict(type="str", default="admin"),
ipaadmin_password=dict(type="str", required=False, no_log=True),
name=dict(type="list", aliases=["cn", "service"], default=None, name=dict(type="list", aliases=["cn", "service"], default=None,
required=True), required=True),
# present # present
@@ -126,15 +117,13 @@ def main():
# Get parameters # Get parameters
# general # general
ipaadmin_principal = ansible_module.params.get("ipaadmin_principal") names = ansible_module.params_get("name")
ipaadmin_password = ansible_module.params.get("ipaadmin_password")
names = ansible_module.params.get("name")
# present # present
description = ansible_module.params.get("description") description = ansible_module.params_get("description")
# state # state
state = ansible_module.params.get("state") state = ansible_module.params_get("state")
# Check parameters # Check parameters
@@ -158,13 +147,9 @@ def main():
changed = False changed = False
exit_args = {} exit_args = {}
ccache_dir = None
ccache_name = None # Connect to IPA API
try: with ansible_module.ipa_connect():
if not valid_creds(ansible_module, ipaadmin_principal):
ccache_dir, ccache_name = temp_kinit(ipaadmin_principal,
ipaadmin_password)
api_connect()
commands = [] commands = []
@@ -203,18 +188,12 @@ def main():
for name, command, args in commands: for name, command, args in commands:
try: try:
api_command(ansible_module, command, to_text(name), args) ansible_module.ipa_command(command, name, args)
changed = True changed = True
except Exception as e: except Exception as e:
ansible_module.fail_json(msg="%s: %s: %s" % (command, name, ansible_module.fail_json(msg="%s: %s: %s" % (command, name,
str(e))) str(e)))
except Exception as e:
ansible_module.fail_json(msg=str(e))
finally:
temp_kdestroy(ccache_dir, ccache_name)
# Done # Done
ansible_module.exit_json(changed=changed, **exit_args) ansible_module.exit_json(changed=changed, **exit_args)

View File

@@ -32,13 +32,9 @@ DOCUMENTATION = """
module: ipahbacsvcgroup module: ipahbacsvcgroup
short description: Manage FreeIPA hbacsvcgroups short description: Manage FreeIPA hbacsvcgroups
description: Manage FreeIPA hbacsvcgroups description: Manage FreeIPA hbacsvcgroups
extends_documentation_fragment:
- ipamodule_base_docs
options: options:
ipaadmin_principal:
description: The admin principal
default: admin
ipaadmin_password:
description: The admin password
required: false
name: name:
description: The hbacsvcgroup name description: The hbacsvcgroup name
required: false required: false
@@ -101,20 +97,17 @@ EXAMPLES = """
RETURN = """ RETURN = """
""" """
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.ansible_freeipa_module import \
from ansible.module_utils._text import to_text IPAAnsibleModule, compare_args_ipa, gen_add_del_lists
from ansible.module_utils.ansible_freeipa_module import temp_kinit, \
temp_kdestroy, valid_creds, api_connect, api_command, compare_args_ipa, \
gen_add_del_lists
def find_hbacsvcgroup(module, name): def find_hbacsvcgroup(module, name):
_args = { _args = {
"all": True, "all": True,
"cn": to_text(name), "cn": name,
} }
_result = api_command(module, "hbacsvcgroup_find", to_text(name), _args) _result = module.ipa_command("hbacsvcgroup_find", name, _args)
if len(_result["result"]) > 1: if len(_result["result"]) > 1:
module.fail_json( module.fail_json(
@@ -128,7 +121,7 @@ def find_hbacsvcgroup(module, name):
def gen_args(description, nomembers): def gen_args(description, nomembers):
_args = {} _args = {}
if description is not None: if description is not None:
_args["description"] = to_text(description) _args["description"] = description
if nomembers is not None: if nomembers is not None:
_args["nomembers"] = nomembers _args["nomembers"] = nomembers
@@ -138,18 +131,15 @@ def gen_args(description, nomembers):
def gen_member_args(hbacsvc): def gen_member_args(hbacsvc):
_args = {} _args = {}
if hbacsvc is not None: if hbacsvc is not None:
_args["member_hbacsvc"] = [to_text(svc) for svc in hbacsvc] _args["member_hbacsvc"] = hbacsvc
return _args return _args
def main(): def main():
ansible_module = AnsibleModule( ansible_module = IPAAnsibleModule(
argument_spec=dict( argument_spec=dict(
# general # general
ipaadmin_principal=dict(type="str", default="admin"),
ipaadmin_password=dict(type="str", required=False, no_log=True),
name=dict(type="list", aliases=["cn"], default=None, name=dict(type="list", aliases=["cn"], default=None,
required=True), required=True),
# present # present
@@ -170,17 +160,15 @@ def main():
# Get parameters # Get parameters
# general # general
ipaadmin_principal = ansible_module.params.get("ipaadmin_principal") names = ansible_module.params_get("name")
ipaadmin_password = ansible_module.params.get("ipaadmin_password")
names = ansible_module.params.get("name")
# present # present
description = ansible_module.params.get("description") description = ansible_module.params_get("description")
nomembers = ansible_module.params.get("nomembers") nomembers = ansible_module.params_get("nomembers")
hbacsvc = ansible_module.params.get("hbacsvc") hbacsvc = ansible_module.params_get("hbacsvc")
action = ansible_module.params.get("action") action = ansible_module.params_get("action")
# state # state
state = ansible_module.params.get("state") state = ansible_module.params_get("state")
# Check parameters # Check parameters
@@ -213,13 +201,9 @@ def main():
changed = False changed = False
exit_args = {} exit_args = {}
ccache_dir = None
ccache_name = None # Connect to IPA API
try: with ansible_module.ipa_connect():
if not valid_creds(ansible_module, ipaadmin_principal):
ccache_dir, ccache_name = temp_kinit(ipaadmin_principal,
ipaadmin_password)
api_connect()
commands = [] commands = []
@@ -257,18 +241,14 @@ def main():
if len(hbacsvc_add) > 0: if len(hbacsvc_add) > 0:
commands.append([name, "hbacsvcgroup_add_member", commands.append([name, "hbacsvcgroup_add_member",
{ {
"hbacsvc": "hbacsvc": hbacsvc_add
[to_text(svc)
for svc in hbacsvc_add],
}]) }])
# Remove members # Remove members
if len(hbacsvc_del) > 0: if len(hbacsvc_del) > 0:
commands.append([name, commands.append([name,
"hbacsvcgroup_remove_member", "hbacsvcgroup_remove_member",
{ {
"hbacsvc": "hbacsvc": hbacsvc_del
[to_text(svc)
for svc in hbacsvc_del],
}]) }])
elif action == "member": elif action == "member":
if res_find is None: if res_find is None:
@@ -278,8 +258,7 @@ def main():
# Ensure members are present # Ensure members are present
commands.append([name, "hbacsvcgroup_add_member", commands.append([name, "hbacsvcgroup_add_member",
{ {
"hbacsvc": [to_text(svc) "hbacsvc": hbacsvc
for svc in hbacsvc],
}]) }])
elif state == "absent": elif state == "absent":
if action == "hbacsvcgroup": if action == "hbacsvcgroup":
@@ -294,8 +273,7 @@ def main():
# Ensure members are absent # Ensure members are absent
commands.append([name, "hbacsvcgroup_remove_member", commands.append([name, "hbacsvcgroup_remove_member",
{ {
"hbacsvc": [to_text(svc) "hbacsvc": hbacsvc
for svc in hbacsvc],
}]) }])
else: else:
ansible_module.fail_json(msg="Unkown state '%s'" % state) ansible_module.fail_json(msg="Unkown state '%s'" % state)
@@ -308,8 +286,7 @@ def main():
errors = [] errors = []
for name, command, args in commands: for name, command, args in commands:
try: try:
result = api_command(ansible_module, command, to_text(name), result = ansible_module.ipa_command(command, name, args)
args)
if "completed" in result: if "completed" in result:
if result["completed"] > 0: if result["completed"] > 0:
changed = True changed = True
@@ -332,12 +309,6 @@ def main():
if len(errors) > 0: if len(errors) > 0:
ansible_module.fail_json(msg=", ".join(errors)) ansible_module.fail_json(msg=", ".join(errors))
except Exception as e:
ansible_module.fail_json(msg=str(e))
finally:
temp_kdestroy(ccache_dir, ccache_name)
# Done # Done
ansible_module.exit_json(changed=changed, **exit_args) ansible_module.exit_json(changed=changed, **exit_args)

View File

@@ -31,13 +31,9 @@ DOCUMENTATION = """
module: ipahost module: ipahost
short description: Manage FreeIPA hosts short description: Manage FreeIPA hosts
description: Manage FreeIPA hosts description: Manage FreeIPA hosts
extends_documentation_fragment:
- ipamodule_base_docs
options: options:
ipaadmin_principal:
description: The admin principal
default: admin
ipaadmin_password:
description: The admin password
required: false
name: name:
description: The full qualified domain name. description: The full qualified domain name.
aliases: ["fqdn"] aliases: ["fqdn"]
@@ -380,7 +376,7 @@ EXAMPLES = """
# Ensure host is absent # Ensure host is absent
- ipahost: - ipahost:
ipaadmin_password: password1 ipaadmin_password: SomeADMINpassword
name: host01.example.com name: host01.example.com
state: absent state: absent
""" """
@@ -404,15 +400,10 @@ host:
returned: always returned: always
""" """
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.ansible_freeipa_module import \
from ansible.module_utils._text import to_text IPAAnsibleModule, compare_args_ipa, gen_add_del_lists, \
from ansible.module_utils.ansible_freeipa_module import temp_kinit, \ encode_certificate, is_ipv4_addr, is_ipv6_addr, ipalib_errors
temp_kdestroy, valid_creds, api_connect, api_command, compare_args_ipa, \
module_params_get, gen_add_del_lists, encode_certificate, api_get_realm, \
is_ipv4_addr, is_ipv6_addr, ipalib_errors
import six import six
if six.PY3: if six.PY3:
unicode = str unicode = str
@@ -423,7 +414,7 @@ def find_host(module, name):
} }
try: try:
_result = api_command(module, "host_show", to_text(name), _args) _result = module.ipa_command("host_show", name, _args)
except ipalib_errors.NotFound as e: except ipalib_errors.NotFound as e:
msg = str(e) msg = str(e)
if "host not found" in msg: if "host not found" in msg:
@@ -450,17 +441,16 @@ def find_dnsrecord(module, name):
_args = { _args = {
"all": True, "all": True,
"idnsname": to_text(host_name) "idnsname": host_name
} }
_result = api_command(module, "dnsrecord_show", to_text(domain_name), _result = module.ipa_command("dnsrecord_show", domain_name, _args)
_args)
return _result["result"] return _result["result"]
def show_host(module, name): def show_host(module, name):
_result = api_command(module, "host_show", to_text(name), {}) _result = module.ipa_command("host_show", name, {})
return _result["result"] return _result["result"]
@@ -663,12 +653,9 @@ def main():
# krbprincipalname # krbprincipalname
) )
ansible_module = AnsibleModule( ansible_module = IPAAnsibleModule(
argument_spec=dict( argument_spec=dict(
# general # general
ipaadmin_principal=dict(type="str", default="admin"),
ipaadmin_password=dict(type="str", no_log=True),
name=dict(type="list", aliases=["fqdn"], default=None, name=dict(type="list", aliases=["fqdn"], default=None,
required=False), required=False),
@@ -705,56 +692,52 @@ def main():
# Get parameters # Get parameters
# general # general
ipaadmin_principal = module_params_get(ansible_module, names = ansible_module.params_get("name")
"ipaadmin_principal") hosts = ansible_module.params_get("hosts")
ipaadmin_password = module_params_get(ansible_module,
"ipaadmin_password")
names = module_params_get(ansible_module, "name")
hosts = module_params_get(ansible_module, "hosts")
# present # present
description = module_params_get(ansible_module, "description") description = ansible_module.params_get("description")
locality = module_params_get(ansible_module, "locality") locality = ansible_module.params_get("locality")
location = module_params_get(ansible_module, "location") location = ansible_module.params_get("location")
platform = module_params_get(ansible_module, "platform") platform = ansible_module.params_get("platform")
os = module_params_get(ansible_module, "os") os = ansible_module.params_get("os")
password = module_params_get(ansible_module, "password") password = ansible_module.params_get("password")
random = module_params_get(ansible_module, "random") random = ansible_module.params_get("random")
certificate = module_params_get(ansible_module, "certificate") certificate = ansible_module.params_get("certificate")
managedby_host = module_params_get(ansible_module, "managedby_host") managedby_host = ansible_module.params_get("managedby_host")
principal = module_params_get(ansible_module, "principal") principal = ansible_module.params_get("principal")
allow_create_keytab_user = module_params_get( allow_create_keytab_user = ansible_module.params_get(
ansible_module, "allow_create_keytab_user") "allow_create_keytab_user")
allow_create_keytab_group = module_params_get( allow_create_keytab_group = ansible_module.params_get(
ansible_module, "allow_create_keytab_group") "allow_create_keytab_group")
allow_create_keytab_host = module_params_get( allow_create_keytab_host = ansible_module.params_get(
ansible_module, "allow_create_keytab_host") "allow_create_keytab_host")
allow_create_keytab_hostgroup = module_params_get( allow_create_keytab_hostgroup = ansible_module.params_get(
ansible_module, "allow_create_keytab_hostgroup") "allow_create_keytab_hostgroup")
allow_retrieve_keytab_user = module_params_get( allow_retrieve_keytab_user = ansible_module.params_get(
ansible_module, "allow_retrieve_keytab_user") "allow_retrieve_keytab_user")
allow_retrieve_keytab_group = module_params_get( allow_retrieve_keytab_group = ansible_module.params_get(
ansible_module, "allow_retrieve_keytab_group") "allow_retrieve_keytab_group")
allow_retrieve_keytab_host = module_params_get( allow_retrieve_keytab_host = ansible_module.params_get(
ansible_module, "allow_retrieve_keytab_host") "allow_retrieve_keytab_host")
allow_retrieve_keytab_hostgroup = module_params_get( allow_retrieve_keytab_hostgroup = ansible_module.params_get(
ansible_module, "allow_retrieve_keytab_hostgroup") "allow_retrieve_keytab_hostgroup")
mac_address = module_params_get(ansible_module, "mac_address") mac_address = ansible_module.params_get("mac_address")
sshpubkey = module_params_get(ansible_module, "sshpubkey") sshpubkey = ansible_module.params_get("sshpubkey")
userclass = module_params_get(ansible_module, "userclass") userclass = ansible_module.params_get("userclass")
auth_ind = module_params_get(ansible_module, "auth_ind") auth_ind = ansible_module.params_get("auth_ind")
requires_pre_auth = module_params_get(ansible_module, "requires_pre_auth") requires_pre_auth = ansible_module.params_get("requires_pre_auth")
ok_as_delegate = module_params_get(ansible_module, "ok_as_delegate") ok_as_delegate = ansible_module.params_get("ok_as_delegate")
ok_to_auth_as_delegate = module_params_get(ansible_module, ok_to_auth_as_delegate = ansible_module.params_get(
"ok_to_auth_as_delegate") "ok_to_auth_as_delegate")
force = module_params_get(ansible_module, "force") force = ansible_module.params_get("force")
reverse = module_params_get(ansible_module, "reverse") reverse = ansible_module.params_get("reverse")
ip_address = module_params_get(ansible_module, "ip_address") ip_address = ansible_module.params_get("ip_address")
update_dns = module_params_get(ansible_module, "update_dns") update_dns = ansible_module.params_get("update_dns")
update_password = module_params_get(ansible_module, "update_password") update_password = ansible_module.params_get("update_password")
# general # general
action = module_params_get(ansible_module, "action") action = ansible_module.params_get("action")
state = module_params_get(ansible_module, "state") state = ansible_module.params_get("state")
# Check parameters # Check parameters
@@ -786,17 +769,13 @@ def main():
changed = False changed = False
exit_args = {} exit_args = {}
ccache_dir = None
ccache_name = None # Connect to IPA API
try: with ansible_module.ipa_connect():
if not valid_creds(ansible_module, ipaadmin_principal):
ccache_dir, ccache_name = temp_kinit(ipaadmin_principal,
ipaadmin_password)
api_connect()
# Check version specific settings # Check version specific settings
server_realm = api_get_realm() server_realm = ansible_module.ipa_get_realm()
commands = [] commands = []
host_set = set() host_set = set()
@@ -973,7 +952,7 @@ def main():
# Principals are not returned as utf8 for IPA using # Principals are not returned as utf8 for IPA using
# python2 using host_show, therefore we need to # python2 using host_show, therefore we need to
# convert the principals that we should remove. # convert the principals that we should remove.
principal_del = [to_text(x) for x in principal_del] principal_del = [unicode(x) for x in principal_del]
(allow_create_keytab_user_add, (allow_create_keytab_user_add,
allow_create_keytab_user_del) = \ allow_create_keytab_user_del) = \
@@ -1373,8 +1352,7 @@ def main():
errors = [] errors = []
for name, command, args in commands: for name, command, args in commands:
try: try:
result = api_command(ansible_module, command, to_text(name), result = ansible_module.ipa_command(command, name, args)
args)
if "completed" in result: if "completed" in result:
if result["completed"] > 0: if result["completed"] > 0:
changed = True changed = True
@@ -1428,12 +1406,6 @@ def main():
if len(errors) > 0: if len(errors) > 0:
ansible_module.fail_json(msg=", ".join(errors)) ansible_module.fail_json(msg=", ".join(errors))
except Exception as e:
ansible_module.fail_json(msg=str(e))
finally:
temp_kdestroy(ccache_dir, ccache_name)
# Done # Done
ansible_module.exit_json(changed=changed, host=exit_args) ansible_module.exit_json(changed=changed, host=exit_args)

View File

@@ -32,13 +32,9 @@ DOCUMENTATION = """
module: ipahostgroup module: ipahostgroup
short description: Manage FreeIPA hostgroups short description: Manage FreeIPA hostgroups
description: Manage FreeIPA hostgroups description: Manage FreeIPA hostgroups
extends_documentation_fragment:
- ipamodule_base_docs
options: options:
ipaadmin_principal:
description: The admin principal
default: admin
ipaadmin_password:
description: The admin password
required: false
name: name:
description: The hostgroup name description: The hostgroup name
required: false required: false
@@ -138,11 +134,9 @@ EXAMPLES = """
RETURN = """ RETURN = """
""" """
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.ansible_freeipa_module import \
from ansible.module_utils.ansible_freeipa_module import temp_kinit, \ IPAAnsibleModule, compare_args_ipa, gen_add_del_lists, gen_add_list, \
temp_kdestroy, valid_creds, api_connect, api_command, compare_args_ipa, \ gen_intersection_list
module_params_get, gen_add_del_lists, api_check_command, api_check_param, \
gen_add_list, gen_intersection_list
def find_hostgroup(module, name): def find_hostgroup(module, name):
@@ -151,7 +145,7 @@ def find_hostgroup(module, name):
"cn": name, "cn": name,
} }
_result = api_command(module, "hostgroup_find", name, _args) _result = module.ipa_command("hostgroup_find", name, _args)
if len(_result["result"]) > 1: if len(_result["result"]) > 1:
module.fail_json( module.fail_json(
@@ -185,12 +179,9 @@ def gen_member_args(host, hostgroup):
def main(): def main():
ansible_module = AnsibleModule( ansible_module = IPAAnsibleModule(
argument_spec=dict( argument_spec=dict(
# general # general
ipaadmin_principal=dict(type="str", default="admin"),
ipaadmin_password=dict(type="str", required=False, no_log=True),
name=dict(type="list", aliases=["cn"], default=None, name=dict(type="list", aliases=["cn"], default=None,
required=True), required=True),
# present # present
@@ -217,25 +208,19 @@ def main():
# Get parameters # Get parameters
# general # general
ipaadmin_principal = module_params_get(ansible_module, names = ansible_module.params_get("name")
"ipaadmin_principal")
ipaadmin_password = module_params_get(ansible_module,
"ipaadmin_password")
names = module_params_get(ansible_module, "name")
# present # present
description = module_params_get(ansible_module, "description") description = ansible_module.params_get("description")
nomembers = module_params_get(ansible_module, "nomembers") nomembers = ansible_module.params_get("nomembers")
host = module_params_get(ansible_module, "host") host = ansible_module.params_get("host")
hostgroup = module_params_get(ansible_module, "hostgroup") hostgroup = ansible_module.params_get("hostgroup")
membermanager_user = module_params_get(ansible_module, membermanager_user = ansible_module.params_get("membermanager_user")
"membermanager_user") membermanager_group = ansible_module.params_get("membermanager_group")
membermanager_group = module_params_get(ansible_module, rename = ansible_module.params_get("rename")
"membermanager_group") action = ansible_module.params_get("action")
rename = module_params_get(ansible_module, "rename")
action = module_params_get(ansible_module, "action")
# state # state
state = module_params_get(ansible_module, "state") state = ansible_module.params_get("state")
# Check parameters # Check parameters
@@ -287,15 +272,11 @@ def main():
changed = False changed = False
exit_args = {} exit_args = {}
ccache_dir = None
ccache_name = None
try:
if not valid_creds(ansible_module, ipaadmin_principal):
ccache_dir, ccache_name = temp_kinit(ipaadmin_principal,
ipaadmin_password)
api_connect()
has_add_membermanager = api_check_command( # Connect to IPA API
with ansible_module.ipa_connect():
has_add_membermanager = ansible_module.ipa_command_exists(
"hostgroup_add_member_manager") "hostgroup_add_member_manager")
if ((membermanager_user is not None or if ((membermanager_user is not None or
membermanager_group is not None) and not has_add_membermanager): membermanager_group is not None) and not has_add_membermanager):
@@ -303,7 +284,8 @@ def main():
msg="Managing a membermanager user or group is not supported " msg="Managing a membermanager user or group is not supported "
"by your IPA version" "by your IPA version"
) )
has_mod_rename = api_check_param("hostgroup_mod", "rename") has_mod_rename = ansible_module.ipa_command_param_exists(
"hostgroup_mod", "rename")
if not has_mod_rename and rename is not None: if not has_mod_rename and rename is not None:
ansible_module.fail_json( ansible_module.fail_json(
msg="Renaming hostgroups is not supported by your IPA version") msg="Renaming hostgroups is not supported by your IPA version")
@@ -515,7 +497,7 @@ def main():
# Execute commands # Execute commands
for name, command, args in commands: for name, command, args in commands:
try: try:
result = api_command(ansible_module, command, name, args) result = ansible_module.ipa_command(command, name, args)
if "completed" in result: if "completed" in result:
if result["completed"] > 0: if result["completed"] > 0:
changed = True changed = True
@@ -537,12 +519,6 @@ def main():
if len(errors) > 0: if len(errors) > 0:
ansible_module.fail_json(msg=", ".join(errors)) ansible_module.fail_json(msg=", ".join(errors))
except Exception as e:
ansible_module.fail_json(msg=str(e))
finally:
temp_kdestroy(ccache_dir, ccache_name)
# Done # Done
ansible_module.exit_json(changed=changed, **exit_args) ansible_module.exit_json(changed=changed, **exit_args)

View File

@@ -66,21 +66,14 @@ RETURN = """
""" """
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.ansible_freeipa_module import \ from ansible.module_utils.ansible_freeipa_module import \
temp_kinit, temp_kdestroy, valid_creds, api_connect, api_command, \ IPAAnsibleModule, compare_args_ipa
compare_args_ipa, module_params_get, ipamodule_base_spec, \
get_ipamodule_base_vars
import six
if six.PY3:
unicode = str
def find_location(module, name): def find_location(module, name):
"""Find if a location with the given name already exist.""" """Find if a location with the given name already exist."""
try: try:
_result = api_command(module, "location_show", name, {"all": True}) _result = module.ipa_command("location_show", name, {"all": True})
except Exception: # pylint: disable=broad-except except Exception: # pylint: disable=broad-except
# An exception is raised if location name is not found. # An exception is raised if location name is not found.
return None return None
@@ -96,20 +89,16 @@ def gen_args(description):
def main(): def main():
# Arguments ansible_module = IPAAnsibleModule(
argument_spec = dict( argument_spec=dict(
name=dict(type="list", aliases=["idnsname"], name=dict(type="list", aliases=["idnsname"],
default=None, required=True), default=None, required=True),
# present # present
description=dict(required=False, type='str', default=None), description=dict(required=False, type='str', default=None),
# state # state
state=dict(type="str", default="present", state=dict(type="str", default="present",
choices=["present", "absent"]), choices=["present", "absent"]),
) ),
argument_spec.update(ipamodule_base_spec)
ansible_module = AnsibleModule(
argument_spec=argument_spec,
supports_check_mode=True, supports_check_mode=True,
) )
@@ -118,14 +107,13 @@ def main():
# Get parameters # Get parameters
# general # general
base_vars = get_ipamodule_base_vars(ansible_module) names = ansible_module.params_get("name")
names = module_params_get(ansible_module, "name")
# present # present
description = module_params_get(ansible_module, "description") description = ansible_module.params_get("description")
# state # state
state = module_params_get(ansible_module, "state") state = ansible_module.params_get("state")
# Check parameters # Check parameters
@@ -148,15 +136,9 @@ def main():
changed = False changed = False
exit_args = {} exit_args = {}
ccache_dir = None
ccache_name = None
try:
if not valid_creds(ansible_module, base_vars["ipaadmin_principal"]):
ccache_dir, ccache_name = temp_kinit(
base_vars["ipaadmin_principal"],
base_vars["ipaadmin_password"])
api_connect()
# Connect to IPA API
with ansible_module.ipa_connect():
commands = [] commands = []
for name in names: for name in names:
# Make sure location exists # Make sure location exists
@@ -194,8 +176,7 @@ def main():
for name, command, args in commands: for name, command, args in commands:
try: try:
result = api_command(ansible_module, command, name, result = ansible_module.ipa_command(command, name, args)
args)
if "completed" in result: if "completed" in result:
if result["completed"] > 0: if result["completed"] > 0:
changed = True changed = True
@@ -205,12 +186,6 @@ def main():
ansible_module.fail_json(msg="%s: %s: %s" % (command, name, ansible_module.fail_json(msg="%s: %s: %s" % (command, name,
str(e))) str(e)))
except Exception as e:
ansible_module.fail_json(msg=str(e))
finally:
temp_kdestroy(ccache_dir, ccache_name)
# Done # Done
ansible_module.exit_json(changed=changed, **exit_args) ansible_module.exit_json(changed=changed, **exit_args)

View File

@@ -31,13 +31,9 @@ DOCUMENTATION = """
module: ipapermission module: ipapermission
short description: Manage FreeIPA permission short description: Manage FreeIPA permission
description: Manage FreeIPA permission and permission members description: Manage FreeIPA permission and permission members
extends_documentation_fragment:
- ipamodule_base_docs
options: options:
ipaadmin_principal:
description: The admin principal.
default: admin
ipaadmin_password:
description: The admin password.
required: false
name: name:
description: The permission name string. description: The permission name string.
required: true required: true
@@ -133,20 +129,14 @@ RETURN = """
""" """
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.ansible_freeipa_module import \ from ansible.module_utils.ansible_freeipa_module import \
temp_kinit, temp_kdestroy, valid_creds, api_connect, api_command, \ IPAAnsibleModule, compare_args_ipa
compare_args_ipa, module_params_get, api_check_ipa_version
import six
if six.PY3:
unicode = str
def find_permission(module, name): def find_permission(module, name):
"""Find if a permission with the given name already exist.""" """Find if a permission with the given name already exist."""
try: try:
_result = api_command(module, "permission_show", name, {"all": True}) _result = module.ipa_command("permission_show", name, {"all": True})
except Exception: # pylint: disable=broad-except except Exception: # pylint: disable=broad-except
# An exception is raised if permission name is not found. # An exception is raised if permission name is not found.
return None return None
@@ -191,12 +181,9 @@ def gen_args(right, attrs, bindtype, subtree,
def main(): def main():
ansible_module = AnsibleModule( ansible_module = IPAAnsibleModule(
argument_spec=dict( argument_spec=dict(
# general # general
ipaadmin_principal=dict(type="str", default="admin"),
ipaadmin_password=dict(type="str", required=False, no_log=True),
name=dict(type="list", aliases=["cn"], name=dict(type="list", aliases=["cn"],
default=None, required=True), default=None, required=True),
# present # present
@@ -243,31 +230,27 @@ def main():
# Get parameters # Get parameters
# general # general
ipaadmin_principal = module_params_get(ansible_module, names = ansible_module.params_get("name")
"ipaadmin_principal")
ipaadmin_password = module_params_get(ansible_module, "ipaadmin_password")
names = module_params_get(ansible_module, "name")
# present # present
right = module_params_get(ansible_module, "right") right = ansible_module.params_get("right")
attrs = module_params_get(ansible_module, "attrs") attrs = ansible_module.params_get("attrs")
bindtype = module_params_get(ansible_module, "bindtype") bindtype = ansible_module.params_get("bindtype")
subtree = module_params_get(ansible_module, "subtree") subtree = ansible_module.params_get("subtree")
extra_target_filter = module_params_get(ansible_module, extra_target_filter = ansible_module.params_get("extra_target_filter")
"extra_target_filter") rawfilter = ansible_module.params_get("rawfilter")
rawfilter = module_params_get(ansible_module, "rawfilter") target = ansible_module.params_get("target")
target = module_params_get(ansible_module, "target") targetto = ansible_module.params_get("targetto")
targetto = module_params_get(ansible_module, "targetto") targetfrom = ansible_module.params_get("targetfrom")
targetfrom = module_params_get(ansible_module, "targetfrom") memberof = ansible_module.params_get("memberof")
memberof = module_params_get(ansible_module, "memberof") targetgroup = ansible_module.params_get("targetgroup")
targetgroup = module_params_get(ansible_module, "targetgroup") object_type = ansible_module.params_get("object_type")
object_type = module_params_get(ansible_module, "object_type") no_members = ansible_module.params_get("no_members")
no_members = module_params_get(ansible_module, "no_members") rename = ansible_module.params_get("rename")
rename = module_params_get(ansible_module, "rename") action = ansible_module.params_get("action")
action = module_params_get(ansible_module, "action")
# state # state
state = module_params_get(ansible_module, "state") state = ansible_module.params_get("state")
# Check parameters # Check parameters
@@ -311,7 +294,7 @@ def main():
msg="Argument '%s' can not be used with action " msg="Argument '%s' can not be used with action "
"'%s' and state '%s'" % (x, action, state)) "'%s' and state '%s'" % (x, action, state))
if bindtype == "self" and api_check_ipa_version("<", "4.8.7"): if bindtype == "self" and ansible_module.ipa_check_version("<", "4.8.7"):
ansible_module.fail_json( ansible_module.fail_json(
msg="Bindtype 'self' is not supported by your IPA version.") msg="Bindtype 'self' is not supported by your IPA version.")
@@ -324,13 +307,9 @@ def main():
changed = False changed = False
exit_args = {} exit_args = {}
ccache_dir = None
ccache_name = None # Connect to IPA API
try: with ansible_module.ipa_connect():
if not valid_creds(ansible_module, ipaadmin_principal):
ccache_dir, ccache_name = temp_kinit(ipaadmin_principal,
ipaadmin_password)
api_connect()
commands = [] commands = []
for name in names: for name in names:
@@ -454,8 +433,7 @@ def main():
for name, command, args in commands: for name, command, args in commands:
try: try:
result = api_command(ansible_module, command, name, result = ansible_module.ipa_command(command, name, args)
args)
if "completed" in result: if "completed" in result:
if result["completed"] > 0: if result["completed"] > 0:
changed = True changed = True
@@ -480,12 +458,6 @@ def main():
if len(errors) > 0: if len(errors) > 0:
ansible_module.fail_json(msg=", ".join(errors)) ansible_module.fail_json(msg=", ".join(errors))
except Exception as e:
ansible_module.fail_json(msg=str(e))
finally:
temp_kdestroy(ccache_dir, ccache_name)
# Done # Done
ansible_module.exit_json(changed=changed, **exit_args) ansible_module.exit_json(changed=changed, **exit_args)

View File

@@ -34,13 +34,9 @@ DOCUMENTATION = """
module: ipaprivilege module: ipaprivilege
short description: Manage FreeIPA privilege short description: Manage FreeIPA privilege
description: Manage FreeIPA privilege and privilege members description: Manage FreeIPA privilege and privilege members
extends_documentation_fragment:
- ipamodule_base_docs
options: options:
ipaadmin_principal:
description: The admin principal.
default: admin
ipaadmin_password:
description: The admin password.
required: false
name: name:
description: The list of privilege name strings. description: The list of privilege name strings.
required: true required: true
@@ -111,10 +107,8 @@ RETURN = """
""" """
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.ansible_freeipa_module import \ from ansible.module_utils.ansible_freeipa_module import \
temp_kinit, temp_kdestroy, valid_creds, api_connect, api_command, \ IPAAnsibleModule, compare_args_ipa, gen_add_del_lists
compare_args_ipa, module_params_get, gen_add_del_lists
import six import six
if six.PY3: if six.PY3:
@@ -124,7 +118,7 @@ if six.PY3:
def find_privilege(module, name): def find_privilege(module, name):
"""Find if a privilege with the given name already exist.""" """Find if a privilege with the given name already exist."""
try: try:
_result = api_command(module, "privilege_show", name, {"all": True}) _result = module.ipa_command("privilege_show", name, {"all": True})
except Exception: # pylint: disable=broad-except except Exception: # pylint: disable=broad-except
# An exception is raised if privilege name is not found. # An exception is raised if privilege name is not found.
return None return None
@@ -133,12 +127,9 @@ def find_privilege(module, name):
def main(): def main():
ansible_module = AnsibleModule( ansible_module = IPAAnsibleModule(
argument_spec=dict( argument_spec=dict(
# general # general
ipaadmin_principal=dict(type="str", default="admin"),
ipaadmin_password=dict(type="str", required=False, no_log=True),
name=dict(type="list", aliases=["cn"], name=dict(type="list", aliases=["cn"],
default=None, required=True), default=None, required=True),
# present # present
@@ -160,19 +151,16 @@ def main():
# Get parameters # Get parameters
# general # general
ipaadmin_principal = module_params_get(ansible_module, names = ansible_module.params_get("name")
"ipaadmin_principal")
ipaadmin_password = module_params_get(ansible_module, "ipaadmin_password")
names = module_params_get(ansible_module, "name")
# present # present
description = module_params_get(ansible_module, "description") description = ansible_module.params_get("description")
permission = module_params_get(ansible_module, "permission") permission = ansible_module.params_get("permission")
rename = module_params_get(ansible_module, "rename") rename = ansible_module.params_get("rename")
action = module_params_get(ansible_module, "action") action = ansible_module.params_get("action")
# state # state
state = module_params_get(ansible_module, "state") state = ansible_module.params_get("state")
# Check parameters # Check parameters
invalid = [] invalid = []
@@ -211,13 +199,9 @@ def main():
changed = False changed = False
exit_args = {} exit_args = {}
ccache_dir = None
ccache_name = None # Connect to IPA API
try: with ansible_module.ipa_connect():
if not valid_creds(ansible_module, ipaadmin_principal):
ccache_dir, ccache_name = temp_kinit(ipaadmin_principal,
ipaadmin_password)
api_connect()
commands = [] commands = []
for name in names: for name in names:
@@ -328,8 +312,7 @@ def main():
for name, command, args in commands: for name, command, args in commands:
try: try:
result = api_command(ansible_module, command, name, result = ansible_module.ipa_command(command, name, args)
args)
if "completed" in result: if "completed" in result:
if result["completed"] > 0: if result["completed"] > 0:
changed = True changed = True
@@ -354,12 +337,6 @@ def main():
if len(errors) > 0: if len(errors) > 0:
ansible_module.fail_json(msg=", ".join(errors)) ansible_module.fail_json(msg=", ".join(errors))
except Exception as e:
ansible_module.fail_json(msg=str(e))
finally:
temp_kdestroy(ccache_dir, ccache_name)
# Done # Done
ansible_module.exit_json(changed=changed, **exit_args) ansible_module.exit_json(changed=changed, **exit_args)

View File

@@ -111,19 +111,17 @@ EXAMPLES = """
RETURN = """ RETURN = """
""" """
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.ansible_freeipa_module import \
from ansible.module_utils._text import to_text IPAAnsibleModule, compare_args_ipa
from ansible.module_utils.ansible_freeipa_module import temp_kinit, \
temp_kdestroy, valid_creds, api_connect, api_command, compare_args_ipa
def find_pwpolicy(module, name): def find_pwpolicy(module, name):
_args = { _args = {
"all": True, "all": True,
"cn": to_text(name), "cn": name,
} }
_result = api_command(module, "pwpolicy_find", to_text(name), _args) _result = module.ipa_command("pwpolicy_find", name, _args)
if len(_result["result"]) > 1: if len(_result["result"]) > 1:
module.fail_json( module.fail_json(
@@ -160,12 +158,9 @@ def gen_args(maxlife, minlife, history, minclasses, minlength, priority,
def main(): def main():
ansible_module = AnsibleModule( ansible_module = IPAAnsibleModule(
argument_spec=dict( argument_spec=dict(
# general # general
ipaadmin_principal=dict(type="str", default="admin"),
ipaadmin_password=dict(type="str", required=False, no_log=True),
name=dict(type="list", aliases=["cn"], default=None, name=dict(type="list", aliases=["cn"], default=None,
required=False), required=False),
# present # present
@@ -198,28 +193,26 @@ def main():
# Get parameters # Get parameters
# general # general
ipaadmin_principal = ansible_module.params.get("ipaadmin_principal") names = ansible_module.params_get("name")
ipaadmin_password = ansible_module.params.get("ipaadmin_password")
names = ansible_module.params.get("name")
# present # present
maxlife = ansible_module.params.get("maxlife") maxlife = ansible_module.params_get("maxlife")
minlife = ansible_module.params.get("minlife") minlife = ansible_module.params_get("minlife")
history = ansible_module.params.get("history") history = ansible_module.params_get("history")
minclasses = ansible_module.params.get("minclasses") minclasses = ansible_module.params_get("minclasses")
minlength = ansible_module.params.get("minlength") minlength = ansible_module.params_get("minlength")
priority = ansible_module.params.get("priority") priority = ansible_module.params_get("priority")
maxfail = ansible_module.params.get("maxfail") maxfail = ansible_module.params_get("maxfail")
failinterval = ansible_module.params.get("failinterval") failinterval = ansible_module.params_get("failinterval")
lockouttime = ansible_module.params.get("lockouttime") lockouttime = ansible_module.params_get("lockouttime")
# state # state
state = ansible_module.params.get("state") state = ansible_module.params_get("state")
# Check parameters # Check parameters
if names is None: if names is None:
names = ["global_policy"] names = [u"global_policy"]
if state == "present": if state == "present":
if len(names) != 1: if len(names) != 1:
@@ -245,13 +238,8 @@ def main():
changed = False changed = False
exit_args = {} exit_args = {}
ccache_dir = None
ccache_name = None with ansible_module.ipa_connect():
try:
if not valid_creds(ansible_module, ipaadmin_principal):
ccache_dir, ccache_name = temp_kinit(ipaadmin_principal,
ipaadmin_password)
api_connect()
commands = [] commands = []
@@ -292,18 +280,12 @@ def main():
for name, command, args in commands: for name, command, args in commands:
try: try:
api_command(ansible_module, command, to_text(name), args) ansible_module.ipa_command(command, name, args)
changed = True changed = True
except Exception as e: except Exception as e:
ansible_module.fail_json(msg="%s: %s: %s" % (command, name, ansible_module.fail_json(msg="%s: %s: %s" % (command, name,
str(e))) str(e)))
except Exception as e:
ansible_module.fail_json(msg=str(e))
finally:
temp_kdestroy(ccache_dir, ccache_name)
# Done # Done
ansible_module.exit_json(changed=changed, **exit_args) ansible_module.exit_json(changed=changed, **exit_args)

View File

@@ -33,13 +33,9 @@ DOCUMENTATION = """
module: iparole module: iparole
short description: Manage FreeIPA role short description: Manage FreeIPA role
description: Manage FreeIPA role description: Manage FreeIPA role
extends_documentation_fragment:
- ipamodule_base_docs
options: options:
ipaadmin_principal:
description: The admin principal.
default: admin
ipaadmin_password:
description: The admin password.
required: false
role: role:
description: The list of role name strings. description: The list of role name strings.
required: true required: true
@@ -102,11 +98,9 @@ EXAMPLES = """
# pylint: disable=wrong-import-position # pylint: disable=wrong-import-position
# pylint: disable=import-error # pylint: disable=import-error
# pylint: disable=no-name-in-module # pylint: disable=no-name-in-module
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_text from ansible.module_utils._text import to_text
from ansible.module_utils.ansible_freeipa_module import \ from ansible.module_utils.ansible_freeipa_module import \
temp_kinit, temp_kdestroy, valid_creds, api_connect, api_command, \ IPAAnsibleModule, gen_add_del_lists, compare_args_ipa
gen_add_del_lists, compare_args_ipa, module_params_get, api_get_realm
import six import six
@@ -117,7 +111,7 @@ if six.PY3:
def find_role(module, name): def find_role(module, name):
"""Find if a role with the given name already exist.""" """Find if a role with the given name already exist."""
try: try:
_result = api_command(module, "role_show", name, {"all": True}) _result = module.ipa_command("role_show", name, {"all": True})
except Exception: # pylint: disable=broad-except except Exception: # pylint: disable=broad-except
# An exception is raised if role name is not found. # An exception is raised if role name is not found.
return None return None
@@ -134,7 +128,7 @@ def gen_args(module):
args = {} args = {}
for param, arg in arg_map.items(): for param, arg in arg_map.items():
value = module_params_get(module, param) value = module.params_get(param)
if value is not None: if value is not None:
args[arg] = value args[arg] = value
@@ -143,8 +137,8 @@ def gen_args(module):
def check_parameters(module): def check_parameters(module):
"""Check if parameters passed for module processing are valid.""" """Check if parameters passed for module processing are valid."""
action = module_params_get(module, "action") action = module.params_get("action")
state = module_params_get(module, "state") state = module.params_get("state")
invalid = [] invalid = []
@@ -158,30 +152,15 @@ def check_parameters(module):
invalid.extend(['privilege']) invalid.extend(['privilege'])
for arg in invalid: for arg in invalid:
if module_params_get(module, arg) is not None: if module.params_get(arg) is not None:
module.fail_json( module.fail_json(
msg="Argument '%s' can not be used with action '%s'" % msg="Argument '%s' can not be used with action '%s'" %
(arg, state)) (arg, state))
def verify_credentials(module):
"""Ensure there are valid Kerberos credentials."""
ccache_dir = None
ccache_name = None
ipaadmin_principal = module_params_get(module, "ipaadmin_principal")
ipaadmin_password = module_params_get(module, "ipaadmin_password")
if not valid_creds(module, ipaadmin_principal):
ccache_dir, ccache_name = temp_kinit(ipaadmin_principal,
ipaadmin_password)
return (ccache_dir, ccache_name)
def member_intersect(module, attr, memberof, res_find): def member_intersect(module, attr, memberof, res_find):
"""Filter member arguments from role found by intersection.""" """Filter member arguments from role found by intersection."""
params = module_params_get(module, attr) params = module.params_get(attr)
if not res_find: if not res_find:
return params return params
filtered = [] filtered = []
@@ -193,7 +172,7 @@ def member_intersect(module, attr, memberof, res_find):
def member_difference(module, attr, memberof, res_find): def member_difference(module, attr, memberof, res_find):
"""Filter member arguments from role found by difference.""" """Filter member arguments from role found by difference."""
params = module_params_get(module, attr) params = module.params_get(attr)
if not res_find: if not res_find:
return params return params
filtered = [] filtered = []
@@ -248,7 +227,7 @@ def filter_service(module, res_find, predicate):
modified service to be compared to. modified service to be compared to.
""" """
_services = [] _services = []
service = module_params_get(module, 'service') service = module.params_get('service')
if service: if service:
existing = [to_text(x) for x in res_find.get('member_service', [])] existing = [to_text(x) for x in res_find.get('member_service', [])]
for svc in service: for svc in service:
@@ -262,7 +241,7 @@ def ensure_role_with_members_is_present(module, name, res_find, action):
"""Define commands to ensure member are present for action `role`.""" """Define commands to ensure member are present for action `role`."""
commands = [] commands = []
privilege_add, privilege_del = gen_add_del_lists( privilege_add, privilege_del = gen_add_del_lists(
module_params_get(module, "privilege"), module.params_get("privilege"),
res_find.get('memberof_privilege', [])) res_find.get('memberof_privilege', []))
if privilege_add: if privilege_add:
@@ -277,7 +256,7 @@ def ensure_role_with_members_is_present(module, name, res_find, action):
for key in ["user", "group", "host", "hostgroup"]: for key in ["user", "group", "host", "hostgroup"]:
add_list, del_list = gen_add_del_lists( add_list, del_list = gen_add_del_lists(
module_params_get(module, key), module.params_get(key),
res_find.get('member_%s' % key, []) res_find.get('member_%s' % key, [])
) )
if add_list: if add_list:
@@ -286,8 +265,10 @@ def ensure_role_with_members_is_present(module, name, res_find, action):
del_members[key] = [to_text(item) for item in del_list] del_members[key] = [to_text(item) for item in del_list]
service = [ service = [
to_text(svc) if '@' in svc else ('%s@%s' % (svc, api_get_realm())) to_text(svc)
for svc in (module_params_get(module, 'service') or []) if '@' in svc
else ('%s@%s' % (svc, module.ipa_get_realm()))
for svc in (module.params_get('service') or [])
] ]
existing = [str(svc) for svc in res_find.get('member_service', [])] existing = [str(svc) for svc in res_find.get('member_service', [])]
add_list, del_list = gen_add_del_lists(service, existing) add_list, del_list = gen_add_del_lists(service, existing)
@@ -364,7 +345,7 @@ def process_commands(module, commands):
for name, command, args in commands: for name, command, args in commands:
try: try:
result = api_command(module, command, name, args) result = module.ipa_command(command, name, args)
if "completed" in result: if "completed" in result:
if result["completed"] > 0: if result["completed"] > 0:
changed = True changed = True
@@ -386,7 +367,7 @@ def role_commands_for_name(module, state, action, name):
"""Define commands for the Role module.""" """Define commands for the Role module."""
commands = [] commands = []
rename = module_params_get(module, "rename") rename = module.params_get("rename")
res_find = find_role(module, name) res_find = find_role(module, name)
@@ -421,12 +402,9 @@ def role_commands_for_name(module, state, action, name):
def create_module(): def create_module():
"""Create module description.""" """Create module description."""
ansible_module = AnsibleModule( ansible_module = IPAAnsibleModule(
argument_spec=dict( argument_spec=dict(
# generalgroups # generalgroups
ipaadmin_principal=dict(type="str", default="admin"),
ipaadmin_password=dict(type="str", required=False, no_log=True),
name=dict(type="list", aliases=["cn"], default=None, name=dict(type="list", aliases=["cn"], default=None,
required=True), required=True),
# present # present
@@ -463,15 +441,13 @@ def main():
check_parameters(ansible_module) check_parameters(ansible_module)
# Init # Init
ccache_dir = None
ccache_name = None
try:
ccache_dir, ccache_name = verify_credentials(ansible_module)
api_connect()
state = module_params_get(ansible_module, "state") # Connect to IPA API
action = module_params_get(ansible_module, "action") with ansible_module.ipa_connect():
names = module_params_get(ansible_module, "name")
state = ansible_module.params_get("state")
action = ansible_module.params_get("action")
names = ansible_module.params_get("name")
commands = [] commands = []
for name in names: for name in names:
@@ -480,12 +456,6 @@ def main():
changed, exit_args = process_commands(ansible_module, commands) changed, exit_args = process_commands(ansible_module, commands)
except Exception as exception: # pylint: disable=broad-except
ansible_module.fail_json(msg=str(exception))
finally:
temp_kdestroy(ccache_dir, ccache_name)
# Done # Done
ansible_module.exit_json(changed=changed, **exit_args) ansible_module.exit_json(changed=changed, **exit_args)

View File

@@ -31,13 +31,9 @@ DOCUMENTATION = """
module: ipaselfservice module: ipaselfservice
short description: Manage FreeIPA selfservices short description: Manage FreeIPA selfservices
description: Manage FreeIPA selfservices and selfservice attributes description: Manage FreeIPA selfservices and selfservice attributes
extends_documentation_fragment:
- ipamodule_base_docs
options: options:
ipaadmin_principal:
description: The admin principal.
default: admin
ipaadmin_password:
description: The admin password.
required: false
name: name:
description: The list of selfservice name strings. description: The list of selfservice name strings.
required: true required: true
@@ -103,21 +99,14 @@ RETURN = """
""" """
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.ansible_freeipa_module import \ from ansible.module_utils.ansible_freeipa_module import \
temp_kinit, temp_kdestroy, valid_creds, api_connect, api_command, \ IPAAnsibleModule, compare_args_ipa
compare_args_ipa, module_params_get
import six
if six.PY3:
unicode = str
def find_selfservice(module, name): def find_selfservice(module, name):
"""Find if a selfservice with the given name already exist.""" """Find if a selfservice with the given name already exist."""
try: try:
_result = api_command(module, "selfservice_show", name, {"all": True}) _result = module.ipa_command("selfservice_show", name, {"all": True})
except Exception: # pylint: disable=broad-except except Exception: # pylint: disable=broad-except
# An exception is raised if selfservice name is not found. # An exception is raised if selfservice name is not found.
return None return None
@@ -135,12 +124,9 @@ def gen_args(permission, attribute):
def main(): def main():
ansible_module = AnsibleModule( ansible_module = IPAAnsibleModule(
argument_spec=dict( argument_spec=dict(
# general # general
ipaadmin_principal=dict(type="str", default="admin"),
ipaadmin_password=dict(type="str", required=False, no_log=True),
name=dict(type="list", aliases=["aciname"], default=None, name=dict(type="list", aliases=["aciname"], default=None,
required=True), required=True),
# present # present
@@ -162,17 +148,14 @@ def main():
# Get parameters # Get parameters
# general # general
ipaadmin_principal = module_params_get(ansible_module, names = ansible_module.params_get("name")
"ipaadmin_principal")
ipaadmin_password = module_params_get(ansible_module, "ipaadmin_password")
names = module_params_get(ansible_module, "name")
# present # present
permission = module_params_get(ansible_module, "permission") permission = ansible_module.params_get("permission")
attribute = module_params_get(ansible_module, "attribute") attribute = ansible_module.params_get("attribute")
action = module_params_get(ansible_module, "action") action = ansible_module.params_get("action")
# state # state
state = module_params_get(ansible_module, "state") state = ansible_module.params_get("state")
# Check parameters # Check parameters
@@ -219,13 +202,9 @@ def main():
changed = False changed = False
exit_args = {} exit_args = {}
ccache_dir = None
ccache_name = None # Connect to IPA API
try: with ansible_module.ipa_connect():
if not valid_creds(ansible_module, ipaadmin_principal):
ccache_dir, ccache_name = temp_kinit(ipaadmin_principal,
ipaadmin_password)
api_connect()
commands = [] commands = []
for name in names: for name in names:
@@ -301,8 +280,7 @@ def main():
for name, command, args in commands: for name, command, args in commands:
try: try:
result = api_command(ansible_module, command, name, result = ansible_module.ipa_command(command, name, args)
args)
if "completed" in result: if "completed" in result:
if result["completed"] > 0: if result["completed"] > 0:
changed = True changed = True
@@ -312,12 +290,6 @@ def main():
ansible_module.fail_json(msg="%s: %s: %s" % (command, name, ansible_module.fail_json(msg="%s: %s: %s" % (command, name,
str(e))) str(e)))
except Exception as e:
ansible_module.fail_json(msg=str(e))
finally:
temp_kdestroy(ccache_dir, ccache_name)
# Done # Done
ansible_module.exit_json(changed=changed, **exit_args) ansible_module.exit_json(changed=changed, **exit_args)

View File

@@ -31,13 +31,9 @@ DOCUMENTATION = """
module: ipaserver module: ipaserver
short description: Manage FreeIPA server short description: Manage FreeIPA server
description: Manage FreeIPA server description: Manage FreeIPA server
extends_documentation_fragment:
- ipamodule_base_docs
options: options:
ipaadmin_principal:
description: The admin principal.
default: admin
ipaadmin_password:
description: The admin password.
required: false
name: name:
description: The list of server name strings. description: The list of server name strings.
required: true required: true
@@ -184,20 +180,14 @@ RETURN = """
""" """
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.ansible_freeipa_module import \ from ansible.module_utils.ansible_freeipa_module import \
temp_kinit, temp_kdestroy, valid_creds, api_connect, api_command, \ IPAAnsibleModule, compare_args_ipa, DNSName
api_command_no_name, compare_args_ipa, module_params_get, DNSName
import six
if six.PY3:
unicode = str
def find_server(module, name): def find_server(module, name):
"""Find if a server with the given name already exist.""" """Find if a server with the given name already exist."""
try: try:
_result = api_command(module, "server_show", name, {"all": True}) _result = module.ipa_command("server_show", name, {"all": True})
except Exception: # pylint: disable=broad-except except Exception: # pylint: disable=broad-except
# An exception is raised if server name is not found. # An exception is raised if server name is not found.
return None return None
@@ -208,12 +198,12 @@ def find_server(module, name):
def server_role_status(module, name): def server_role_status(module, name):
"""Get server role of a hidden server with the given name.""" """Get server role of a hidden server with the given name."""
try: try:
_result = api_command_no_name(module, "server_role_find", _result = module.ipa_command_no_name("server_role_find",
{"server_server": name, {"server_server": name,
"role_servrole": 'IPA master', "role_servrole": 'IPA master',
"include_master": True, "include_master": True,
"raw": True, "raw": True,
"all": True}) "all": True})
except Exception: # pylint: disable=broad-except except Exception: # pylint: disable=broad-except
# An exception is raised if server name is not found. # An exception is raised if server name is not found.
return None return None
@@ -246,12 +236,9 @@ def gen_args(location, service_weight, no_members, delete_continue,
def main(): def main():
ansible_module = AnsibleModule( ansible_module = IPAAnsibleModule(
argument_spec=dict( argument_spec=dict(
# general # general
ipaadmin_principal=dict(type="str", default="admin"),
ipaadmin_password=dict(type="str", required=False, no_log=True),
name=dict(type="list", aliases=["cn"], name=dict(type="list", aliases=["cn"],
default=None, required=True), default=None, required=True),
# present # present
@@ -282,14 +269,11 @@ def main():
# Get parameters # Get parameters
# general # general
ipaadmin_principal = module_params_get(ansible_module, names = ansible_module.params_get("name")
"ipaadmin_principal")
ipaadmin_password = module_params_get(ansible_module, "ipaadmin_password")
names = module_params_get(ansible_module, "name")
# present # present
location = module_params_get(ansible_module, "location") location = ansible_module.params_get("location")
service_weight = module_params_get(ansible_module, "service_weight") service_weight = ansible_module.params_get("service_weight")
# Service weight smaller than 0 leads to resetting service weight # Service weight smaller than 0 leads to resetting service weight
if service_weight is not None and \ if service_weight is not None and \
(service_weight < -1 or service_weight > 65535): (service_weight < -1 or service_weight > 65535):
@@ -298,19 +282,18 @@ def main():
service_weight) service_weight)
if service_weight == -1: if service_weight == -1:
service_weight = "" service_weight = ""
hidden = module_params_get(ansible_module, "hidden") hidden = ansible_module.params_get("hidden")
no_members = module_params_get(ansible_module, "no_members") no_members = ansible_module.params_get("no_members")
# absent # absent
delete_continue = module_params_get(ansible_module, "delete_continue") delete_continue = ansible_module.params_get("delete_continue")
ignore_topology_disconnect = module_params_get( ignore_topology_disconnect = ansible_module.params_get(
ansible_module, "ignore_topology_disconnect") "ignore_topology_disconnect")
ignore_last_of_role = module_params_get(ansible_module, ignore_last_of_role = ansible_module.params_get("ignore_last_of_role")
"ignore_last_of_role") force = ansible_module.params_get("force")
force = module_params_get(ansible_module, "force")
# state # state
state = module_params_get(ansible_module, "state") state = ansible_module.params_get("state")
# Check parameters # Check parameters
@@ -338,13 +321,9 @@ def main():
changed = False changed = False
exit_args = {} exit_args = {}
ccache_dir = None
ccache_name = None # Connect to IPA API
try: with ansible_module.ipa_connect():
if not valid_creds(ansible_module, ipaadmin_principal):
ccache_dir, ccache_name = temp_kinit(ipaadmin_principal,
ipaadmin_password)
api_connect()
commands = [] commands = []
for name in names: for name in names:
@@ -414,8 +393,7 @@ def main():
for name, command, args in commands: for name, command, args in commands:
try: try:
result = api_command(ansible_module, command, name, result = ansible_module.ipa_command(command, name, args)
args)
if "completed" in result: if "completed" in result:
if result["completed"] > 0: if result["completed"] > 0:
changed = True changed = True
@@ -425,12 +403,6 @@ def main():
ansible_module.fail_json(msg="%s: %s: %s" % (command, name, ansible_module.fail_json(msg="%s: %s: %s" % (command, name,
str(e))) str(e)))
except Exception as e:
ansible_module.fail_json(msg=str(e))
finally:
temp_kdestroy(ccache_dir, ccache_name)
# Done # Done
ansible_module.exit_json(changed=changed, **exit_args) ansible_module.exit_json(changed=changed, **exit_args)

View File

@@ -32,13 +32,9 @@ DOCUMENTATION = """
module: ipaservice module: ipaservice
short description: Manage FreeIPA service short description: Manage FreeIPA service
description: Manage FreeIPA service description: Manage FreeIPA service
extends_documentation_fragment:
- ipamodule_base_docs
options: options:
ipaadmin_principal:
description: The admin principal
default: admin
ipaadmin_password:
description: The admin password
required: false
name: name:
description: The service to manage description: The service to manage
required: true required: true
@@ -226,11 +222,9 @@ EXAMPLES = """
RETURN = """ RETURN = """
""" """
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.ansible_freeipa_module import \
from ansible.module_utils.ansible_freeipa_module import temp_kinit, \ IPAAnsibleModule, compare_args_ipa, encode_certificate, \
temp_kdestroy, valid_creds, api_connect, api_command, compare_args_ipa, \ gen_add_del_lists, ipalib_errors
encode_certificate, gen_add_del_lists, module_params_get, to_text, \
api_check_param, ipalib_errors
def find_service(module, name): def find_service(module, name):
@@ -239,7 +233,7 @@ def find_service(module, name):
} }
try: try:
_result = api_command(module, "service_show", to_text(name), _args) _result = module.ipa_command("service_show", name, _args)
except ipalib_errors.NotFound: except ipalib_errors.NotFound:
return None return None
@@ -349,12 +343,9 @@ def check_parameters(module, state, action, names, parameters):
def init_ansible_module(): def init_ansible_module():
ansible_module = AnsibleModule( ansible_module = IPAAnsibleModule(
argument_spec=dict( argument_spec=dict(
# general # general
ipaadmin_principal=dict(type="str", default="admin"),
ipaadmin_password=dict(type="str", required=False, no_log=True),
name=dict(type="list", aliases=["service"], default=None, name=dict(type="list", aliases=["service"], default=None,
required=True), required=True),
# service attributesstr # service attributesstr
@@ -424,51 +415,48 @@ def main():
# Get parameters # Get parameters
# general # general
ipaadmin_principal = module_params_get(ansible_module, names = ansible_module.params_get("name")
"ipaadmin_principal")
ipaadmin_password = module_params_get(ansible_module, "ipaadmin_password")
names = module_params_get(ansible_module, "name")
# service attributes # service attributes
principal = module_params_get(ansible_module, "principal") principal = ansible_module.params_get("principal")
certificate = module_params_get(ansible_module, "certificate") certificate = ansible_module.params_get("certificate")
pac_type = module_params_get(ansible_module, "pac_type") pac_type = ansible_module.params_get("pac_type")
auth_ind = module_params_get(ansible_module, "auth_ind") auth_ind = ansible_module.params_get("auth_ind")
skip_host_check = module_params_get(ansible_module, "skip_host_check") skip_host_check = ansible_module.params_get("skip_host_check")
force = module_params_get(ansible_module, "force") force = ansible_module.params_get("force")
requires_pre_auth = module_params_get(ansible_module, "requires_pre_auth") requires_pre_auth = ansible_module.params_get("requires_pre_auth")
ok_as_delegate = module_params_get(ansible_module, "ok_as_delegate") ok_as_delegate = ansible_module.params_get("ok_as_delegate")
ok_to_auth_as_delegate = module_params_get(ansible_module, ok_to_auth_as_delegate = ansible_module.params_get(
"ok_to_auth_as_delegate") "ok_to_auth_as_delegate")
smb = module_params_get(ansible_module, "smb") smb = ansible_module.params_get("smb")
netbiosname = module_params_get(ansible_module, "netbiosname") netbiosname = ansible_module.params_get("netbiosname")
host = module_params_get(ansible_module, "host") host = ansible_module.params_get("host")
allow_create_keytab_user = module_params_get( allow_create_keytab_user = ansible_module.params_get(
ansible_module, "allow_create_keytab_user") "allow_create_keytab_user")
allow_create_keytab_group = module_params_get( allow_create_keytab_group = ansible_module.params_get(
ansible_module, "allow_create_keytab_group") "allow_create_keytab_group")
allow_create_keytab_host = module_params_get( allow_create_keytab_host = ansible_module.params_get(
ansible_module, "allow_create_keytab_host") "allow_create_keytab_host")
allow_create_keytab_hostgroup = module_params_get( allow_create_keytab_hostgroup = ansible_module.params_get(
ansible_module, "allow_create_keytab_hostgroup") "allow_create_keytab_hostgroup")
allow_retrieve_keytab_user = module_params_get( allow_retrieve_keytab_user = ansible_module.params_get(
ansible_module, "allow_retrieve_keytab_user") "allow_retrieve_keytab_user")
allow_retrieve_keytab_group = module_params_get( allow_retrieve_keytab_group = ansible_module.params_get(
ansible_module, "allow_retrieve_keytab_group") "allow_retrieve_keytab_group")
allow_retrieve_keytab_host = module_params_get( allow_retrieve_keytab_host = ansible_module.params_get(
ansible_module, "allow_retrieve_keytab_host") "allow_retrieve_keytab_host")
allow_retrieve_keytab_hostgroup = module_params_get( allow_retrieve_keytab_hostgroup = ansible_module.params_get(
ansible_module, "allow_retrieve_keytab_hostgroup") "allow_retrieve_keytab_hostgroup")
delete_continue = module_params_get(ansible_module, "delete_continue") delete_continue = ansible_module.params_get("delete_continue")
# action # action
action = module_params_get(ansible_module, "action") action = ansible_module.params_get("action")
# state # state
state = module_params_get(ansible_module, "state") state = ansible_module.params_get("state")
# check parameters # check parameters
check_parameters(ansible_module, state, action, names, vars()) check_parameters(ansible_module, state, action, names, vars())
@@ -477,15 +465,11 @@ def main():
changed = False changed = False
exit_args = {} exit_args = {}
ccache_dir = None
ccache_name = None
try:
if not valid_creds(ansible_module, ipaadmin_principal):
ccache_dir, ccache_name = temp_kinit(ipaadmin_principal,
ipaadmin_password)
api_connect()
has_skip_host_check = api_check_param( # Connect to IPA API
with ansible_module.ipa_connect():
has_skip_host_check = ansible_module.ipa_command_param_exists(
"service_add", "skip_host_check") "service_add", "skip_host_check")
if skip_host_check and not has_skip_host_check: if skip_host_check and not has_skip_host_check:
ansible_module.fail_json( ansible_module.fail_json(
@@ -850,7 +834,7 @@ def main():
errors = [] errors = []
for name, command, args in commands: for name, command, args in commands:
try: try:
result = api_command(ansible_module, command, name, args) result = ansible_module.ipa_command(command, name, args)
if "completed" in result: if "completed" in result:
if result["completed"] > 0: if result["completed"] > 0:
@@ -876,12 +860,6 @@ def main():
if len(errors) > 0: if len(errors) > 0:
ansible_module.fail_json(msg=", ".join(errors)) ansible_module.fail_json(msg=", ".join(errors))
except Exception as ex:
ansible_module.fail_json(msg=str(ex))
finally:
temp_kdestroy(ccache_dir, ccache_name)
# Done # Done
ansible_module.exit_json(changed=changed, **exit_args) ansible_module.exit_json(changed=changed, **exit_args)

View File

@@ -32,13 +32,9 @@ DOCUMENTATION = """
module: ipasudocmd module: ipasudocmd
short description: Manage FreeIPA sudo command short description: Manage FreeIPA sudo command
description: Manage FreeIPA sudo command description: Manage FreeIPA sudo command
extends_documentation_fragment:
- ipamodule_base_docs
options: options:
ipaadmin_principal:
description: The admin principal
default: admin
ipaadmin_password:
description: The admin password
required: false
name: name:
description: The sudo command description: The sudo command
required: true required: true
@@ -71,19 +67,17 @@ EXAMPLES = """
RETURN = """ RETURN = """
""" """
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.ansible_freeipa_module import \
from ansible.module_utils._text import to_text IPAAnsibleModule, compare_args_ipa
from ansible.module_utils.ansible_freeipa_module import temp_kinit, \
temp_kdestroy, valid_creds, api_connect, api_command, compare_args_ipa
def find_sudocmd(module, name): def find_sudocmd(module, name):
_args = { _args = {
"all": True, "all": True,
"sudocmd": to_text(name), "sudocmd": name,
} }
_result = api_command(module, "sudocmd_find", to_text(name), _args) _result = module.ipa_command("sudocmd_find", name, _args)
if len(_result["result"]) > 1: if len(_result["result"]) > 1:
module.fail_json( module.fail_json(
@@ -97,18 +91,15 @@ def find_sudocmd(module, name):
def gen_args(description): def gen_args(description):
_args = {} _args = {}
if description is not None: if description is not None:
_args["description"] = to_text(description) _args["description"] = description
return _args return _args
def main(): def main():
ansible_module = AnsibleModule( ansible_module = IPAAnsibleModule(
argument_spec=dict( argument_spec=dict(
# general # general
ipaadmin_principal=dict(type="str", default="admin"),
ipaadmin_password=dict(type="str", required=False, no_log=True),
name=dict(type="list", aliases=["sudocmd"], default=None, name=dict(type="list", aliases=["sudocmd"], default=None,
required=True), required=True),
# present # present
@@ -125,14 +116,12 @@ def main():
# Get parameters # Get parameters
# general # general
ipaadmin_principal = ansible_module.params.get("ipaadmin_principal") names = ansible_module.params_get("name")
ipaadmin_password = ansible_module.params.get("ipaadmin_password")
names = ansible_module.params.get("name")
# present # present
description = ansible_module.params.get("description") description = ansible_module.params_get("description")
# state # state
state = ansible_module.params.get("state") state = ansible_module.params_get("state")
# Check parameters # Check parameters
if state == "absent": if state == "absent":
@@ -147,13 +136,9 @@ def main():
changed = False changed = False
exit_args = {} exit_args = {}
ccache_dir = None
ccache_name = None # Connect to IPA API
try: with ansible_module.ipa_connect():
if not valid_creds(ansible_module, ipaadmin_principal):
ccache_dir, ccache_name = temp_kinit(ipaadmin_principal,
ipaadmin_password)
api_connect()
commands = [] commands = []
@@ -189,8 +174,7 @@ def main():
# Execute commands # Execute commands
for name, command, args in commands: for name, command, args in commands:
try: try:
result = api_command(ansible_module, command, to_text(name), result = ansible_module.ipa_command(command, name, args)
args)
# Check if any changes were made by any command # Check if any changes were made by any command
if command == 'sudocmd_del': if command == 'sudocmd_del':
changed |= "Deleted" in result['summary'] changed |= "Deleted" in result['summary']
@@ -200,12 +184,6 @@ def main():
ansible_module.fail_json(msg="%s: %s: %s" % (command, name, ansible_module.fail_json(msg="%s: %s: %s" % (command, name,
str(e))) str(e)))
except Exception as e:
ansible_module.fail_json(msg=str(e))
finally:
temp_kdestroy(ccache_dir, ccache_name)
# Done # Done
ansible_module.exit_json(changed=changed, **exit_args) ansible_module.exit_json(changed=changed, **exit_args)

View File

@@ -32,13 +32,9 @@ DOCUMENTATION = """
module: ipasudocmdgroup module: ipasudocmdgroup
short description: Manage FreeIPA sudocmd groups short description: Manage FreeIPA sudocmd groups
description: Manage FreeIPA sudocmd groups description: Manage FreeIPA sudocmd groups
extends_documentation_fragment:
- ipamodule_base_docs
options: options:
ipaadmin_principal:
description: The admin principal
default: admin
ipaadmin_password:
description: The admin password
required: false
name: name:
description: The sudocmodgroup name description: The sudocmodgroup name
required: false required: false
@@ -103,18 +99,15 @@ EXAMPLES = """
RETURN = """ RETURN = """
""" """
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.ansible_freeipa_module import \
from ansible.module_utils._text import to_text IPAAnsibleModule, compare_args_ipa, gen_add_del_lists, ipalib_errors
from ansible.module_utils.ansible_freeipa_module import temp_kinit, \
temp_kdestroy, valid_creds, api_connect, api_command, compare_args_ipa, \
gen_add_del_lists, ipalib_errors
def find_sudocmdgroup(module, name): def find_sudocmdgroup(module, name):
args = {"all": True} args = {"all": True}
try: try:
_result = api_command(module, "sudocmdgroup_show", to_text(name), args) _result = module.ipa_command("sudocmdgroup_show", name, args)
except ipalib_errors.NotFound: except ipalib_errors.NotFound:
return None return None
else: else:
@@ -124,7 +117,7 @@ def find_sudocmdgroup(module, name):
def gen_args(description, nomembers): def gen_args(description, nomembers):
_args = {} _args = {}
if description is not None: if description is not None:
_args["description"] = to_text(description) _args["description"] = description
if nomembers is not None: if nomembers is not None:
_args["nomembers"] = nomembers _args["nomembers"] = nomembers
@@ -140,12 +133,9 @@ def gen_member_args(sudocmd):
def main(): def main():
ansible_module = AnsibleModule( ansible_module = IPAAnsibleModule(
argument_spec=dict( argument_spec=dict(
# general # general
ipaadmin_principal=dict(type="str", default="admin"),
ipaadmin_password=dict(type="str", required=False, no_log=True),
name=dict(type="list", aliases=["cn"], default=None, name=dict(type="list", aliases=["cn"], default=None,
required=True), required=True),
# present # present
@@ -166,17 +156,15 @@ def main():
# Get parameters # Get parameters
# general # general
ipaadmin_principal = ansible_module.params.get("ipaadmin_principal") names = ansible_module.params_get("name")
ipaadmin_password = ansible_module.params.get("ipaadmin_password")
names = ansible_module.params.get("name")
# present # present
description = ansible_module.params.get("description") description = ansible_module.params_get("description")
nomembers = ansible_module.params.get("nomembers") nomembers = ansible_module.params_get("nomembers")
sudocmd = ansible_module.params.get("sudocmd") sudocmd = ansible_module.params_get("sudocmd")
action = ansible_module.params.get("action") action = ansible_module.params_get("action")
# state # state
state = ansible_module.params.get("state") state = ansible_module.params_get("state")
# Check parameters # Check parameters
@@ -209,13 +197,9 @@ def main():
changed = False changed = False
exit_args = {} exit_args = {}
ccache_dir = None
ccache_name = None # Connect to IPA API
try: with ansible_module.ipa_connect():
if not valid_creds(ansible_module, ipaadmin_principal):
ccache_dir, ccache_name = temp_kinit(ipaadmin_principal,
ipaadmin_password)
api_connect()
commands = [] commands = []
@@ -255,9 +239,7 @@ def main():
if len(sudocmd_add) > 0: if len(sudocmd_add) > 0:
commands.append([name, "sudocmdgroup_add_member", commands.append([name, "sudocmdgroup_add_member",
{ {
"sudocmd": [to_text(c) "sudocmd": sudocmd_add
for c in
sudocmd_add]
} }
]) ])
# Remove members # Remove members
@@ -265,9 +247,7 @@ def main():
commands.append([name, commands.append([name,
"sudocmdgroup_remove_member", "sudocmdgroup_remove_member",
{ {
"sudocmd": [to_text(c) "sudocmd": sudocmd_del
for c in
sudocmd_del]
} }
]) ])
elif action == "member": elif action == "member":
@@ -277,7 +257,7 @@ def main():
# Ensure members are present # Ensure members are present
commands.append([name, "sudocmdgroup_add_member", commands.append([name, "sudocmdgroup_add_member",
{"sudocmd": [to_text(c) for c in sudocmd]} {"sudocmd": sudocmd}
]) ])
elif state == "absent": elif state == "absent":
if action == "sudocmdgroup": if action == "sudocmdgroup":
@@ -291,7 +271,7 @@ def main():
# Ensure members are absent # Ensure members are absent
commands.append([name, "sudocmdgroup_remove_member", commands.append([name, "sudocmdgroup_remove_member",
{"sudocmd": [to_text(c) for c in sudocmd]} {"sudocmd": sudocmd}
]) ])
else: else:
ansible_module.fail_json(msg="Unkown state '%s'" % state) ansible_module.fail_json(msg="Unkown state '%s'" % state)
@@ -303,8 +283,7 @@ def main():
# Execute commands # Execute commands
for name, command, args in commands: for name, command, args in commands:
try: try:
result = api_command(ansible_module, command, to_text(name), result = ansible_module.ipa_command(command, name, args)
args)
if action == "member": if action == "member":
if "completed" in result and result["completed"] > 0: if "completed" in result and result["completed"] > 0:
changed = True changed = True
@@ -331,12 +310,6 @@ def main():
if len(errors) > 0: if len(errors) > 0:
ansible_module.fail_json(msg=", ".join(errors)) ansible_module.fail_json(msg=", ".join(errors))
except Exception as e:
ansible_module.fail_json(msg=str(e))
finally:
temp_kdestroy(ccache_dir, ccache_name)
# Done # Done
ansible_module.exit_json(changed=changed, **exit_args) ansible_module.exit_json(changed=changed, **exit_args)

View File

@@ -31,13 +31,9 @@ DOCUMENTATION = """
module: ipasudorule module: ipasudorule
short description: Manage FreeIPA sudo rules short description: Manage FreeIPA sudo rules
description: Manage FreeIPA sudo rules description: Manage FreeIPA sudo rules
extends_documentation_fragment:
- ipamodule_base_docs
options: options:
ipaadmin_principal:
description: The admin principal
default: admin
ipaadmin_password:
description: The admin password
required: false
name: name:
description: The sudorule name description: The sudorule name
required: true required: true
@@ -187,10 +183,9 @@ EXAMPLES = """
RETURN = """ RETURN = """
""" """
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.ansible_freeipa_module import \
from ansible.module_utils.ansible_freeipa_module import temp_kinit, \ IPAAnsibleModule, compare_args_ipa, gen_add_del_lists, gen_add_list, \
temp_kdestroy, valid_creds, api_connect, api_command, compare_args_ipa, \ gen_intersection_list
module_params_get, gen_add_del_lists, gen_add_list, gen_intersection_list
def find_sudorule(module, name): def find_sudorule(module, name):
@@ -199,7 +194,7 @@ def find_sudorule(module, name):
"cn": name, "cn": name,
} }
_result = api_command(module, "sudorule_find", name, _args) _result = module.ipa_command("sudorule_find", name, _args)
if len(_result["result"]) > 1: if len(_result["result"]) > 1:
module.fail_json( module.fail_json(
@@ -235,12 +230,9 @@ def gen_args(description, usercat, hostcat, cmdcat, runasusercat,
def main(): def main():
ansible_module = AnsibleModule( ansible_module = IPAAnsibleModule(
argument_spec=dict( argument_spec=dict(
# general # general
ipaadmin_principal=dict(type="str", default="admin"),
ipaadmin_password=dict(type="str", required=False, no_log=True),
name=dict(type="list", aliases=["cn"], default=None, name=dict(type="list", aliases=["cn"], default=None,
required=True), required=True),
# present # present
@@ -286,42 +278,37 @@ def main():
# Get parameters # Get parameters
# general # general
ipaadmin_principal = module_params_get(ansible_module, names = ansible_module.params_get("name")
"ipaadmin_principal")
ipaadmin_password = module_params_get(ansible_module, "ipaadmin_password")
names = module_params_get(ansible_module, "name")
# present # present
# The 'noqa' variables are not used here, but required for vars(). # The 'noqa' variables are not used here, but required for vars().
# The use of 'noqa' ensures flake8 does not complain about them. # The use of 'noqa' ensures flake8 does not complain about them.
description = module_params_get(ansible_module, "description") # noqa description = ansible_module.params_get("description") # noqa
cmdcategory = module_params_get(ansible_module, 'cmdcategory') # noqa cmdcategory = ansible_module.params_get('cmdcategory') # noqa
usercategory = module_params_get(ansible_module, "usercategory") # noqa usercategory = ansible_module.params_get("usercategory") # noqa
hostcategory = module_params_get(ansible_module, "hostcategory") # noqa hostcategory = ansible_module.params_get("hostcategory") # noqa
runasusercategory = module_params_get(ansible_module, # noqa runasusercategory = ansible_module.params_get( # noqa
"runasusercategory") "runasusercategory")
runasgroupcategory = module_params_get(ansible_module, # noqa runasgroupcategory = ansible_module.params_get( # noqa
"runasgroupcategory") "runasgroupcategory")
hostcategory = module_params_get(ansible_module, "hostcategory") # noqa hostcategory = ansible_module.params_get("hostcategory") # noqa
nomembers = module_params_get(ansible_module, "nomembers") # noqa nomembers = ansible_module.params_get("nomembers") # noqa
host = module_params_get(ansible_module, "host") host = ansible_module.params_get("host")
hostgroup = module_params_get(ansible_module, "hostgroup") hostgroup = ansible_module.params_get("hostgroup")
user = module_params_get(ansible_module, "user") user = ansible_module.params_get("user")
group = module_params_get(ansible_module, "group") group = ansible_module.params_get("group")
allow_sudocmd = module_params_get(ansible_module, 'allow_sudocmd') allow_sudocmd = ansible_module.params_get('allow_sudocmd')
allow_sudocmdgroup = module_params_get(ansible_module, allow_sudocmdgroup = ansible_module.params_get('allow_sudocmdgroup')
'allow_sudocmdgroup') deny_sudocmd = ansible_module.params_get('deny_sudocmd')
deny_sudocmd = module_params_get(ansible_module, 'deny_sudocmd') deny_sudocmdgroup = ansible_module.params_get('deny_sudocmdgroup')
deny_sudocmdgroup = module_params_get(ansible_module, sudooption = ansible_module.params_get("sudooption")
'deny_sudocmdgroup') order = ansible_module.params_get("order")
sudooption = module_params_get(ansible_module, "sudooption") runasuser = ansible_module.params_get("runasuser")
order = module_params_get(ansible_module, "order") runasgroup = ansible_module.params_get("runasgroup")
runasuser = module_params_get(ansible_module, "runasuser") action = ansible_module.params_get("action")
runasgroup = module_params_get(ansible_module, "runasgroup")
action = module_params_get(ansible_module, "action")
# state # state
state = module_params_get(ansible_module, "state") state = ansible_module.params_get("state")
# Check parameters # Check parameters
@@ -393,13 +380,9 @@ def main():
changed = False changed = False
exit_args = {} exit_args = {}
ccache_dir = None
ccache_name = None # Connect to IPA API
try: with ansible_module.ipa_connect():
if not valid_creds(ansible_module, ipaadmin_principal):
ccache_dir, ccache_name = temp_kinit(ipaadmin_principal,
ipaadmin_password)
api_connect()
commands = [] commands = []
@@ -850,8 +833,7 @@ def main():
errors = [] errors = []
for name, command, args in commands: for name, command, args in commands:
try: try:
result = api_command(ansible_module, command, name, result = ansible_module.ipa_command(command, name, args)
args)
if "completed" in result: if "completed" in result:
if result["completed"] > 0: if result["completed"] > 0:
@@ -873,12 +855,6 @@ def main():
if len(errors) > 0: if len(errors) > 0:
ansible_module.fail_json(msg=", ".join(errors)) ansible_module.fail_json(msg=", ".join(errors))
except Exception as ex:
ansible_module.fail_json(msg=str(ex))
finally:
temp_kdestroy(ccache_dir, ccache_name)
# Done # Done
ansible_module.exit_json(changed=changed, **exit_args) ansible_module.exit_json(changed=changed, **exit_args)

View File

@@ -31,13 +31,9 @@ DOCUMENTATION = """
module: ipatopologysegment module: ipatopologysegment
short description: Manage FreeIPA topology segments short description: Manage FreeIPA topology segments
description: Manage FreeIPA topology segments description: Manage FreeIPA topology segments
extends_documentation_fragment:
- ipamodule_base_docs
options: options:
ipaadmin_principal:
description: The admin principal
default: admin
ipaadmin_password:
description: The admin password
required: false
suffix: suffix:
description: Topology suffix description: Topology suffix
required: true required: true
@@ -67,35 +63,41 @@ author:
EXAMPLES = """ EXAMPLES = """
- ipatopologysegment: - ipatopologysegment:
ipaadmin_password: SomeADMINpassword
suffix: domain suffix: domain
left: ipaserver.test.local left: ipaserver.test.local
right: ipareplica1.test.local right: ipareplica1.test.local
state: present state: present
- ipatopologysegment: - ipatopologysegment:
ipaadmin_password: SomeADMINpassword
suffix: domain suffix: domain
name: ipaserver.test.local-to-replica1.test.local name: ipaserver.test.local-to-replica1.test.local
state: absent state: absent
- ipatopologysegment: - ipatopologysegment:
ipaadmin_password: SomeADMINpassword
suffix: domain suffix: domain
left: ipaserver.test.local left: ipaserver.test.local
right: ipareplica1.test.local right: ipareplica1.test.local
state: absent state: absent
- ipatopologysegment: - ipatopologysegment:
ipaadmin_password: SomeADMINpassword
suffix: ca suffix: ca
name: ipaserver.test.local-to-replica1.test.local name: ipaserver.test.local-to-replica1.test.local
direction: left-to-right direction: left-to-right
state: reinitialized state: reinitialized
- ipatopologysegment: - ipatopologysegment:
ipaadmin_password: SomeADMINpassword
suffix: domain+ca suffix: domain+ca
left: ipaserver.test.local left: ipaserver.test.local
right: ipareplica1.test.local right: ipareplica1.test.local
state: absent state: absent
- ipatopologysegment: - ipatopologysegment:
ipaadmin_password: SomeADMINpassword
suffix: domain+ca suffix: domain+ca
left: ipaserver.test.local left: ipaserver.test.local
right: ipareplica1.test.local right: ipareplica1.test.local
@@ -113,19 +115,16 @@ not-found:
type: list type: list
""" """
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.ansible_freeipa_module import IPAAnsibleModule
from ansible.module_utils._text import to_text
from ansible.module_utils.ansible_freeipa_module import temp_kinit, \
temp_kdestroy, valid_creds, api_connect, api_command
def find_left_right(module, suffix, left, right): def find_left_right(module, suffix, left, right):
_args = { _args = {
"iparepltoposegmentleftnode": to_text(left), "iparepltoposegmentleftnode": left,
"iparepltoposegmentrightnode": to_text(right), "iparepltoposegmentrightnode": right,
} }
_result = api_command(module, "topologysegment_find", _result = module.ipa_command("topologysegment_find",
to_text(suffix), _args) suffix, _args)
if len(_result["result"]) > 1: if len(_result["result"]) > 1:
module.fail_json( module.fail_json(
msg="Combination of left node '%s' and right node '%s' is " msg="Combination of left node '%s' and right node '%s' is "
@@ -138,10 +137,10 @@ def find_left_right(module, suffix, left, right):
def find_cn(module, suffix, name): def find_cn(module, suffix, name):
_args = { _args = {
"cn": to_text(name), "cn": name,
} }
_result = api_command(module, "topologysegment_find", _result = module.ipa_command("topologysegment_find",
to_text(suffix), _args) suffix, _args)
if len(_result["result"]) > 1: if len(_result["result"]) > 1:
module.fail_json( module.fail_json(
msg="CN '%s' is not unique for suffix '%s'" % (name, suffix)) msg="CN '%s' is not unique for suffix '%s'" % (name, suffix))
@@ -156,7 +155,7 @@ def find_left_right_cn(module, suffix, left, right, name):
left_right = find_left_right(module, suffix, left, right) left_right = find_left_right(module, suffix, left, right)
if left_right is not None: if left_right is not None:
if name is not None and \ if name is not None and \
left_right["cn"][0] != to_text(name): left_right["cn"][0] != name:
module.fail_json( module.fail_json(
msg="Left and right nodes do not match " msg="Left and right nodes do not match "
"given name name (cn) '%s'" % name) "given name name (cn) '%s'" % name)
@@ -174,10 +173,8 @@ def find_left_right_cn(module, suffix, left, right, name):
def main(): def main():
ansible_module = AnsibleModule( ansible_module = IPAAnsibleModule(
argument_spec=dict( argument_spec=dict(
ipaadmin_principal=dict(type="str", default="admin"),
ipaadmin_password=dict(type="str", required=False, no_log=True),
suffix=dict(choices=["domain", "ca", "domain+ca"], required=True), suffix=dict(choices=["domain", "ca", "domain+ca"], required=True),
name=dict(type="str", aliases=["cn"], default=None), name=dict(type="str", aliases=["cn"], default=None),
left=dict(type="str", aliases=["leftnode"], default=None), left=dict(type="str", aliases=["leftnode"], default=None),
@@ -195,14 +192,12 @@ def main():
# Get parameters # Get parameters
ipaadmin_principal = ansible_module.params.get("ipaadmin_principal") suffixes = ansible_module.params_get("suffix")
ipaadmin_password = ansible_module.params.get("ipaadmin_password") name = ansible_module.params_get("name")
suffixes = ansible_module.params.get("suffix") left = ansible_module.params_get("left")
name = ansible_module.params.get("name") right = ansible_module.params_get("right")
left = ansible_module.params.get("left") direction = ansible_module.params_get("direction")
right = ansible_module.params.get("right") state = ansible_module.params_get("state")
direction = ansible_module.params.get("direction")
state = ansible_module.params.get("state")
# Check parameters # Check parameters
@@ -214,14 +209,8 @@ def main():
changed = False changed = False
exit_args = {} exit_args = {}
ccache_dir = None
ccache_name = None
try:
if not valid_creds(ansible_module, ipaadmin_principal):
ccache_dir, ccache_name = temp_kinit(ipaadmin_principal,
ipaadmin_password)
api_connect()
with ansible_module.ipa_connect():
commands = [] commands = []
for suffix in suffixes.split("+"): for suffix in suffixes.split("+"):
@@ -233,17 +222,17 @@ def main():
ansible_module.fail_json( ansible_module.fail_json(
msg="Left and right need to be set.") msg="Left and right need to be set.")
args = { args = {
"iparepltoposegmentleftnode": to_text(left), "iparepltoposegmentleftnode": left,
"iparepltoposegmentrightnode": to_text(right), "iparepltoposegmentrightnode": right,
} }
if name is not None: if name is not None:
args["cn"] = to_text(name) args["cn"] = name
res_left_right = find_left_right(ansible_module, suffix, res_left_right = find_left_right(ansible_module, suffix,
left, right) left, right)
if res_left_right is not None: if res_left_right is not None:
if name is not None and \ if name is not None and \
res_left_right["cn"][0] != to_text(name): res_left_right["cn"][0] != name:
ansible_module.fail_json( ansible_module.fail_json(
msg="Left and right nodes already used with " msg="Left and right nodes already used with "
"different name (cn) '%s'" % res_left_right["cn"]) "different name (cn) '%s'" % res_left_right["cn"])
@@ -260,7 +249,7 @@ def main():
# else: Nothing to change # else: Nothing to change
else: else:
if name is None: if name is None:
args["cn"] = to_text("%s-to-%s" % (left, right)) args["cn"] = "%s-to-%s" % (left, right)
commands.append(["topologysegment_add", args, suffix]) commands.append(["topologysegment_add", args, suffix])
elif state in ["absent", "disabled"]: elif state in ["absent", "disabled"]:
@@ -333,15 +322,9 @@ def main():
# Execute command # Execute command
for command, args, _suffix in commands: for command, args, _suffix in commands:
api_command(ansible_module, command, to_text(_suffix), args) ansible_module.ipa_command(command, _suffix, args)
changed = True changed = True
except Exception as e:
ansible_module.fail_json(msg=str(e))
finally:
temp_kdestroy(ccache_dir, ccache_name)
# Done # Done
ansible_module.exit_json(changed=changed, **exit_args) ansible_module.exit_json(changed=changed, **exit_args)

View File

@@ -31,13 +31,9 @@ DOCUMENTATION = """
module: ipatopologysuffix module: ipatopologysuffix
short description: Verify FreeIPA topology suffix short description: Verify FreeIPA topology suffix
description: Verify FreeIPA topology suffix description: Verify FreeIPA topology suffix
extends_documentation_fragment:
- ipamodule_base_docs
options: options:
ipaadmin_principal:
description: The admin principal
default: admin
ipaadmin_password:
description: The admin password
required: false
suffix: suffix:
description: Topology suffix description: Topology suffix
required: true required: true
@@ -52,6 +48,7 @@ author:
EXAMPLES = """ EXAMPLES = """
- ipatopologysuffix: - ipatopologysuffix:
ipaadmin_password: SomeADMINpassword
suffix: domain suffix: domain
state: verified state: verified
""" """
@@ -59,16 +56,12 @@ EXAMPLES = """
RETURN = """ RETURN = """
""" """
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.ansible_freeipa_module import IPAAnsibleModule
from ansible.module_utils._text import to_text
from ansible.module_utils.ansible_freeipa_module import execute_api_command
def main(): def main():
ansible_module = AnsibleModule( ansible_module = IPAAnsibleModule(
argument_spec=dict( argument_spec=dict(
ipaadmin_principal=dict(type="str", default="admin"),
ipaadmin_password=dict(type="str", required=False, no_log=True),
suffix=dict(choices=["domain", "ca"], required=True), suffix=dict(choices=["domain", "ca"], required=True),
state=dict(type="str", default="verified", state=dict(type="str", default="verified",
choices=["verified"]), choices=["verified"]),
@@ -80,10 +73,8 @@ def main():
# Get parameters # Get parameters
ipaadmin_principal = ansible_module.params.get("ipaadmin_principal") suffix = ansible_module.params_get("suffix")
ipaadmin_password = ansible_module.params.get("ipaadmin_password") state = ansible_module.params_get("state")
suffix = ansible_module.params.get("suffix")
state = ansible_module.params.get("state")
# Check parameters # Check parameters
@@ -91,16 +82,15 @@ def main():
# Create command # Create command
if state in ["verified"]: if state not in ["verified"]:
command = "topologysuffix_verify"
args = {}
else:
ansible_module.fail_json(msg="Unkown state '%s'" % state) ansible_module.fail_json(msg="Unkown state '%s'" % state)
# Execute command # Execute command
execute_api_command(ansible_module, ipaadmin_principal, ipaadmin_password, with ansible_module.ipa_connect():
command, to_text(suffix), args) # Execute command
ansible_module.ipa_command(["topologysuffix_verify", suffix,
{}])
# Done # Done

View File

@@ -20,9 +20,6 @@
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
from ansible.module_utils.ansible_freeipa_module import temp_kinit, \
temp_kdestroy, valid_creds, api_connect, api_command, module_params_get
from ansible.module_utils.basic import AnsibleModule
ANSIBLE_METADATA = {'metadata_version': '1.1', ANSIBLE_METADATA = {'metadata_version': '1.1',
'supported_by': 'community', 'supported_by': 'community',
'status': ['preview'], 'status': ['preview'],
@@ -33,6 +30,8 @@ DOCUMENTATION = """
module: ipatrust module: ipatrust
short_description: Manage FreeIPA Domain Trusts. short_description: Manage FreeIPA Domain Trusts.
description: Manage FreeIPA Domain Trusts. description: Manage FreeIPA Domain Trusts.
extends_documentation_fragment:
- ipamodule_base_docs
options: options:
realm: realm:
description: description:
@@ -97,6 +96,7 @@ author:
EXAMPLES = """ EXAMPLES = """
# add ad-trust # add ad-trust
- ipatrust: - ipatrust:
ipaadmin_password: SomeADMINpassword
realm: ad.example.test realm: ad.example.test
trust_type: ad trust_type: ad
admin: Administrator admin: Administrator
@@ -105,6 +105,7 @@ EXAMPLES = """
# delete ad-trust # delete ad-trust
- ipatrust: - ipatrust:
ipaadmin_password: SomeADMINpassword
realm: ad.example.test realm: ad.example.test
state: absent state: absent
""" """
@@ -113,13 +114,17 @@ RETURN = """
""" """
from ansible.module_utils.ansible_freeipa_module import \
IPAAnsibleModule
def find_trust(module, realm): def find_trust(module, realm):
_args = { _args = {
"all": True, "all": True,
"cn": realm, "cn": realm,
} }
_result = api_command(module, "trust_find", realm, _args) _result = module.ipa_command("trust_find", realm, _args)
if len(_result["result"]) > 1: if len(_result["result"]) > 1:
module.fail_json(msg="There is more than one realm '%s'" % (realm)) module.fail_json(msg="There is more than one realm '%s'" % (realm))
@@ -132,7 +137,7 @@ def find_trust(module, realm):
def del_trust(module, realm): def del_trust(module, realm):
_args = {} _args = {}
_result = api_command(module, "trust_del", realm, _args) _result = module.ipa_command("trust_del", realm, _args)
if len(_result["result"]["failed"]) > 0: if len(_result["result"]["failed"]) > 0:
module.fail_json( module.fail_json(
msg="Trust deletion has failed for '%s'" % (realm)) msg="Trust deletion has failed for '%s'" % (realm))
@@ -141,7 +146,7 @@ def del_trust(module, realm):
def add_trust(module, realm, args): def add_trust(module, realm, args):
_args = args _args = args
_result = api_command(module, "trust_add", realm, _args) _result = module.ipa_command("trust_add", realm, _args)
if "cn" not in _result["result"]: if "cn" not in _result["result"]:
module.fail_json( module.fail_json(
@@ -174,11 +179,9 @@ def gen_args(trust_type, admin, password, server, trust_secret, base_id,
def main(): def main():
ansible_module = AnsibleModule( ansible_module = IPAAnsibleModule(
argument_spec=dict( argument_spec=dict(
# general # general
ipaadmin_principal=dict(type="str", default="admin"),
ipaadmin_password=dict(type="str", required=False, no_log=True),
realm=dict(type="str", default=None, required=True), realm=dict(type="str", default=None, required=True),
# state # state
state=dict(type="str", default="present", state=dict(type="str", default="present",
@@ -207,35 +210,29 @@ def main():
ansible_module._ansible_debug = True ansible_module._ansible_debug = True
# general # general
ipaadmin_principal = module_params_get( realm = ansible_module.params_get("realm")
ansible_module, "ipaadmin_principal")
ipaadmin_password = module_params_get(ansible_module, "ipaadmin_password")
realm = module_params_get(ansible_module, "realm")
# state # state
state = module_params_get(ansible_module, "state") state = ansible_module.params_get("state")
# trust # trust
trust_type = module_params_get(ansible_module, "trust_type") trust_type = ansible_module.params_get("trust_type")
admin = module_params_get(ansible_module, "admin") admin = ansible_module.params_get("admin")
password = module_params_get(ansible_module, "password") password = ansible_module.params_get("password")
server = module_params_get(ansible_module, "server") server = ansible_module.params_get("server")
trust_secret = module_params_get(ansible_module, "trust_secret") trust_secret = ansible_module.params_get("trust_secret")
base_id = module_params_get(ansible_module, "base_id") base_id = ansible_module.params_get("base_id")
range_size = module_params_get(ansible_module, "range_size") range_size = ansible_module.params_get("range_size")
range_type = module_params_get(ansible_module, "range_type") range_type = ansible_module.params_get("range_type")
two_way = module_params_get(ansible_module, "two_way") two_way = ansible_module.params_get("two_way")
external = module_params_get(ansible_module, "external") external = ansible_module.params_get("external")
changed = False changed = False
exit_args = {} exit_args = {}
ccache_dir = None
ccache_name = None # Connect to IPA API
try: with ansible_module.ipa_connect():
if not valid_creds(ansible_module, ipaadmin_principal):
ccache_dir, ccache_name = temp_kinit(
ipaadmin_principal, ipaadmin_password)
api_connect()
res_find = find_trust(ansible_module, realm) res_find = find_trust(ansible_module, realm)
if state == "absent": if state == "absent":
@@ -257,12 +254,6 @@ def main():
add_trust(ansible_module, realm, args) add_trust(ansible_module, realm, args)
changed = True changed = True
except Exception as e:
ansible_module.fail_json(msg=str(e))
finally:
temp_kdestroy(ccache_dir, ccache_name)
# Done # Done
ansible_module.exit_json(changed=changed, **exit_args) ansible_module.exit_json(changed=changed, **exit_args)

View File

@@ -31,13 +31,9 @@ DOCUMENTATION = """
module: ipauser module: ipauser
short description: Manage FreeIPA users short description: Manage FreeIPA users
description: Manage FreeIPA users description: Manage FreeIPA users
extends_documentation_fragment:
- ipamodule_base_docs
options: options:
ipaadmin_principal:
description: The admin principal
default: admin
ipaadmin_password:
description: The admin password
required: false
name: name:
description: The list of users (internally uid). description: The list of users (internally uid).
required: false required: false
@@ -472,16 +468,11 @@ user:
returned: always returned: always
""" """
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_text from ansible.module_utils.ansible_freeipa_module import \
from ansible.module_utils.ansible_freeipa_module import temp_kinit, \ IPAAnsibleModule, compare_args_ipa, gen_add_del_lists, date_format, \
temp_kdestroy, valid_creds, api_connect, api_command, date_format, \ encode_certificate, load_cert_from_str, DN_x500_text, to_text
compare_args_ipa, module_params_get, api_check_param, api_get_realm, \
api_command_no_name, gen_add_del_lists, encode_certificate, \
load_cert_from_str, DN_x500_text, api_check_command
import six import six
if six.PY3: if six.PY3:
unicode = str unicode = str
@@ -494,7 +485,7 @@ def find_user(module, name, preserved=False):
if preserved: if preserved:
_args["preserved"] = preserved _args["preserved"] = preserved
_result = api_command(module, "user_find", name, _args) _result = module.ipa_command("user_find", name, _args)
if len(_result["result"]) > 1: if len(_result["result"]) > 1:
module.fail_json( module.fail_json(
@@ -792,12 +783,9 @@ def main():
nomembers=dict(type='bool', default=None), nomembers=dict(type='bool', default=None),
) )
ansible_module = AnsibleModule( ansible_module = IPAAnsibleModule(
argument_spec=dict( argument_spec=dict(
# general # general
ipaadmin_principal=dict(type="str", default="admin"),
ipaadmin_password=dict(type="str", required=False, no_log=True),
name=dict(type="list", aliases=["login"], default=None, name=dict(type="list", aliases=["login"], default=None,
required=False), required=False),
users=dict(type="list", aliases=["login"], default=None, users=dict(type="list", aliases=["login"], default=None,
@@ -836,69 +824,65 @@ def main():
# Get parameters # Get parameters
# general # general
ipaadmin_principal = module_params_get(ansible_module, names = ansible_module.params_get("name")
"ipaadmin_principal") users = ansible_module.params_get("users")
ipaadmin_password = module_params_get(ansible_module, "ipaadmin_password")
names = module_params_get(ansible_module, "name")
users = module_params_get(ansible_module, "users")
# present # present
first = module_params_get(ansible_module, "first") first = ansible_module.params_get("first")
last = module_params_get(ansible_module, "last") last = ansible_module.params_get("last")
fullname = module_params_get(ansible_module, "fullname") fullname = ansible_module.params_get("fullname")
displayname = module_params_get(ansible_module, "displayname") displayname = ansible_module.params_get("displayname")
initials = module_params_get(ansible_module, "initials") initials = ansible_module.params_get("initials")
homedir = module_params_get(ansible_module, "homedir") homedir = ansible_module.params_get("homedir")
shell = module_params_get(ansible_module, "shell") shell = ansible_module.params_get("shell")
email = module_params_get(ansible_module, "email") email = ansible_module.params_get("email")
principal = module_params_get(ansible_module, "principal") principal = ansible_module.params_get("principal")
principalexpiration = module_params_get(ansible_module, principalexpiration = ansible_module.params_get(
"principalexpiration") "principalexpiration")
if principalexpiration is not None: if principalexpiration is not None:
if principalexpiration[:-1] != "Z": if principalexpiration[:-1] != "Z":
principalexpiration = principalexpiration + "Z" principalexpiration = principalexpiration + "Z"
principalexpiration = date_format(principalexpiration) principalexpiration = date_format(principalexpiration)
passwordexpiration = module_params_get(ansible_module, passwordexpiration = ansible_module.params_get("passwordexpiration")
"passwordexpiration")
if passwordexpiration is not None: if passwordexpiration is not None:
if passwordexpiration[:-1] != "Z": if passwordexpiration[:-1] != "Z":
passwordexpiration = passwordexpiration + "Z" passwordexpiration = passwordexpiration + "Z"
passwordexpiration = date_format(passwordexpiration) passwordexpiration = date_format(passwordexpiration)
password = module_params_get(ansible_module, "password") password = ansible_module.params_get("password")
random = module_params_get(ansible_module, "random") random = ansible_module.params_get("random")
uid = module_params_get(ansible_module, "uid") uid = ansible_module.params_get("uid")
gid = module_params_get(ansible_module, "gid") gid = ansible_module.params_get("gid")
city = module_params_get(ansible_module, "city") city = ansible_module.params_get("city")
userstate = module_params_get(ansible_module, "userstate") userstate = ansible_module.params_get("userstate")
postalcode = module_params_get(ansible_module, "postalcode") postalcode = ansible_module.params_get("postalcode")
phone = module_params_get(ansible_module, "phone") phone = ansible_module.params_get("phone")
mobile = module_params_get(ansible_module, "mobile") mobile = ansible_module.params_get("mobile")
pager = module_params_get(ansible_module, "pager") pager = ansible_module.params_get("pager")
fax = module_params_get(ansible_module, "fax") fax = ansible_module.params_get("fax")
orgunit = module_params_get(ansible_module, "orgunit") orgunit = ansible_module.params_get("orgunit")
title = module_params_get(ansible_module, "title") title = ansible_module.params_get("title")
manager = module_params_get(ansible_module, "manager") manager = ansible_module.params_get("manager")
carlicense = module_params_get(ansible_module, "carlicense") carlicense = ansible_module.params_get("carlicense")
sshpubkey = module_params_get(ansible_module, "sshpubkey") sshpubkey = ansible_module.params_get("sshpubkey")
userauthtype = module_params_get(ansible_module, "userauthtype") userauthtype = ansible_module.params_get("userauthtype")
userclass = module_params_get(ansible_module, "userclass") userclass = ansible_module.params_get("userclass")
radius = module_params_get(ansible_module, "radius") radius = ansible_module.params_get("radius")
radiususer = module_params_get(ansible_module, "radiususer") radiususer = ansible_module.params_get("radiususer")
departmentnumber = module_params_get(ansible_module, "departmentnumber") departmentnumber = ansible_module.params_get("departmentnumber")
employeenumber = module_params_get(ansible_module, "employeenumber") employeenumber = ansible_module.params_get("employeenumber")
employeetype = module_params_get(ansible_module, "employeetype") employeetype = ansible_module.params_get("employeetype")
preferredlanguage = module_params_get(ansible_module, "preferredlanguage") preferredlanguage = ansible_module.params_get("preferredlanguage")
certificate = module_params_get(ansible_module, "certificate") certificate = ansible_module.params_get("certificate")
certmapdata = module_params_get(ansible_module, "certmapdata") certmapdata = ansible_module.params_get("certmapdata")
noprivate = module_params_get(ansible_module, "noprivate") noprivate = ansible_module.params_get("noprivate")
nomembers = module_params_get(ansible_module, "nomembers") nomembers = ansible_module.params_get("nomembers")
# deleted # deleted
preserve = module_params_get(ansible_module, "preserve") preserve = ansible_module.params_get("preserve")
# mod # mod
update_password = module_params_get(ansible_module, "update_password") update_password = ansible_module.params_get("update_password")
# general # general
action = module_params_get(ansible_module, "action") action = ansible_module.params_get("action")
state = module_params_get(ansible_module, "state") state = ansible_module.params_get("state")
# Check parameters # Check parameters
@@ -930,21 +914,17 @@ def main():
changed = False changed = False
exit_args = {} exit_args = {}
ccache_dir = None
ccache_name = None # Connect to IPA API
try: with ansible_module.ipa_connect():
if not valid_creds(ansible_module, ipaadmin_principal):
ccache_dir, ccache_name = temp_kinit(ipaadmin_principal,
ipaadmin_password)
api_connect()
# Check version specific settings # Check version specific settings
server_realm = api_get_realm() server_realm = ansible_module.ipa_get_realm()
# Default email domain # Default email domain
result = api_command_no_name(ansible_module, "config_show", {}) result = ansible_module.ipa_command_no_name("config_show", {})
default_email_domain = result["result"]["ipadefaultemaildomain"][0] default_email_domain = result["result"]["ipadefaultemaildomain"][0]
# Extend email addresses # Extend email addresses
@@ -1048,7 +1028,8 @@ def main():
# be part of check_parameters as this is used also before the # be part of check_parameters as this is used also before the
# connection to the API has been established. # connection to the API has been established.
if passwordexpiration is not None and \ if passwordexpiration is not None and \
not api_check_param("user_add", "krbpasswordexpiration"): not ansible_module.ipa_command_param_exists(
"user_add", "krbpasswordexpiration"):
ansible_module.fail_json( ansible_module.fail_json(
msg="The use of passwordexpiration is not supported by " msg="The use of passwordexpiration is not supported by "
"your IPA version") "your IPA version")
@@ -1058,7 +1039,7 @@ def main():
# be part of check_parameters as this is used also before the # be part of check_parameters as this is used also before the
# connection to the API has been established. # connection to the API has been established.
if certmapdata is not None and \ if certmapdata is not None and \
not api_check_command("user_add_certmapdata"): not ansible_module.ipa_command_exists("user_add_certmapdata"):
ansible_module.fail_json( ansible_module.fail_json(
msg="The use of certmapdata is not supported by " msg="The use of certmapdata is not supported by "
"your IPA version") "your IPA version")
@@ -1387,8 +1368,7 @@ def main():
errors = [] errors = []
for name, command, args in commands: for name, command, args in commands:
try: try:
result = api_command(ansible_module, command, name, result = ansible_module.ipa_command(command, name, args)
args)
if "completed" in result: if "completed" in result:
if result["completed"] > 0: if result["completed"] > 0:
changed = True changed = True
@@ -1432,12 +1412,6 @@ def main():
if len(errors) > 0: if len(errors) > 0:
ansible_module.fail_json(msg=", ".join(errors)) ansible_module.fail_json(msg=", ".join(errors))
except Exception as e:
ansible_module.fail_json(msg=str(e))
finally:
temp_kdestroy(ccache_dir, ccache_name)
# Done # Done
ansible_module.exit_json(changed=changed, user=exit_args) ansible_module.exit_json(changed=changed, user=exit_args)

View File

@@ -31,13 +31,9 @@ DOCUMENTATION = """
module: ipavault module: ipavault
short description: Manage vaults and secret vaults. short description: Manage vaults and secret vaults.
description: Manage vaults and secret vaults. KRA service must be enabled. description: Manage vaults and secret vaults. KRA service must be enabled.
extends_documentation_fragment:
- ipamodule_base_docs
options: options:
ipaadmin_principal:
description: The admin principal
default: admin
ipaadmin_password:
description: The admin password
required: false
name: name:
description: The vault name description: The vault name
required: true required: true
@@ -317,12 +313,9 @@ vault:
import os import os
from base64 import b64decode from base64 import b64decode
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_text from ansible.module_utils._text import to_text
from ansible.module_utils.ansible_freeipa_module import temp_kinit, \ from ansible.module_utils.ansible_freeipa_module import IPAAnsibleModule, \
temp_kdestroy, valid_creds, api_connect, api_command, \ gen_add_del_lists, compare_args_ipa, exit_raw_json, ipalib_errors
gen_add_del_lists, compare_args_ipa, module_params_get, exit_raw_json, \
ipalib_errors
def find_vault(module, name, username, service, shared): def find_vault(module, name, username, service, shared):
@@ -338,7 +331,7 @@ def find_vault(module, name, username, service, shared):
else: else:
_args['shared'] = shared _args['shared'] = shared
_result = api_command(module, "vault_find", name, _args) _result = module.ipa_command("vault_find", name, _args)
if len(_result["result"]) > 1: if len(_result["result"]) > 1:
module.fail_json( module.fail_json(
@@ -579,7 +572,7 @@ def get_stored_data(module, res_find, args):
# retrieve vault stored data # retrieve vault stored data
try: try:
result = api_command(module, 'vault_retrieve', name, pwdargs) result = module.ipa_command('vault_retrieve', name, pwdargs)
except ipalib_errors.NotFound: except ipalib_errors.NotFound:
return None return None
@@ -587,12 +580,9 @@ def get_stored_data(module, res_find, args):
def main(): def main():
ansible_module = AnsibleModule( ansible_module = IPAAnsibleModule(
argument_spec=dict( argument_spec=dict(
# generalgroups # generalgroups
ipaadmin_principal=dict(type="str", default="admin"),
ipaadmin_password=dict(type="str", required=False, no_log=True),
name=dict(type="list", aliases=["cn"], default=None, name=dict(type="list", aliases=["cn"], default=None,
required=True), required=True),
@@ -663,45 +653,40 @@ def main():
ansible_module._ansible_debug = True ansible_module._ansible_debug = True
# general # general
ipaadmin_principal = module_params_get(ansible_module, names = ansible_module.params_get("name")
"ipaadmin_principal")
ipaadmin_password = module_params_get(ansible_module, "ipaadmin_password")
names = module_params_get(ansible_module, "name")
# present # present
description = module_params_get(ansible_module, "description") description = ansible_module.params_get("description")
username = module_params_get(ansible_module, "username") username = ansible_module.params_get("username")
service = module_params_get(ansible_module, "service") service = ansible_module.params_get("service")
shared = module_params_get(ansible_module, "shared") shared = ansible_module.params_get("shared")
users = module_params_get(ansible_module, "users") users = ansible_module.params_get("users")
groups = module_params_get(ansible_module, "groups") groups = ansible_module.params_get("groups")
services = module_params_get(ansible_module, "services") services = ansible_module.params_get("services")
owners = module_params_get(ansible_module, "owners") owners = ansible_module.params_get("owners")
ownergroups = module_params_get(ansible_module, "ownergroups") ownergroups = ansible_module.params_get("ownergroups")
ownerservices = module_params_get(ansible_module, "ownerservices") ownerservices = ansible_module.params_get("ownerservices")
vault_type = module_params_get(ansible_module, "vault_type") vault_type = ansible_module.params_get("vault_type")
salt = module_params_get(ansible_module, "vault_salt") salt = ansible_module.params_get("vault_salt")
password = module_params_get(ansible_module, "vault_password") password = ansible_module.params_get("vault_password")
password_file = module_params_get(ansible_module, "vault_password_file") password_file = ansible_module.params_get("vault_password_file")
new_password = module_params_get(ansible_module, "new_password") new_password = ansible_module.params_get("new_password")
new_password_file = module_params_get(ansible_module, "new_password_file") new_password_file = ansible_module.params_get("new_password_file")
public_key = module_params_get(ansible_module, "vault_public_key") public_key = ansible_module.params_get("vault_public_key")
public_key_file = module_params_get(ansible_module, public_key_file = ansible_module.params_get("vault_public_key_file")
"vault_public_key_file") private_key = ansible_module.params_get("vault_private_key")
private_key = module_params_get(ansible_module, "vault_private_key") private_key_file = ansible_module.params_get("vault_private_key_file")
private_key_file = module_params_get(ansible_module,
"vault_private_key_file")
vault_data = module_params_get(ansible_module, "vault_data") vault_data = ansible_module.params_get("vault_data")
datafile_in = module_params_get(ansible_module, "datafile_in") datafile_in = ansible_module.params_get("datafile_in")
datafile_out = module_params_get(ansible_module, "datafile_out") datafile_out = ansible_module.params_get("datafile_out")
action = module_params_get(ansible_module, "action") action = ansible_module.params_get("action")
state = module_params_get(ansible_module, "state") state = ansible_module.params_get("state")
# Check parameters # Check parameters
@@ -732,17 +717,10 @@ def main():
changed = False changed = False
exit_args = {} exit_args = {}
ccache_dir = None
ccache_name = None
try:
if not valid_creds(ansible_module, ipaadmin_principal):
ccache_dir, ccache_name = temp_kinit(ipaadmin_principal,
ipaadmin_password)
# Need to set krb5 ccache name, due to context='ansible-freeipa'
if ccache_name is not None:
os.environ["KRB5CCNAME"] = ccache_name
api_connect(context='ansible-freeipa') with ansible_module.ipa_connect(context='ansible-freeipa') as ccache_name:
if ccache_name is not None:
os.environ["KRB5CCNAME"] = ccache_name
commands = [] commands = []
@@ -970,7 +948,7 @@ def main():
errors = [] errors = []
for name, command, args in commands: for name, command, args in commands:
try: try:
result = api_command(ansible_module, command, name, args) result = ansible_module.ipa_command(command, name, args)
if command == 'vault_archive': if command == 'vault_archive':
changed = 'Archived data into' in result['summary'] changed = 'Archived data into' in result['summary']
@@ -1012,12 +990,6 @@ def main():
if len(errors) > 0: if len(errors) > 0:
ansible_module.fail_json(msg=", ".join(errors)) ansible_module.fail_json(msg=", ".join(errors))
except Exception as exception:
ansible_module.fail_json(msg=str(exception))
finally:
temp_kdestroy(ccache_dir, ccache_name)
# Done # Done
# exit_raw_json is a replacement for ansible_module.exit_json that # exit_raw_json is a replacement for ansible_module.exit_json that

View File

@@ -31,13 +31,9 @@ DOCUMENTATION = """
module: ipa$name module: ipa$name
short description: Manage FreeIPA $name short description: Manage FreeIPA $name
description: Manage FreeIPA $name and $name members description: Manage FreeIPA $name and $name members
extends_documentation_fragment:
- ipamodule_base_docs
options: options:
ipaadmin_principal:
description: The admin principal.
default: admin
ipaadmin_password:
description: The admin password.
required: false
name: name:
description: The list of $name name strings. description: The list of $name name strings.
required: true required: true
@@ -65,17 +61,20 @@ options:
EXAMPLES = """ EXAMPLES = """
# Ensure $name NAME is present # Ensure $name NAME is present
- ipa$name: - ipa$name:
ipaadmin_password: SomeADMINpassword
name: NAME name: NAME
PARAMETERS PARAMETERS
# Ensure $name "NAME" member PARAMETER2 VALUE is present # Ensure $name "NAME" member PARAMETER2 VALUE is present
- ipa$name: - ipa$name:
ipaadmin_password: SomeADMINpassword
name: NAME name: NAME
PARAMETER2: VALUE PARAMETER2: VALUE
action: member action: member
# Ensure $name "NAME" member PARAMETER2 VALUE is absent # Ensure $name "NAME" member PARAMETER2 VALUE is absent
- ipa$name: - ipa$name:
ipaadmin_password: SomeADMINpassword
name: NAME name: NAME
PARAMETER2: VALUE PARAMETER2: VALUE
action: member action: member
@@ -83,11 +82,13 @@ EXAMPLES = """
# Ensure $name NAME is absent # Ensure $name NAME is absent
- ipa$name: - ipa$name:
ipaadmin_password: SomeADMINpassword
name: NAME name: NAME
state: absent state: absent
# Ensure $name NAME ... # Ensure $name NAME ...
- ipa$name: - ipa$name:
ipaadmin_password: SomeADMINpassword
name: NAME name: NAME
CHANGE PARAMETERS CHANGE PARAMETERS
""" """
@@ -96,10 +97,10 @@ RETURN = """
""" """
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.ansible_freeipa_module import \ from ansible.module_utils.ansible_freeipa_module import \
temp_kinit, temp_kdestroy, valid_creds, api_connect, api_command, \ IPAAnsibleModule, compare_args_ipa, gen_add_del_lists, gen_add_list, \
compare_args_ipa, module_params_get, gen_add_del_lists gen_intersection_list
import six import six
if six.PY3: if six.PY3:
@@ -109,7 +110,7 @@ if six.PY3:
def find_$name(module, name): def find_$name(module, name):
"""Find if a $name with the given name already exist.""" """Find if a $name with the given name already exist."""
try: try:
_result = api_command(module, "$name_show", name, {"all": True}) _result = module.ipa_command("$name_show", name, {"all": True})
except Exception: # pylint: disable=broad-except except Exception: # pylint: disable=broad-except
# An exception is raised if $name name is not found. # An exception is raised if $name name is not found.
return None return None
@@ -132,12 +133,9 @@ def gen_member_args(PARAMETER2):
def main(): def main():
ansible_module = AnsibleModule( ansible_module = IPAAnsibleModule(
argument_spec=dict( argument_spec=dict(
# general # general
ipaadmin_principal=dict(type="str", default="admin"),
ipaadmin_password=dict(type="str", required=False, no_log=True),
name=dict(type="list", aliases=["API_PARAMETER_NAME"], name=dict(type="list", aliases=["API_PARAMETER_NAME"],
default=None, required=True), default=None, required=True),
# present # present
@@ -159,18 +157,15 @@ def main():
# Get parameters # Get parameters
# general # general
ipaadmin_principal = module_params_get(ansible_module, names = ansible_module.params_get("name")
"ipaadmin_principal")
ipaadmin_password = module_params_get(ansible_module, "ipaadmin_password")
names = module_params_get(ansible_module, "name")
# present # present
PARAMETER1 = module_params_get(ansible_module, "PARAMETER1") PARAMETER1 = ansible_module.params_get("PARAMETER1")
PARAMETER2 = module_params_get(ansible_module, "PARAMETER2") PARAMETER2 = ansible_module.params_get("PARAMETER2")
action = module_params_get(ansible_module, "action") action = ansible_module.params_get("action")
# state # state
state = module_params_get(ansible_module, "state") state = ansible_module.params_get("state")
# Check parameters # Check parameters
@@ -200,13 +195,9 @@ def main():
changed = False changed = False
exit_args = {} exit_args = {}
ccache_dir = None
ccache_name = None # Connect to IPA API
try: with ansible_module.ipa_connect():
if not valid_creds(ansible_module, ipaadmin_principal):
ccache_dir, ccache_name = temp_kinit(ipaadmin_principal,
ipaadmin_password)
api_connect()
commands = [] commands = []
for name in names: for name in names:
@@ -257,13 +248,18 @@ def main():
ansible_module.fail_json( ansible_module.fail_json(
msg="No $name '%s'" % name) msg="No $name '%s'" % name)
if PARAMETER2 is None: # Reduce add lists for PARAMETER2
ansible_module.fail_json(msg="No PARAMETER2 given") # to new entries only that are not in res_find.
if PARAMETER2 is not None and \
"API_PARAMETER2_NAME" in res_find:
PARAMETER2 = gen_add_list(
PARAMETER2, res_find["API_PARAMETER2_NAME"])
commands.append([name, "$name_add_member", if PARAMETER2 is not None:
{ commands.append([name, "$name_add_member",
"PARAMETER2": PARAMETER2, {
}]) "PARAMETER2": PARAMETER2,
}])
elif state == "absent": elif state == "absent":
if action == "$name": if action == "$name":
@@ -275,13 +271,17 @@ def main():
ansible_module.fail_json( ansible_module.fail_json(
msg="No $name '%s'" % name) msg="No $name '%s'" % name)
if PARAMETER2 is None: # Reduce del lists of member_host and member_hostgroup,
ansible_module.fail_json(msg="No PARAMETER2 given") # to the entries only that are in res_find.
if PARAMETER2 is not None:
PARAMETER2 = gen_intersection_list(
PARAMETER2, res_find.get("API_PARAMETER2_NAME"))
commands.append([name, "$name_remove_member", if PARAMETER2 is not None:
{ commands.append([name, "$name_remove_member",
"PARAMETER2": PARAMETER2, {
}]) "PARAMETER2": PARAMETER2,
}])
else: else:
ansible_module.fail_json(msg="Unkown state '%s'" % state) ansible_module.fail_json(msg="Unkown state '%s'" % state)
@@ -294,8 +294,7 @@ def main():
for name, command, args in commands: for name, command, args in commands:
try: try:
result = api_command(ansible_module, command, name, result = ansible_module.ipa_command(command, name, args)
args)
if "completed" in result: if "completed" in result:
if result["completed"] > 0: if result["completed"] > 0:
changed = True changed = True
@@ -320,12 +319,6 @@ def main():
if len(errors) > 0: if len(errors) > 0:
ansible_module.fail_json(msg=", ".join(errors)) ansible_module.fail_json(msg=", ".join(errors))
except Exception as e:
ansible_module.fail_json(msg=str(e))
finally:
temp_kdestroy(ccache_dir, ccache_name)
# Done # Done
ansible_module.exit_json(changed=changed, **exit_args) ansible_module.exit_json(changed=changed, **exit_args)

View File

@@ -31,13 +31,9 @@ DOCUMENTATION = """
module: ipa$name module: ipa$name
short description: Manage FreeIPA $name short description: Manage FreeIPA $name
description: Manage FreeIPA $name description: Manage FreeIPA $name
extends_documentation_fragment:
- ipamodule_base_docs
options: options:
ipaadmin_principal:
description: The admin principal.
default: admin
ipaadmin_password:
description: The admin password.
required: false
name: name:
description: The list of $name name strings. description: The list of $name name strings.
required: true required: true
@@ -60,16 +56,19 @@ options:
EXAMPLES = """ EXAMPLES = """
# Ensure $name NAME is present # Ensure $name NAME is present
- ipa$name: - ipa$name:
ipaadmin_password: SomeADMINpassword
name: NAME name: NAME
PARAMETERS PARAMETERS
# Ensure $name NAME is absent # Ensure $name NAME is absent
- ipa$name: - ipa$name:
ipaadmin_password: SomeADMINpassword
name: NAME name: NAME
state: absent state: absent
# Ensure $name NAME ... # Ensure $name NAME ...
- ipa$name: - ipa$name:
ipaadmin_password: SomeADMINpassword
name: NAME name: NAME
CHANGE PARAMETERS CHANGE PARAMETERS
""" """
@@ -78,10 +77,8 @@ RETURN = """
""" """
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.ansible_freeipa_module import \ from ansible.module_utils.ansible_freeipa_module import \
temp_kinit, temp_kdestroy, valid_creds, api_connect, api_command, \ IPAAnsibleModule, compare_args_ipa
compare_args_ipa, module_params_get
import six import six
if six.PY3: if six.PY3:
@@ -91,7 +88,7 @@ if six.PY3:
def find_$name(module, name): def find_$name(module, name):
"""Find if a $name with the given name already exist.""" """Find if a $name with the given name already exist."""
try: try:
_result = api_command(module, "$name_show", name, {"all": True}) _result = module.ipa_command("$name_show", name, {"all": True})
except Exception: # pylint: disable=broad-except except Exception: # pylint: disable=broad-except
# An exception is raised if $name name is not found. # An exception is raised if $name name is not found.
return None return None
@@ -109,12 +106,9 @@ def gen_args(PARAMETER1, PARAMETER2):
def main(): def main():
ansible_module = AnsibleModule( ansible_module = IPAAnsibleModule(
argument_spec=dict( argument_spec=dict(
# general # general
ipaadmin_principal=dict(type="str", default="admin"),
ipaadmin_password=dict(type="str", required=False, no_log=True),
name=dict(type="list", aliases=["API_PARAMETER_NAME"], name=dict(type="list", aliases=["API_PARAMETER_NAME"],
default=None, required=True), default=None, required=True),
# present # present
@@ -134,17 +128,14 @@ def main():
# Get parameters # Get parameters
# general # general
ipaadmin_principal = module_params_get(ansible_module, names = ansible_module.params_get("name")
"ipaadmin_principal")
ipaadmin_password = module_params_get(ansible_module, "ipaadmin_password")
names = module_params_get(ansible_module, "name")
# present # present
PARAMETER1 = module_params_get(ansible_module, "PARAMETER1") PARAMETER1 = ansible_module.params_get("PARAMETER1")
PARAMETER2 = module_params_get(ansible_module, "PARAMETER2") PARAMETER2 = ansible_module.params_get("PARAMETER2")
# state # state
state = module_params_get(ansible_module, "state") state = ansible_module.params_get("state")
# Check parameters # Check parameters
@@ -170,13 +161,9 @@ def main():
changed = False changed = False
exit_args = {} exit_args = {}
ccache_dir = None
ccache_name = None # Connect to IPA API
try: with ansible_module.ipa_connect():
if not valid_creds(ansible_module, ipaadmin_principal):
ccache_dir, ccache_name = temp_kinit(ipaadmin_principal,
ipaadmin_password)
api_connect()
commands = [] commands = []
for name in names: for name in names:
@@ -215,8 +202,7 @@ def main():
for name, command, args in commands: for name, command, args in commands:
try: try:
result = api_command(ansible_module, command, name, result = ansible_module.ipa_command(command, name, args)
args)
if "completed" in result: if "completed" in result:
if result["completed"] > 0: if result["completed"] > 0:
changed = True changed = True
@@ -226,12 +212,6 @@ def main():
ansible_module.fail_json(msg="%s: %s: %s" % (command, name, ansible_module.fail_json(msg="%s: %s: %s" % (command, name,
str(e))) str(e)))
except Exception as e:
ansible_module.fail_json(msg=str(e))
finally:
temp_kdestroy(ccache_dir, ccache_name)
# Done # Done
ansible_module.exit_json(changed=changed, **exit_args) ansible_module.exit_json(changed=changed, **exit_args)