/
gerrit_account.in.py
301 lines (234 loc) · 10.6 KB
/
gerrit_account.in.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
# Copyright (C) 2015 Codethink Limited
#
# This program 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.
#
# This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
# Prepend the contents of common.py to this file to create the final
# self-contained module.
import logging
from ansible.module_utils.basic import *
DOCUMENTATION = '''
---
module: gerrit_account
author: Sam Thursfield
short_description: Manage accounts in an instance of Gerrit Code Review
'''
EXAMPLES = '''
- gerrit_account:
username: Jenkins
fullname: Jenkins continuous integration tool
email: admin@example.com
groups:
- Non-Interactive Users
- Testers
gerrit_url: http://gerrit.example.com:8080/
gerrit_admin_username: dicky
gerrit_admin_password: b0sst0nes
'''
# https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html
ACCOUNT_ARGUMENTS = dict(
username = dict(type='str', required=True),
# This is called 'name' in the Gerrit API, but that word implies 'unique
# identifier' in Ansible which is not true of a person's name. Hopefully
# calling it 'fullname' will prevent confusion.
fullname = dict(type='str'),
# Sets the 'primary' email. Any other email address the account has will be
# removed. The 'no_confirmation' setting will be used, so you don't have to
# authorize the email account.
email = dict(type='str'),
# This will remove any SSH keys that aren't what the user specified. As
# with emails, this is probably annoying in some situations (sorry if it
# annoyed you), but Ansible modules should *ensure* the system is in the
# specified state. Right now the module only lets you specify one SSH key,
# so it should *ensure* that there is only that key.
ssh_key = dict(type='str'),
http_password = dict(type='str'),
groups = dict(type='list'),
active = dict(type='bool', choices=BOOLEANS)
)
def create_account(gerrit, username=None):
# Although we could pass an AccountInput entry here to set details in one
# go, it's left up to the update_account() function, to avoid having a
# totally separate code path for create vs. update.
account_info = gerrit.put('/accounts/%s' % quote(username))
return account_info
def create_account_email(gerrit, account_id, email, preferred=False,
no_confirmation=False):
logging.info('Creating email %s for account %s', email, account_id)
email_input = {
# Setting 'email' is optional (it's already in the URL) but it's good
# to double check that the email is encoded in the URL properly.
'email': email,
'preferred': preferred,
'no_confirmation': no_confirmation,
}
logging.debug(email_input)
path = 'accounts/%s/emails/%s' % (account_id, quote(email))
headers = {'content-type': 'application/json'}
gerrit.post(path, data=json.dumps(email_input), headers=headers)
def create_account_ssh_key(gerrit, account_id, ssh_public_key):
logging.info('Creating SSH key %s for account %s', ssh_public_key,
account_id)
path = 'accounts/%s/sshkeys' % (account_id)
gerrit.post(path, data=ssh_public_key)
def create_group_membership(gerrit, account_id, group_id):
logging.info('Creating membership of %s in group %s', account_id, group_id)
path = 'groups/%s/members/%s' % (quote(group_id), account_id)
gerrit.put(path)
def ensure_only_member_of_these_groups(gerrit, account_id, ansible_groups):
path = 'accounts/%s' % account_id
group_info_list = get_list(gerrit, path + '/groups')
changed = False
gerrit_groups = []
for group_info in group_info_list:
if group_info['name'] in ansible_groups:
logging.info("Preserving %s membership of group %s", path,
group_info)
gerrit_groups.append(group_info['name'])
else:
logging.info("Removing %s from group %s", path, group_info)
membership_path = 'groups/%s/members/%s' % (
quote(group_info['id']), account_id)
try:
gerrit.delete(membership_path)
changed = True
except requests.exceptions.HTTPError as e:
if e.response.status_code == 404:
# This is a kludge, it'd be better to work out in advance
# which groups the user is a member of only via membership
# in a different. That's not trivial though with the
# current API Gerrit provides.
logging.info(
"Ignored %s; assuming membership of this group is due "
"to membership of a group that includes it.", e)
else:
raise
# If the user gave group IDs instead of group names, this will
# needlessly recreate the membership. The only actual issue will be that
# Ansible reports 'changed' when nothing really did change, I think.
#
# We might receive [""] when the user tries to pass in an empty list, so
# handle that.
for new_group in set(ansible_groups).difference(gerrit_groups):
if len(new_group) > 0:
create_group_membership(gerrit, account_id, new_group)
gerrit_groups.append(new_group)
changed = True
return gerrit_groups, changed
def ensure_only_one_account_email(gerrit, account_id, email):
path = 'accounts/%s' % account_id
email_info_list = get_list(gerrit, path + '/emails')
changed = False
found_email = False
for email_info in email_info_list:
existing_email = email_info['email']
if existing_email == email:
# Since we're deleting all emails except this one, there's no need
# to care whether it's the 'preferred' one. It soon will be!
logging.info("Keeping %s email %s", path, email)
found_email = True
else:
logging.info("Removing %s email %s", path, existing_email)
gerrit.delete(path + '/emails/%s' % quote(existing_email))
changed = True
if len(email) > 0 and not found_email:
create_account_email(gerrit, account_id, email,
preferred=True, no_confirmation=True)
changed = True
return email, changed
def ensure_only_one_account_ssh_key(gerrit, account_id, ssh_public_key):
path = 'accounts/%s' % account_id
ssh_key_info_list = get_list(gerrit, path + '/sshkeys')
changed = False
found_ssh_key = False
for ssh_key_info in ssh_key_info_list:
if ssh_key_info['ssh_public_key'] == ssh_public_key:
logging.info("Keeping %s SSH key %s", path, ssh_key_info)
found_ssh_key = True
else:
logging.info("Removing %s SSH key %s", path, ssh_key_info)
gerrit.delete(path + '/sshkeys/%i' % ssh_key_info['seq'])
changed = True
if len(ssh_public_key) > 0 and not found_ssh_key:
create_account_ssh_key(gerrit, account_id, ssh_public_key)
changed = True
return ssh_public_key, changed
def update_account(gerrit, username=None, **params):
change = False
try:
account_info = gerrit.get('/accounts/%s' % quote(username))
except requests.exceptions.HTTPError as e:
if e.response.status_code == 404:
logging.info("Account %s not found, creating it.", username)
account_info = create_account(gerrit, username)
change = True
else:
raise
logging.debug(
'Existing account info for account %s: %s', username,
json.dumps(account_info, indent=4))
account_id = account_info['_account_id']
path = 'accounts/%s' % account_id
output = {}
output['id'] = account_id
fullname, fullname_changed = maybe_update_field(
gerrit, path, 'name', account_info.get('name'), params.get('fullname'))
output['fullname'] = fullname
change |= fullname_changed
# Ansible sets the value of params that the user did not provide to None.
if params.get('active') is not None:
active = get_boolean(gerrit, path + '/active')
active, active_changed = maybe_update_field(
gerrit, path, 'active', active, params['active'], type='bool')
output['active'] = active
change |= active_changed
if params.get('email') is not None:
email, emails_changed = ensure_only_one_account_email(
gerrit, account_id, params['email'])
output['email'] = email
change |= emails_changed
if params.get('groups') is not None:
groups, groups_changed = ensure_only_member_of_these_groups(
gerrit, account_id, params['groups'])
output['groups'] = groups
change |= groups_changed
if params.get('http_password') is not None:
http_password = get_string(gerrit, path + '/password.http')
http_password, http_password_changed = maybe_update_field(
gerrit, path, 'http_password', http_password,
params.get('http_password'),
gerrit_api_path='password.http')
output['http_password'] = http_password
change |= http_password_changed
if params.get('ssh_key') is not None:
ssh_key, ssh_keys_changed = ensure_only_one_account_ssh_key(
gerrit, account_id, params['ssh_key'])
output['ssh_key'] = ssh_key
change |= ssh_keys_changed
return output, change
def main():
logging.basicConfig(filename='/tmp/ansible-gerrit-debug.log',
level=logging.DEBUG)
argument_spec = dict()
argument_spec.update(ACCOUNT_ARGUMENTS)
argument_spec.update(GERRIT_COMMON_ARGUMENTS)
module = AnsibleModule(argument_spec)
logging.debug('Module parameters: %s', json.dumps(module.params, indent=4))
try:
gerrit = gerrit_connection(**module.params)
output, changed = update_account(
gerrit, **module.params)
module.exit_json(changed=changed, **output)
except (AnsibleGerritError, requests.exceptions.RequestException) as e:
logging.error('%r', e)
module.fail_json(msg=str(e))
main()