Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New module: management of users in ManageIQ (monitoring/manageiq/manageiq_user) #25106

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/docsite/rst/dev_guide/developing_module_utilities.rst
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ The following is a list of module_utils files and a general description. The mod
- ismount.py - Contains single helper function that fixes os.path.ismount
- junos.py - Definitions and helper functions for modules that manage Junos networking devices
- known_hosts.py - utilities for working with known_hosts file
- manageiq.py - Functions and utilities for modules that work with ManageIQ platform and its resources.
- mysql.py - Allows modules to connect to a MySQL instance
- netapp.py - Functions and utilities for modules that work with the NetApp storage platforms.
- netcfg.py - Configuration utility functions for use by networking modules
Expand Down
77 changes: 77 additions & 0 deletions lib/ansible/module_utils/manageiq.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
#
# Copyright (c) 2017, Daniel Korn <korndaniel1@gmail.com>
#
# This code is part of Ansible, but is an independent component.
# This particular file snippet, and this file snippet only, is BSD licensed.
# Modules you write using this snippet, which is embedded dynamically by Ansible
# still belong to the author of the module, and may assign their own license
# to the complete work.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


import os
from manageiq_client.api import ManageIQClient
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

handle import error



def manageiq_argument_spec():
return dict(
miq_url=dict(default=os.environ.get('MIQ_URL', None)),
miq_username=dict(default=os.environ.get('MIQ_USERNAME', None)),
miq_password=dict(default=os.environ.get('MIQ_PASSWORD', None), no_log=True),
validate_certs=dict(require=False, type='bool', default=True),
ca_bundle_path=dict(required=False, type='str', defualt=None)
)


class ManageIQ(object):
"""
class encapsulating ManageIQ API client
"""

def __init__(self, module):

for arg in ['miq_url', 'miq_username', 'miq_password']:
if module.params[arg] in (None, ''):
module.fail_json(msg="missing required argument: {}".format(arg))

url = module.params['miq_url']
username = module.params['miq_username']
password = module.params['miq_password']
verify_ssl = module.params['validate_certs']
ca_bundle_path = module.params['ca_bundle_path']

self.module = module
self.api_url = url + '/api'
self.client = ManageIQClient(self.api_url, (username, password), verify_ssl=verify_ssl, ca_bundle_path=ca_bundle_path)

def find_collection_resource_by(self, collection_name, **params):
""" Searches the collection resource by the collection name and the param passed

Returns:
the resource as an object if it exists in manageiq, None otherwise.
"""
try:
entity = self.client.collections.__getattribute__(collection_name).get(**params)
except ValueError:
return None
except Exception as e:
self.module.fail_json(msg="Failed to find resource {error}".format(error=e))
return vars(entity)
Empty file.
232 changes: 232 additions & 0 deletions lib/ansible/modules/monitoring/manageiq/manageiq_user.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,232 @@
#!/usr/bin/python
#
# (c) 2017, Daniel Korn <korndaniel1@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.

ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}


DOCUMENTATION = '''

module: manageiq_user

short_description: Management of users in ManageIQ
extends_documentation_fragment: manageiq
version_added: '2.4'
author: Daniel Korn (@dkorn)
description:
- The manageiq_user module supports adding, updating and deleting users in ManageIQ.

options:
name:
description:
- The unique userid in manageiq, often mentioned as username
required: true
default: null
fullname:
description:
- The users' full name
required: false
default: null
password:
description:
- The users' password
required: false
default: null
group:
description:
- The name of the group to which the user belongs
required: false
default: null
email:
description:
- The users' E-mail address
required: false
default: null
state:
description:
- The state of the user
- On present, it will create the user if it does not exist or update the
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use formatting options: for example C(present) instead of present.

user if the associated data is different
- On absent, it will delete the user if it exists
required: False
choices: ['present', 'absent']
default: 'present'
'''

EXAMPLES = '''
- name: Create a new user in ManageIQ
manageiq_user:
name: 'dkorn'
fullname: 'Daniel Korn'
password: '******'
group: 'EvmGroup-user'
email: 'dkorn@redhat.com'
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

state: 'present'
miq_url: 'http://localhost:3000'
miq_username: 'admin'
miq_password: '******'
validate_certs: False
'''

RETURN = '''
'''

from ansible.module_utils.basic import AnsibleModule
import ansible.module_utils.manageiq as manageiq_utils


class ManageIQUser(object):
"""
object to execute user management operations in manageiq
"""

def __init__(self, manageiq):
self.changed = False
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

changed doesn't need to be an attribute.

self.manageiq = manageiq

def delete_user(self, userid):
"""Deletes the user from manageiq.

Returns:
a short message describing the operation executed.
"""
user = self.manageiq.find_collection_resource_by('users', userid=userid)
if not user: # user doesn't exist
return dict(
changed=self.changed,
msg="User {userid} does not exist in manageiq".format(userid=userid))
try:
url = '{api_url}/users/{user_id}'.format(api_url=self.manageiq.api_url, user_id=user['id'])
result = self.manageiq.client.post(url, action='delete')
self.changed = True
return dict(changed=self.changed, msg=result['message'])
except Exception as e:
self.manageiq.module.fail_json(msg="Failed to delete user {userid}: {error}".format(userid=userid, error=e))

def user_update_required(self, user, username, group_id, email):
""" Returns True if the username, group id or email passed for the user
differ from the user's existing ones, False otherwise.
"""
if username is not None and user['name'] != username:
return True
if group_id is not None and user['current_group_id'] != group_id:
return True
if email is not None and user.get('email') != email:
return True
return False

def update_user_if_required(self, user, userid, username, group_id, password, email):
"""Updates the user in manageiq.

Returns:
the created user id, name, created_on timestamp,
updated_on timestamp, userid and current_group_id
"""
if not self.user_update_required(user, username, group_id, email):
return dict(
changed=self.changed,
msg="User {userid} already exist, no need for updates".format(userid=userid))
url = '{api_url}/users/{user_id}'.format(api_url=self.manageiq.api_url, user_id=user.id)
resource = {'userid': userid, 'name': username, 'password': password,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am not sure it the resource dictionary should contain all these keys or only the ones with value which isn't None ? I mean, when password parameter is set andemail parameter is not set, will the API unset the email or keep this attribute unmodified ?

'group': {'id': group_id}, 'email': email}
try:
result = self.manageiq.client.post(url, action='edit', resource=resource)
except Exception as e:
self.manageiq.module.fail_json(msg="Failed to update user {userid}: {error}".format(userid=userid, error=e))
self.changed = True
return dict(
changed=self.changed,
msg="Successfully updated the user {userid}: {user_details}".format(userid=userid, user_details=result))

def create_user(self, userid, username, group_id, password, email):
"""Creates the user in manageiq.

Returns:
the created user id, name, created_on timestamp,
updated_on timestamp, userid and current_group_id
"""
url = '{api_url}/users'.format(api_url=self.manageiq.api_url)
resource = {'userid': userid, 'name': username, 'password': password,
'group': {'id': group_id}, 'email': email}
try:
result = self.manageiq.client.post(url, action='create', resource=resource)
except Exception as e:
self.manageiq.module.fail_json(msg="Failed to create user {userid}: {error}".format(userid=userid, error=e))
self.changed = True
return dict(
changed=self.changed,
msg="Successfully created the user {userid}: {user_details}".format(userid=userid, user_details=result['results']))

def create_or_update_user(self, userid, username, password, group, email):
""" Create or update a user in manageiq.

Returns:
Whether or not a change took place and a message describing the
operation executed.
"""
group = self.manageiq.find_collection_resource_by('groups', description=group)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

group parameter is flagged as not required in argument_spec, what returns the ManageIQ API when group is None ?

if not group: # group doesn't exist
self.manageiq.module.fail_json(
msg="Failed to create user {userid}: group {group_name} does not exist in manageiq".format(userid=userid, group_name=group))

user = self.manageiq.find_collection_resource_by('users', userid=userid)
if user: # user already exist
return self.update_user_if_required(user, userid, username, group['id'], password, email)
else:
return self.create_user(userid, username, group['id'], password, email)


def main():
module = AnsibleModule(
argument_spec=dict(
manageiq_utils.manageiq_argument_spec(),
name=dict(required=True, type='str'),
fullname=dict(required=False, type='str'),
password=dict(required=False, type='str', no_log=True),
group=dict(required=False, type='str'),
email=dict(required=False, type='str'),
state=dict(required=False, type='str',
choices=['present', 'absent'], defualt='present'),
),
required_if=[
('state', 'present', ['fullname', 'group', 'password'])
],
)

name = module.params['name']
fullname = module.params['fullname']
password = module.params['password']
group = module.params['group']
email = module.params['email']
state = module.params['state']

manageiq = manageiq_utils.ManageIQ(module)
manageiq_user = ManageIQUser(manageiq)
if state == "present":
res_args = manageiq_user.create_or_update_user(name, fullname,
password, group, email)
if state == "absent":
res_args = manageiq_user.delete_user(name)

module.exit_json(**res_args)


if __name__ == "__main__":
main()
51 changes: 51 additions & 0 deletions lib/ansible/utils/module_docs_fragments/manageiq.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
#
# (c) 2017, Daniel Korn <korndaniel1@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.


class ModuleDocFragment(object):

# Standard ManageIQ documentation fragment
DOCUMENTATION = """
options:
miq_url:
description:
- The ManageIQ environment url
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Full sentences + full stops
Capitals for acronyms

The ManageIQ environment URL.

default: MIQ_URL env var if set. otherwise, it is required to pass it
miq_username:
description:
- ManageIQ username
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ManageIQ username. C(MIQ_USERNAME) env var if set. otherwise, it is required to pass it.

and delete the default: line.

This applies to the remainder of this file

default: MIQ_USERNAME env var if set. otherwise, it is required to pass it
miq_password:
description:
- ManageIQ password
default: MIQ_PASSWORD env var if set. otherwise, it is required to pass it
validate_certs:
required: False
description:
- Whether SSL certificates should be verified for HTTPS requests
default: True
choices: ['True', 'False']
ca_bundle_path:
required: False
description:
- The path to a CA_BUNDLE file or directory with certificates
default: null

requirements:
- 'manageiq-client (source: https://github.com/ManageIQ/manageiq-api-client-python/)'
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To make this a clickable link please do
'manageiq-client U(https://github.com/ManageIQ/manageiq-api-client-python/)'

"""