blob: 0441b42a9e5b4b8abe7795b3f59729511b0c7a58 [file] [log] [blame]
Jakub Josef3de91af2016-12-08 17:03:33 +01001import logging
2logger = logging.getLogger(__name__)
3
4create_admin_groovy = u"""\
5import jenkins.model.*
6import hudson.security.*
7def instance = Jenkins.getInstance()
8def hudsonRealm = new HudsonPrivateSecurityRealm(false)
9def result=hudsonRealm.createAccount("{username}","{password}")
10instance.setSecurityRealm(hudsonRealm)
11def strategy = new hudson.security.FullControlOnceLoggedInAuthorizationStrategy()
12strategy.setAllowAnonymousRead(false)
13instance.setAuthorizationStrategy(strategy)
14instance.save()
15print(result)
Jakub Josef7ae6b242016-12-14 14:41:44 +010016""" # noqa
Jakub Josef3de91af2016-12-08 17:03:33 +010017
18
19create_user_groovy = u"""\
20def result=jenkins.model.Jenkins.instance.securityRealm.createAccount("{username}", "{password}")
21print(result)
22""" # noqa
23
Jakub Josefe3807982016-12-15 11:54:51 +010024
Jakub Josef3de91af2016-12-08 17:03:33 +010025def present(name, username, password, admin=False):
26 """
27 Main jenkins users state method
28
29 :param username: user name
30 :param password: user password
31 :param admin: is admin user flag (username will be always admin)
32 :returns: salt-specified state dict
33 """
34 test = __opts__['test'] # noqa
35 ret = {
36 'name': username,
37 'changes': {},
38 'result': False,
39 'comment': '',
40 }
41
42 result = False
43 if test:
44 status = 'CREATED'
45 ret['changes'][username] = status
46 ret['comment'] = 'User %s %s' % (username, status.lower())
47 else:
Jakub Josef7ae6b242016-12-14 14:41:44 +010048 # try to call jenkins script api with given user and password to prove
49 # his existence
50 user_exists_result = __salt__['jenkins_common.call_groovy_script'](
Jakub Josefe3807982016-12-15 11:54:51 +010051 "print(\"TEST\")", {"username": username}, username, password, [200, 401])
Jakub Josef7ae6b242016-12-14 14:41:44 +010052 user_exists = user_exists_result and user_exists_result[
53 "code"] == 200 and user_exists_result["msg"].count("TEST") == 1
54 if not user_exists:
55 call_result = __salt__['jenkins_common.call_groovy_script'](
56 create_admin_groovy if admin else create_user_groovy, {"username": username, "password": password})
57 if call_result["code"] == 200 and call_result["msg"].count(username) == 1:
58 status = "CREATED" if not admin else "ADMIN CREATED"
59 ret['changes'][username] = status
60 ret['comment'] = 'User %s %s' % (username, status.lower())
61 result = True
62 else:
63 status = 'FAILED'
64 logger.error("Jenkins user API call failure: %s",
65 call_result["msg"])
66 ret['comment'] = 'Jenkins user API call failure: %s' % (call_result[
67 "msg"])
68 else:
69 status = "EXISTS"
Jakub Josef3de91af2016-12-08 17:03:33 +010070 ret['comment'] = 'User %s %s' % (username, status.lower())
71 result = True
Jakub Josef3de91af2016-12-08 17:03:33 +010072 ret['result'] = None if test else result
73 return ret