Coverage for /Users/jingyu.wy/git/ansible-module-apsarastack/src/ansible_collections/alibaba/apsarastack/plugins/modules/ali_ram_user.py: 26%
65 statements
« prev ^ index » next coverage.py v7.8.0, created at 2025-05-22 16:02 +0800
« prev ^ index » next coverage.py v7.8.0, created at 2025-05-22 16:02 +0800
1#!/usr/bin/python
2# -*- coding: utf-8 -*-
4# Copyright (c) 2017-present Alibaba Group Holding Limited. He Guimin <heguimin36@163.com.com>
5# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6#
7# This file is part of Ansible
8#
9# Ansible is free software: you can redistribute it and/or modify
10# it under the terms of the GNU General Public License as published by
11# the Free Software Foundation, either version 3 of the License, or
12# (at your option) any later version.
13#
14# Ansible is distributed in the hope that it will be useful,
15# but WITHOUT ANY WARRANTY; without even the implied warranty of
16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17# GNU General Public License for more details.
18#
19# You should have received a copy of the GNU General Public License
20# along with Ansible. If not, see http://www.gnu.org/licenses/.
22from __future__ import (absolute_import, division, print_function)
24__metaclass__ = type
26ANSIBLE_METADATA = {'metadata_version': '1.1',
27 'status': ['preview'],
28 'supported_by': 'community'}
30DOCUMENTATION = """
31---
32module: ali_ram_user
33short_description: Create, Delete, Update Ram User in Alibaba Cloud.
34description:
35 - Create, Delete, Update Ram User in Alibaba Cloud.
36 - An unique ali_ram_user module is determined by parameters user_name.
37options:
38 state:
39 description:
40 - If I(state=present), user will be created.
41 - If I(state=absent), user will be removed.
42 choices: ['present', 'absent']
43 default: 'present'
44 type: str
45 user_name:
46 description:
47 - The username. It must be 1 to 64 characters in length.
48 - One of I(user_name) and I(user_id) must be specified when operate existing user.
49 aliases: ['name']
50 type: str
51 user_id:
52 description:
53 - The ID of user.
54 - One of I(user_name) and I(user_id) must be specified when operate existing user.
55 aliases: ['id']
56 type: str
57 display_name:
58 description:
59 - The display name. It must be 1 to 128 characters in length.
60 type: str
61 mobile_phone:
62 description:
63 - The mobile phone number of the RAM user. International area code-mobile phone number.
64 type: str
65 aliases: ['phone']
66 email:
67 description:
68 - The email address of the RAM user.
69 type: str
70 comments:
71 description:
72 - The comment. It must be 1 to 128 characters in length.
73 type: str
74 new_user_name:
75 description:
76 - The new username of the new RAM user. It must be 1 to 64 characters in length.
77 type: str
78requirements:
79 - "python >= 3.6"
80 - "footmark >= 1.17.0"
81extends_documentation_fragment:
82 - apsarastack
83author:
84 - "He Guimin (@xiaozhu36)"
85"""
87EXAMPLES = """
88# Note: These examples do not set authentication details, see the Alibaba Cloud Guide for details.
89- name: Changed. Create a new user
90 ali_ram_user:
91 user_name: ansible
92 display_name: ab
93 mobile_phone: 18988888888
94 email: 11288222@qq.com
95 comments: ansible_test
97- name: Changed. Update user
98 ali_ram_user:
99 user_name: '{{ user_name }}'
100 new_user_name: ansible2
102- name: Changed. Delete user
103 ali_ram_user:
104 state: absent
105 user_name: '{{ user_name}}'
107"""
109RETURN = '''
110user:
111 description: Returns an array of complex objects as described below.
112 returned: always
113 type: complex
114 contains:
115 user_name:
116 description: The username.
117 returned: always
118 type: str
119 sample: Alice
120 name:
121 description: alias of 'user_name'.
122 returned: always
123 type: str
124 sample: Alice
125 user_id:
126 description: The ID of the RAM user.
127 returned: always
128 type: str
129 sample: 122748924538****
130 id:
131 description: alias of 'user_id'.
132 returned: always
133 type: str
134 sample: 122748924538****
135 mobile_phone:
136 description: The mobile phone number of the RAM user.
137 returned: always
138 type: str
139 sample: 86-1860000****
140 phone:
141 description: alias of 'mobile_phone'.
142 returned: always
143 type: str
144 sample: vpc-c2e00da5
145 email:
146 description: The email address of the RAM user.
147 returned: always
148 type: str
149 sample: alice@example.com
150 display_name:
151 description: The display name.
152 returned: always
153 type: str
154 sample: Alice
155 create_date:
156 description: The date and time when the RAM user was created.
157 returned: always
158 type: str
159 sample: '2015-01-23T12:33:18Z'
160 comments:
161 description: The comment.
162 returned: always
163 type: string
164 sample: ansible test
165'''
167from ansible.module_utils.basic import AnsibleModule
168from ansible_collections.alibaba.apsarastack.plugins.module_utils.apsarastack_common import common_argument_spec
169from ansible_collections.alibaba.apsarastack.plugins.module_utils.apsarastack_connections import ascm_connect, do_common_request
171HAS_FOOTMARK = False
173try:
174 from footmark.exception import RAMResponseError
175 HAS_FOOTMARK = True
176except ImportError:
177 HAS_FOOTMARK = False
179def ascm_list_user(module, ram_conn):
180 response = do_common_request(
181 ram_conn, "POST", "ascm", "2019-05-10", "ListUsers", body=params)
182# def dns_exists_v2(module, dns_conn, domain_name=None, domain_id=None):
183# if not domain_name and not domain_id:
184# return False
185# try:
186# i = 1
187# params = {
188# "PageNumber": i,
189# "PageSize": 10,
190# }
191# response = do_common_request(
192# dns_conn, "POST", "CloudDns", "2021-06-24", "DescribeGlobalZones", body=params)
193# for domain in response["Data"]:
194# if domain_name:
195# if domain["Name"] == domain_name:
196# return domain
197# else:
198# if domain["Id"] == domain_id:
199# return domain
200# while response["Data"] and (i-1) * params["PageSize"] + len(response["Data"]) < response["TotalItems"]:
201# i += 1
202# params = {
203# "PageNumber": i,
204# "PageSize": 10,
205# }
206# response = do_common_request(
207# dns_conn, "POST", "CloudDns", "2021-06-24", "DescribeGlobalZones", body=params)
208# for domain in response["Data"]:
209# if domain_name:
210# if domain["Name"] == domain_name:
211# return domain
212# else:
213# if domain["Id"] == domain_id:
214# return domain
215# except Exception as e:
216# module.fail_json(msg="Failed to dns_exists_v2: {0}".format(e))
221def user_exists(module, ram_conn, user_name, user_id):
222 params = {
223 "loginName": "uiflinkuser0522060210",
224 }
225 # try:
226 response = do_common_request(
227 ram_conn, "POST", "ascm", "2019-05-10", "ListUsers", "/ascm/auth/user/listUsers", body=params)
228 # except Exception as ex:
230 # return module.fail_json(msg="11111111111%s111111111111" % ex)
231 try:
232 user = None
233 for u in ram_conn.list_users():
234 if user_name and u.name != user_name:
235 continue
236 if user_id and u.user_id != user_id:
237 continue
238 user = u
239 return user
240 except Exception as e:
241 module.fail_json(msg="Failed to describe Users: {0}".format(e))
244def main():
245 argument_spec = common_argument_spec()
246 argument_spec.update(dict(
247 state=dict(default='present', choices=['present', 'absent']),
248 user_name=dict(type='str', aliases=['name']),
249 user_id=dict(type='str', aliases=['id']),
250 display_name=dict(type='str'),
251 mobile_phone=dict(type='str', aliases=['phone']),
252 email=dict(type='str'),
253 comments=dict(type='str'),
254 new_user_name=dict(type='str')
255 ))
257 module = AnsibleModule(argument_spec=argument_spec)
259 if HAS_FOOTMARK is False:
260 module.fail_json(msg='footmark required for this module.')
262 ram_conn = ascm_connect( module)
264 # Get values of variable
265 state = module.params['state']
266 user_name = module.params['user_name']
267 user_id = module.params['user_id']
268 changed = False
270 # Check if user exists
271 user = user_exists(module, ram_conn, user_name, user_id)
273 if state == 'absent':
274 if not user:
275 module.exit_json(changed=changed, user={})
276 try:
277 module.exit_json(changed=user.delete(), user={})
278 except RAMResponseError as ex:
279 module.fail_json(msg='Unable to delete user {0}, error: {1}'.format(user_name, ex))
281 if not user:
282 try:
283 user = ram_conn.create_user(**module.params)
284 module.exit_json(changed=True, user=user.read())
285 except RAMResponseError as e:
286 module.fail_json(msg='Unable to create user, error: {0}'.format(e))
288 try:
289 res = user.update(**module.params)
290 if res:
291 module.exit_json(changed=True, user=res.read())
292 except RAMResponseError as e:
293 module.fail_json(msg='Unable to update user, error: {0}'.format(e))
295 module.exit_json(changed=changed, user=user.read())
298if __name__ == '__main__':
299 main()