blob: 355eddeacd46cb87cf93ed9d7b9ec8922f3b4dad [file] [log] [blame]
Jakub Josef8e7385e2016-12-07 21:20:34 +01001import logging
2logger = logging.getLogger(__name__)
3
4create_credential_groovy = u"""\
5import jenkins.*;
6import jenkins.model.*;
7import hudson.*;
8import hudson.model.*;
9
10import com.cloudbees.plugins.credentials.domains.Domain;
11import com.cloudbees.plugins.credentials.CredentialsScope;
12
13domain = Domain.global()
14store = Jenkins.instance.getExtensionList(
15 'com.cloudbees.plugins.credentials.SystemCredentialsProvider'
16)[0].getStore()
17
18credentials_new = new {clazz}(
19 {params}
20)
21
22creds = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(
23 {clazz}.class, Jenkins.instance
24);
25updated = false;
26
27for (credentials_current in creds) {{
28 // Comparison does not compare passwords but identity.
29 if (credentials_new == credentials_current) {{
30 store.removeCredentials(domain, credentials_current);
31 ret = store.addCredentials(domain, credentials_new)
32 updated = true;
33 println("OVERWRITTEN");
34 break;
35 }}
36}}
37
38if (!updated) {{
39 ret = store.addCredentials(domain, credentials_new)
40 if (ret) {{
41 println("CREATED");
42 }} else {{
43 println("FAILED");
44 }}
45}}
46""" # noqa
47
48
49def present(name, scope, username, password=None, desc="", key=None):
50 """
51 Main jenkins credentials state method
52
53 :param name: credential name
54 :param scope: credential scope
55 :param username: username
56 :param password: password (optional)
57 :param desc: credential description (optional)
58 :param key: credential key (optional)
59 :returns: salt-specified state dict
60 """
61 test = __opts__['test'] # noqa
62 ret = {
63 'name': name,
64 'changes': {},
65 'result': False,
66 'comment': '',
67 }
68 result = False
69 if test:
70 status = 'CREATED'
71 ret['changes'][name] = status
72 ret['comment'] = 'Credentials ' + status.lower()
73 else:
74 clazz = ""
75 if key:
76 clazz = "com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey"
77 params = 'CredentialsScope.{}, "{}", "{}", "{}"'.format(scope, name, desc, key)
78 else:
79 clazz = "com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl"
80 params = 'CredentialsScope.{}, "{}", "{}", "{}", "{}"'.format(scope, name, desc, username, password)
81
82 call_result = __salt__['jenkins_common.call_groovy_script'](create_credential_groovy, {"clazz": clazz, "params":params})
83 if call_result["code"] == 200 and call_result["msg"].strip() in ["CREATED", "OVERWRITTEN"]:
84 status = call_result["msg"]
85 ret['changes'][name] = status
86 ret['comment'] = 'Credentials ' + status.lower()
87 result = True
88 else:
89 status = 'FAILED'
90 logger.error("Jenkins script API execution failure: %s", call_result["msg"])
91 ret['comment'] = 'Jenkins script API execution failure: %s' % (call_result["msg"])
92 ret['result'] = None if test else result
93 return ret