Refactor smtp state
Closes-PROD: https://mirantis.jira.com/browse/PROD-21895
Change-Id: Idf4e8447760b144fbb784e34bdf7dfe0a6cf6579
diff --git a/_states/jenkins_smtp.py b/_states/jenkins_smtp.py
index 45f0244..687f254 100644
--- a/_states/jenkins_smtp.py
+++ b/_states/jenkins_smtp.py
@@ -1,51 +1,8 @@
import logging
+import json
logger = logging.getLogger(__name__)
-set_smtp_groovy = """\
-def result = ""
-for(desc in [Jenkins.getInstance().getDescriptor("hudson.plugins.emailext.ExtendedEmailPublisher"),Jenkins.getInstance().getDescriptor("hudson.tasks.Mailer")]){
- if(desc.getSmtpServer().equals("${host}") &&
- ((desc instanceof hudson.plugins.emailext.ExtendedEmailPublisherDescriptor && desc.getSmtpAuthUsername().equals("${username}")) ||
- (desc instanceof hudson.tasks.Mailer$DescriptorImpl && desc.getSmtpAuthUserName().equals("${username}"))) &&
- desc.getSmtpAuthPassword().toString().equals("${password}") &&
- desc.getSmtpPort().equals("${port}") &&
- desc.getUseSsl() == ${ssl} &&
- desc.getCharset().equals("${charset}") &&
- (!${reply_to_exists} || desc.getReplyAddress().equals("${reply_to}"))){
- result = "EXISTS"
- }else{
- desc.setSmtpAuth("${username}", "${password}")
- desc.setUseSsl(${ssl})
- if(desc instanceof hudson.plugins.emailext.ExtendedEmailPublisherDescriptor){
- desc.setSmtpServer("${host}")
- }else{
- desc.setSmtpHost("${host}")
- }
- desc.setSmtpPort("${port}")
- desc.setCharset("${charset}")
- if(${reply_to_exists}){
- desc.setReplyToAddress("${reply_to}")
- }
- desc.save()
- result = "SUCCESS"
- }
-}
-print(result)
-""" # noqa
-
-set_admin_email_groovy = """
-def jenkinsLocationConfiguration = JenkinsLocationConfiguration.get()
-if(jenkinsLocationConfiguration.getAdminAddress().equals("${email}")){
- print("EXISTS")
-}else{
- jenkinsLocationConfiguration.setAdminAddress("${email}")
- jenkinsLocationConfiguration.save()
- print("SUCCESS")
-}
-""" # noqa
-
-
def __virtual__():
'''
Only load if jenkins_common module exist.
@@ -73,42 +30,25 @@
:param charset: SMTP charset (optional, default UTF-8)
:returns: salt-specified state dict
"""
- test = __opts__['test'] # noqa
- ret = {
- 'name': name,
- 'changes': {},
- 'result': False,
- 'comment': '',
- }
- result = False
- if test:
- status = "SUCCESS"
- ret['changes'][name] = status
- ret['comment'] = 'Jenkins SMTP config %s %s' % (name, status.lower())
- else:
- call_result = __salt__['jenkins_common.call_groovy_script'](
- set_smtp_groovy, {"username": username, "password": password, "host": host,
- "reply_to_exists": "true" if reply_to else "false",
- "reply_to": reply_to,
- "port": port if port else 25,
- "ssl": "true" if ssl else "false",
- "charset": charset if charset else "UTF-8"})
- if call_result["code"] == 200 and call_result["msg"] in [
- "SUCCESS", "EXISTS"]:
- status = call_result["msg"]
- if status == "SUCCESS":
- ret['changes'][name] = status
- ret['comment'] = 'Jenkins smtp config %s %s' % (
- name, status.lower())
- result = True
- else:
- status = 'FAILED'
- logger.error(
- "Jenkins smtp API call failure: %s", call_result["msg"])
- ret['comment'] = 'Jenkins smtp API call failure: %s' % (call_result[
- "msg"])
- ret['result'] = None if test else result
- return ret
+
+ template = __salt__['jenkins_common.load_template'](
+ 'salt://jenkins/files/groovy/smtp.template',
+ __env__)
+
+ return __salt__['jenkins_common.api_call'](name, template,
+ ['CHANGED', 'EXISTS'],
+ {'params': json.dumps({
+ 'username': username,
+ 'password': password,
+ 'host': host,
+ 'useReplyTo': True if reply_to else False,
+ 'replyTo': reply_to,
+ 'port': port if port else 25,
+ 'ssl': True if ssl else False,
+ 'charset': charset if charset else 'UTF-8'
+ })
+ },
+ 'SMTP config')
def admin_email(name, email):
@@ -118,35 +58,12 @@
:param name: jenkins admin email
:returns: salt-specified state dict
"""
- test = __opts__['test'] # noqa
- ret = {
- 'name': name,
- 'changes': {},
- 'result': False,
- 'comment': '',
- }
- result = False
- if test:
- status = "SUCCESS"
- ret['changes'][name] = status
- ret['comment'] = 'Jenkins admin email config %s %s' % (
- name, status.lower())
- else:
- call_result = __salt__['jenkins_common.call_groovy_script'](
- set_admin_email_groovy, {"email": email})
- if call_result["code"] == 200 and call_result["msg"] in [
- "SUCCESS", "EXISTS"]:
- status = call_result["msg"]
- if status == "SUCCESS":
- ret['changes'][name] = status
- ret['comment'] = 'Jenkins admin email config %s %s' % (
- name, status.lower())
- result = True
- else:
- status = 'FAILED'
- logger.error(
- "Jenkins admin email API call failure: %s", call_result["msg"])
- ret['comment'] = 'Jenkins admin email API call failure: %s' % (call_result[
- "msg"])
- ret['result'] = None if test else result
- return ret
+
+ template = __salt__['jenkins_common.load_template'](
+ 'salt://jenkins/files/groovy/admin_email.template',
+ __env__)
+
+ return __salt__['jenkins_common.api_call'](name, template,
+ ['CHANGED', 'EXISTS'],
+ {'email': email},
+ 'Admin email config')
diff --git a/jenkins/files/groovy/admin_email.template b/jenkins/files/groovy/admin_email.template
new file mode 100644
index 0000000..4f72d1b
--- /dev/null
+++ b/jenkins/files/groovy/admin_email.template
@@ -0,0 +1,14 @@
+#!groovy
+
+def jenkinsLocationConfiguration = JenkinsLocationConfiguration.get()
+
+String emailParam = "${email}"
+
+if (jenkinsLocationConfiguration.getAdminAddress().equals(emailParam)) {
+ print("EXISTS")
+} else {
+ jenkinsLocationConfiguration.setAdminAddress(emailParam)
+ jenkinsLocationConfiguration.save()
+ print("CHANGED")
+}
+
diff --git a/jenkins/files/groovy/smtp.template b/jenkins/files/groovy/smtp.template
new file mode 100644
index 0000000..baa55f4
--- /dev/null
+++ b/jenkins/files/groovy/smtp.template
@@ -0,0 +1,65 @@
+#!groovy
+
+import jenkins.model.Jenkins
+
+class Actions {
+ Actions(out) {
+ this.out = out
+ }
+
+ def out
+ def instance = Jenkins.instance
+ Boolean changed = false
+
+ void configureMailer(params) {
+ for (mailer in [instance.getDescriptor("hudson.plugins.emailext.ExtendedEmailPublisher"),
+ instance.getDescriptor("hudson.tasks.Mailer")]) {
+ if (mailer.smtpHost != params.host) {
+ mailer.smtpHost = params.host
+ changed = true
+ }
+ if (mailer.smtpPort != params.port.toString()) {
+ mailer.smtpPort = params.port
+ changed = true
+ }
+ if (mailer.charset != params.charset) {
+ mailer.charset = params.charset
+ changed = true
+ }
+ if (mailer.useSsl != params.ssl) {
+ mailer.useSsl = params.ssl
+ changed = true
+ }
+ if (mailer.smtpAuthUsername != params.username) {
+ mailer.smtpAuthUsername = params.username
+ changed = true
+ }
+ if (mailer.smtpAuthPassword.toString() != params.password) {
+ mailer.smtpAuthPassword = hudson.util.Secret
+ .fromString(params.password)
+ changed = true
+ }
+ if (params.useReplyTo &&
+ mailer instanceof hudson.tasks.Mailer$DescriptorImpl &&
+ mailer.replyToAddress != params.replyTo) {
+ mailer.replyToAddress = params.replyTo
+ changed = true
+ }
+ }
+ }
+}
+
+
+def params = new groovy.json.JsonSlurperClassic()
+ .parseText("""${params}""")
+
+def actions = new Actions(out)
+
+actions.configureMailer(params)
+
+if (actions.changed) {
+ actions.instance.save()
+ print 'CHANGED'
+} else {
+ print 'EXISTS'
+}