Module and states code refactor
Change-Id: Ia1c468d0b55603b6274ca0d275b2720602e5319e
diff --git a/_modules/jenkins_common.py b/_modules/jenkins_common.py
index 64c5544..c7446fa 100644
--- a/_modules/jenkins_common.py
+++ b/_modules/jenkins_common.py
@@ -1,6 +1,7 @@
import logging
from salt.exceptions import SaltInvocationError
+from string import Template
try:
import bcrypt
@@ -32,7 +33,8 @@
return True
-def call_groovy_script(script, props, username=None, password=None, success_status_codes=[200]):
+def call_groovy_script(script, props, username=None,
+ password=None, success_status_codes=[200]):
"""
Common method for call Jenkins groovy script API
@@ -80,15 +82,16 @@
return ret
-def render_groovy_script(script, props):
+def render_groovy_script(script_template, props):
"""
Helper method for rendering groovy script with props
- :param script: groovy script template
+ :param script_template: groovy script template
:param props: groovy script properties
:returns: generated groovy script
"""
- return script.format(**props)
+ template = Template(script_template)
+ return template.safe_substitute(props)
def get_api_crumb(jenkins_url=None, jenkins_user=None, jenkins_password=None):
diff --git a/_states/jenkins_approval.py b/_states/jenkins_approval.py
index e4b21b4..2764745 100644
--- a/_states/jenkins_approval.py
+++ b/_states/jenkins_approval.py
@@ -1,51 +1,52 @@
import logging
+
logger = logging.getLogger(__name__)
approve_signature_groovy = """\
import org.jenkinsci.plugins.scriptsecurity.scripts.ScriptApproval
import org.jenkinsci.plugins.scriptsecurity.scripts.languages.GroovyLanguage
import org.jenkinsci.plugins.scriptsecurity.scripts.ApprovalContext
-def signature = '{signature}'
+def signature = '${signature}'
def scriptApproval = ScriptApproval.get()
def approvedSignatures = Arrays.asList(scriptApproval.approvedSignatures)
-if(approvedSignatures.contains(signature)){{
+if(approvedSignatures.contains(signature)){
print("EXISTS")
-}}else{{
- try{{
+}else{
+ try{
scriptApproval.pendingSignatures.add(new ScriptApproval.PendingSignature(signature, false, ApprovalContext.create()))
scriptApproval.approveSignature(signature)
- if(Arrays.asList(scriptApproval.approvedSignatures).contains(signature)){{
+ if(Arrays.asList(scriptApproval.approvedSignatures).contains(signature)){
print("SUCCESS")
- }}else{{
+ }else{
print("FAILED")
- }}
- }}catch(e){{
+ }
+ }catch(e){
print(e)
- }}
-}}
-""" # noqa
+ }
+}
+""" # noqa
deny_signature_groovy = """\
import org.jenkinsci.plugins.scriptsecurity.scripts.ScriptApproval
import org.jenkinsci.plugins.scriptsecurity.scripts.languages.GroovyLanguage
import org.jenkinsci.plugins.scriptsecurity.scripts.ApprovalContext
-def signature = '{signature}'
+def signature = '${signature}'
def scriptApproval = ScriptApproval.get()
def approvedSignatures = Arrays.asList(scriptApproval.approvedSignatures)
-if(approvedSignatures.contains(signature)){{
- try{{
+if(approvedSignatures.contains(signature)){
+ try{
scriptApproval.denySignature(signature)
- if(!scriptApproval.approvedSignatures.contains(signature)){{
+ if(!scriptApproval.approvedSignatures.contains(signature)){
print("SUCCESS")
- }}else{{
+ }else{
print("FAILED")
- }}
- }}catch(e){{
+ }
+ }catch(e){
print(e)
- }}
-}}else{{
+ }
+}else{
print("NOT PRESENT")
-}}
+}
"""
@@ -81,22 +82,25 @@
if test:
status = "SUCCESS"
ret['changes'][name] = status
- ret['comment'] = 'Jenkins script approval config %s %s' % (name, status.lower())
+ ret['comment'] = 'Jenkins script approval config %s %s' % (
+ name, status.lower())
else:
call_result = __salt__['jenkins_common.call_groovy_script'](
- approve_signature_groovy, {"signature":name})
- if call_result["code"] == 200 and call_result["msg"] in ["SUCCESS", "EXISTS"]:
+ approve_signature_groovy, {"signature": name})
+ 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 script approval config %s %s' % (name, status.lower())
+ ret['comment'] = 'Jenkins script approval config %s %s' % (
+ name, status.lower())
result = True
else:
status = 'FAILED'
logger.error(
"Jenkins script approval API call failure: %s", call_result["msg"])
ret['comment'] = 'Jenkins script approval API call failure: %s' % (call_result[
- "msg"])
+ "msg"])
ret['result'] = None if test else result
return ret
@@ -119,21 +123,24 @@
if test:
status = "SUCCESS"
ret['changes'][name] = status
- ret['comment'] = 'Jenkins script approval config %s %s' % (name, status.lower())
+ ret['comment'] = 'Jenkins script approval config %s %s' % (
+ name, status.lower())
else:
call_result = __salt__['jenkins_common.call_groovy_script'](
- deny_signature_groovy, {"signature":name})
- if call_result["code"] == 200 and call_result["msg"] in ["SUCCESS", "NOT PRESENT"]:
+ deny_signature_groovy, {"signature": name})
+ if call_result["code"] == 200 and call_result["msg"] in [
+ "SUCCESS", "NOT PRESENT"]:
status = call_result["msg"]
if status == "SUCCESS":
ret['changes'][name] = status
- ret['comment'] = 'Jenkins script approval config %s %s' % (name, status.lower())
+ ret['comment'] = 'Jenkins script approval config %s %s' % (
+ name, status.lower())
result = True
else:
status = 'FAILED'
logger.error(
"Jenkins script approval API call failure: %s", call_result["msg"])
ret['comment'] = 'Jenkins script approval lib API call failure: %s' % (call_result[
- "msg"])
+ "msg"])
ret['result'] = None if test else result
return ret
diff --git a/_states/jenkins_artifactory.py b/_states/jenkins_artifactory.py
index 38ce6c2..daccc2e 100644
--- a/_states/jenkins_artifactory.py
+++ b/_states/jenkins_artifactory.py
@@ -1,4 +1,5 @@
import logging
+
logger = logging.getLogger(__name__)
add_artifactory_groovy = u"""\
@@ -8,42 +9,42 @@
def inst = Jenkins.getInstance()
def desc = inst.getDescriptor("org.jfrog.hudson.ArtifactoryBuilder")
// empty artifactory servers is not empty list but null, but find can be called on null
-def server = desc.getArtifactoryServers().find{{it -> it.name.equals("{name}")}}
+def server = desc.getArtifactoryServers().find{it -> it.name.equals("${name}")}
if(server &&
- server.getName().equals("{name}") &&
- server.getUrl().equals("{serverUrl}") &&
- (server.getDeployerCredentialsConfig() == null || server.getDeployerCredentialsConfig().getCredentialsId().equals("{credentialsId}")) &&
- (server.getResolverCredentialsConfig() == null || server.getResolverCredentialsConfig().getCredentialsId().equals("{credentialsId}"))){{
+ server.getName().equals("${name}") &&
+ server.getUrl().equals("${serverUrl}") &&
+ (server.getDeployerCredentialsConfig() == null || server.getDeployerCredentialsConfig().getCredentialsId().equals("${credentialsId}")) &&
+ (server.getResolverCredentialsConfig() == null || server.getResolverCredentialsConfig().getCredentialsId().equals("${credentialsId}"))){
print("EXISTS")
-}}else{{
+}else{
// we must care about null here
- if(desc.getArtifactoryServers() != null && !desc.getArtifactoryServers().isEmpty()){{
- desc.getArtifactoryServers().removeIf{{it -> it.name.equals("{name}")}}
- }}else{{
+ if(desc.getArtifactoryServers() != null && !desc.getArtifactoryServers().isEmpty()){
+ desc.getArtifactoryServers().removeIf{it -> it.name.equals("${name}")}
+ }else{
desc.setArtifactoryServers([])
- }}
+ }
def newServer = new ArtifactoryServer(
- "{name}",
- "{serverUrl}",
- new CredentialsConfig("", "", "{credentialsId}"),
- new CredentialsConfig("", "", "{credentialsId}"),
+ "${name}",
+ "${serverUrl}",
+ new CredentialsConfig("", "", "${credentialsId}"),
+ new CredentialsConfig("", "", "${credentialsId}"),
300,
false,
null)
desc.getArtifactoryServers().add(newServer)
desc.save()
print("ADDED/CHANGED")
-}}
+}
""" # noqa
delete_artifactory_groovy = u"""\
def inst = Jenkins.getInstance()
def desc = inst.getDescriptor("org.jfrog.hudson.ArtifactoryBuilder")
-if(desc.getArtifactoryServers().removeIf{{it -> it.name.equals("{name}")}}){{
+if(desc.getArtifactoryServers().removeIf{it -> it.name.equals("${name}")}){
print("REMOVED")
-}}else{{
+}else{
print("NOT PRESENT")
-}}
+}
""" # noqa
@@ -68,7 +69,8 @@
:param credential_id: artifactory server credential id
:returns: salt-specified state dict
"""
- return _plugin_call(name, url, credential_id, add_artifactory_groovy, ["ADDED/CHANGED", "EXISTS"], **kwargs)
+ return _plugin_call(name, url, credential_id, add_artifactory_groovy, [
+ "ADDED/CHANGED", "EXISTS"], **kwargs)
def absent(name, **kwargs):
@@ -78,7 +80,8 @@
:param name: artifactory server name
:returns: salt-specified state dict
"""
- return _plugin_call(name, None, None, delete_artifactory_groovy, ["REMOVED", "NOT PRESENT"], **kwargs)
+ return _plugin_call(name, None, None, delete_artifactory_groovy, [
+ "REMOVED", "NOT PRESENT"], **kwargs)
def _plugin_call(name, url, credentialsId, template, success_msgs, **kwargs):
diff --git a/_states/jenkins_credential.py b/_states/jenkins_credential.py
index b2470fc..0a6287a 100644
--- a/_states/jenkins_credential.py
+++ b/_states/jenkins_credential.py
@@ -1,4 +1,5 @@
import logging
+
logger = logging.getLogger(__name__)
create_credential_groovy = u"""\
@@ -9,48 +10,48 @@
com.cloudbees.plugins.credentials.common.StandardUsernameCredentials.class,
Jenkins.instance
)
-def key = \"\"\"{key}
+def key = \"\"\"${key}
\"\"\"
-def result = creds.find{{
+def result = creds.find{
(it instanceof com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl &&
- it.username == "{username}" &&
- it.id == "{name}" &&
- it.description == "{desc}" &&
- it.password.toString() == "{password}") ||
+ it.username == "${username}" &&
+ it.id == "${name}" &&
+ it.description == "${desc}" &&
+ it.password.toString() == "${password}") ||
(it instanceof com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey &&
- it.username == "{username}" &&
- it.id == "{name}" &&
- ("{password}" == "" || it.passphrase.toString() == "{password}") &&
- it.description == "{desc}" &&
+ it.username == "${username}" &&
+ it.id == "${name}" &&
+ ("${password}" == "" || it.passphrase.toString() == "${password}") &&
+ it.description == "${desc}" &&
it.privateKeySource.privateKey.equals(key.trim()))
-}}
+}
-if(result){{
+if(result){
print("EXISTS")
-}}else{{
+}else{
domain = Domain.global()
store = Jenkins.instance.getExtensionList(
'com.cloudbees.plugins.credentials.SystemCredentialsProvider'
)[0].getStore()
- credentials_new = new {clazz}(
+ credentials_new = new ${clazz}(
{params}
)
// remove credentails with same if before created new one, if exists
def existingCreds = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(
com.cloudbees.plugins.credentials.common.StandardUsernameCredentials.class,
- Jenkins.instance).find{{it -> it.id.equals("{name}")}}
- if(existingCreds){{
+ Jenkins.instance).find{it -> it.id.equals("${name}")}
+ if(existingCreds){
store.removeCredentials(domain, existingCreds)
- }}
+ }
ret = store.addCredentials(domain, credentials_new)
- if (ret) {{
+ if (ret) {
print("CREATED");
- }} else {{
+ } else {
print("FAILED");
- }}
-}}
+ }
+}
""" # noqa
@@ -103,7 +104,8 @@
call_result = __salt__['jenkins_common.call_groovy_script'](
create_credential_groovy, {"name": name, "username": username, "password": password if password else "", "clazz": clazz, "params": params, "key": key if key else "", "desc": desc if desc else ""})
- if call_result["code"] == 200 and call_result["msg"] in ["CREATED", "EXISTS"]:
+ if call_result["code"] == 200 and call_result["msg"] in [
+ "CREATED", "EXISTS"]:
status = call_result["msg"]
if call_result["msg"] == "CREATED":
ret['changes'][name] = status
diff --git a/_states/jenkins_job.py b/_states/jenkins_job.py
index 6f72d9d..dccac86 100644
--- a/_states/jenkins_job.py
+++ b/_states/jenkins_job.py
@@ -15,10 +15,10 @@
# Jenkins
try:
- import jenkins
- HAS_JENKINS = True
+ import jenkins
+ HAS_JENKINS = True
except ImportError:
- HAS_JENKINS = False
+ HAS_JENKINS = False
log = logging.getLogger(__name__)
@@ -27,7 +27,12 @@
'''
Only load if jenkins_common module exist.
'''
- if HAS_JENKINS and 'jenkins_common.call_groovy_script' not in __salt__:
+ if not HAS_JENKINS:
+ return (
+ False,
+ 'The jenkins_job state module cannot be loaded: '
+ 'python Jenkins API client could not be imported')
+ if 'jenkins_common.call_groovy_script' not in __salt__:
return (
False,
'The jenkins_job state module cannot be loaded: '
@@ -71,7 +76,6 @@
else:
raise e
-
if _job_exists:
buf = six.moves.StringIO(_current_job_config)
oldXMLstring = buf.read()
@@ -151,7 +155,7 @@
'changes': {},
'comment': "Cleanup not necessary"}
list_jobs_groovy = """\
- print(Jenkins.instance.items.collect{{it -> it.name}})
+ print(Jenkins.instance.items.collect{it -> it.name})
"""
deleted_jobs = []
if test:
@@ -159,7 +163,8 @@
ret['changes'][name] = status
ret['comment'] = 'Jobs %s' % status.lower()
else:
- call_result = __salt__['jenkins_common.call_groovy_script'](list_jobs_groovy,{})
+ call_result = __salt__['jenkins_common.call_groovy_script'](
+ list_jobs_groovy, {})
if call_result["code"] == 200:
existing_jobs = call_result["msg"]
if existing_jobs:
diff --git a/_states/jenkins_lib.py b/_states/jenkins_lib.py
index 88f1a47..46970f5 100644
--- a/_states/jenkins_lib.py
+++ b/_states/jenkins_lib.py
@@ -1,4 +1,5 @@
import logging
+
logger = logging.getLogger(__name__)
config_global_libs_groovy = """\
@@ -7,47 +8,47 @@
import jenkins.plugins.git.GitSCMSource;
def globalLibsDesc = Jenkins.getInstance().getDescriptor("org.jenkinsci.plugins.workflow.libs.GlobalLibraries")
-def existingLib = globalLibsDesc.get().getLibraries().find{{
+def existingLib = globalLibsDesc.get().getLibraries().find{
(!it.retriever.class.name.equals("org.jenkinsci.plugins.workflow.libs.SCMSourceRetriever") ||
- it.retriever.scm.remote.equals("{url}") &&
- it.retriever.scm.credentialsId.equals("{credential_id}")) &&
- it.name.equals("{lib_name}") &&
- it.defaultVersion.equals("{branch}") &&
+ it.retriever.scm.remote.equals("${url}") &&
+ it.retriever.scm.credentialsId.equals("${credential_id}")) &&
+ it.name.equals("${lib_name}") &&
+ it.defaultVersion.equals("${branch}") &&
it.implicit == true
-}}
-if(existingLib){{
+}
+if(existingLib){
print("EXISTS")
-}}else{{
+}else{
SCMSourceRetriever retriever = new SCMSourceRetriever(new GitSCMSource(
- "{lib_name}",
- "{url}",
- "{credential_id}",
+ "${lib_name}",
+ "${url}",
+ "${credential_id}",
"*",
"",
false))
- LibraryConfiguration library = new LibraryConfiguration("{lib_name}", retriever)
- library.setDefaultVersion("{branch}")
+ LibraryConfiguration library = new LibraryConfiguration("${lib_name}", retriever)
+ library.setDefaultVersion("${branch}")
library.setImplicit({implicit})
- if(globalLibsDesc.get().getLibraries().isEmpty()){{
+ if(globalLibsDesc.get().getLibraries().isEmpty()){
globalLibsDesc.get().setLibraries([library])
- }}else{{
- globalLibsDesc.get().getLibraries().removeIf{{ it.name.equals("{lib_name}")}}
+ }else{
+ globalLibsDesc.get().getLibraries().removeIf{ it.name.equals("${lib_name}")}
globalLibsDesc.get().getLibraries().add(library)
- }}
+ }
globalLibsDesc.save()
print("SUCCESS")
-}}
-""" # noqa
+}
+""" # noqa
remove_global_libs_groovy = """\
def globalLibsDesc = Jenkins.getInstance().getDescriptor("org.jenkinsci.plugins.workflow.libs.GlobalLibraries")
-def existingLib = globalLibsDesc.get().getLibraries().removeIf{{it.name.equals("{lib_name}")}}
-if(existingLib){{
+def existingLib = globalLibsDesc.get().getLibraries().removeIf{it.name.equals("${lib_name}")}
+if(existingLib){
globalLibsDesc.save()
print("DELETED")
-}}else{{
+}else{
print("NOT PRESENT")
-}}
+}
"""
@@ -63,7 +64,8 @@
return True
-def present(name, url, branch="master", credential_id="", implicit=True, **kwargs):
+def present(name, url, branch="master",
+ credential_id="", implicit=True, **kwargs):
"""
Jenkins Global pipeline library present state method
@@ -85,27 +87,30 @@
if test:
status = "SUCCESS"
ret['changes'][name] = status
- ret['comment'] = 'Jenkins pipeline lib config %s %s' % (name, status.lower())
+ ret['comment'] = 'Jenkins pipeline lib config %s %s' % (
+ name, status.lower())
else:
call_result = __salt__['jenkins_common.call_groovy_script'](
- config_global_libs_groovy, {"lib_name":name,
- "url": url,
- "branch": branch,
- "credential_id": credential_id if credential_id else "",
- "implicit": "true" if implicit else "false"
- })
- if call_result["code"] == 200 and call_result["msg"] in ["SUCCESS", "EXISTS"]:
+ config_global_libs_groovy, {"lib_name": name,
+ "url": url,
+ "branch": branch,
+ "credential_id": credential_id if credential_id else "",
+ "implicit": "true" if implicit else "false"
+ })
+ 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 pipeline lib config %s %s' % (name, status.lower())
+ ret['comment'] = 'Jenkins pipeline lib config %s %s' % (
+ name, status.lower())
result = True
else:
status = 'FAILED'
logger.error(
"Jenkins pipeline lib API call failure: %s", call_result["msg"])
ret['comment'] = 'Jenkins pipeline lib API call failure: %s' % (call_result[
- "msg"])
+ "msg"])
ret['result'] = None if test else result
return ret
@@ -128,21 +133,24 @@
if test:
status = "SUCCESS"
ret['changes'][name] = status
- ret['comment'] = 'Jenkins pipeline lib config %s %s' % (name, status.lower())
+ ret['comment'] = 'Jenkins pipeline lib config %s %s' % (
+ name, status.lower())
else:
call_result = __salt__['jenkins_common.call_groovy_script'](
- remove_global_libs_groovy, {"lib_name":name})
- if call_result["code"] == 200 and call_result["msg"] in ["DELETED", "NOT PRESENT"]:
+ remove_global_libs_groovy, {"lib_name": name})
+ if call_result["code"] == 200 and call_result["msg"] in [
+ "DELETED", "NOT PRESENT"]:
status = call_result["msg"]
if status == "DELETED":
ret['changes'][name] = status
- ret['comment'] = 'Jenkins pipeline lib config %s %s' % (name, status.lower())
+ ret['comment'] = 'Jenkins pipeline lib config %s %s' % (
+ name, status.lower())
result = True
else:
status = 'FAILED'
logger.error(
"Jenkins pipeline lib API call failure: %s", call_result["msg"])
ret['comment'] = 'Jenkins pipeline lib API call failure: %s' % (call_result[
- "msg"])
+ "msg"])
ret['result'] = None if test else result
return ret
diff --git a/_states/jenkins_node.py b/_states/jenkins_node.py
index aa54efd..cb88fa8 100644
--- a/_states/jenkins_node.py
+++ b/_states/jenkins_node.py
@@ -1,6 +1,6 @@
import logging
-logger = logging.getLogger(__name__)
+logger = logging.getLogger(__name__)
create_node_groovy = u"""\
import jenkins.model.*
@@ -8,48 +8,48 @@
import hudson.slaves.*
import hudson.plugins.sshslaves.*
-def result=Jenkins.instance.slaves.find{{
+def result=Jenkins.instance.slaves.find{
it.name == '{name}' &&
it.numExecutors == {num_executors} &&
- it.nodeDescription == "{desc}" &&
- it.remoteFS == "{remote_home}" &&
- it.labelString == "{label}" &&
+ it.nodeDescription == "${desc}" &&
+ it.remoteFS == "${remote_home}" &&
+ it.labelString == "${label}" &&
it.mode == Node.Mode.{node_mode} &&
it.launcher.getClass().getName().equals({launcher}.getClass().getName()) &&
- it.retentionStrategy.getClass().getName().equals(new hudson.slaves.RetentionStrategy.{ret_strategy}().getClass().getName())}}
-if(result){{
+ it.retentionStrategy.getClass().getName().equals(new hudson.slaves.RetentionStrategy.${ret_strategy}().getClass().getName())}
+if(result){
print("EXISTS")
-}}else{{
+}else{
Slave slave = new DumbSlave(
- "{name}",
- "{desc}",
- "{remote_home}",
- "{num_executors}",
- Node.Mode.{node_mode},
- "{label}",
- {launcher},
- new RetentionStrategy.{ret_strategy}(),
+ "${name}",
+ "${desc}",
+ "${remote_home}",
+ "${num_executors}",
+ Node.Mode.${node_mode},
+ "${label}",
+ ${launcher},
+ new RetentionStrategy.${ret_strategy}(),
new LinkedList())
Jenkins.instance.addNode(slave)
print("CREATED")
-}}
+}
""" # noqa
create_lbl_groovy = u"""\
hudson = hudson.model.Hudson.instance
updated = false
-hudson.slaves.find {{ slave -> slave.nodeName.equals("{name}")
- if({append}){{
- slave.labelString = slave.labelString + " " + "{lbl_text}"
- }}else{{
- slave.labelString = "{lbl_text}"
- }}
+hudson.slaves.find { slave -> slave.nodeName.equals("${name}")
+ if({append}){
+ slave.labelString = slave.labelString + " " + "${lbl_text}"
+ }else{
+ slave.labelString = "${lbl_text}"
+ }
updated = true
- print "{lbl_text}"
-}}
-if(!updated){{
+ print "${lbl_text}"
+}
+if(!updated){
print "FAILED"
-}}
+}
hudson.save()
""" # noqa
@@ -57,26 +57,26 @@
def instance = Jenkins.instance
def changed = false
-if(Jenkins.instance.numExecutors != {num_executors}){{
- Jenkins.instance.setNumExecutors({num_executors})
+if(Jenkins.instance.numExecutors != ${num_executors}){
+ Jenkins.instance.setNumExecutors(${num_executors})
changed = true
-}}
+}
-if(!Jenkins.instance.mode.name.equals(new String("{node_mode}").toUpperCase())){{
- Jenkins.instance.setMode(Node.Mode.{node_mode})
+if(!Jenkins.instance.mode.name.equals(new String("${node_mode}").toUpperCase())){
+ Jenkins.instance.setMode(Node.Mode.${node_mode})
changed = true
-}}
+}
-if(!Jenkins.instance.labelString.equals("{labels}")){{
- Jenkins.instance.setLabelString("{labels}")
+if(!Jenkins.instance.labelString.equals("${labels}")){
+ Jenkins.instance.setLabelString("${labels}")
changed = true
-}}
-if(changed){{
+}
+if(changed){
Jenkins.instance.save()
print("CREATED")
-}}else{{
+}else{
print("EXISTS")
-}}
+}
"""
@@ -115,7 +115,8 @@
else:
call_result = __salt__['jenkins_common.call_groovy_script'](
create_lbl_groovy, {'name': name, 'lbl_text': lbl_text, 'append': "true" if append else "false"})
- if call_result["code"] == 200 and call_result["msg"].strip() == lbl_text:
+ if call_result["code"] == 200 and call_result["msg"].strip(
+ ) == lbl_text:
status = "CREATED"
ret['changes'][name] = status
ret['comment'] = 'Label %s %s ' % (name, status.lower())
@@ -130,7 +131,8 @@
return ret
-def present(name, remote_home, launcher, num_executors="1", node_mode="Normal", desc="", labels=[], ret_strategy="Always"):
+def present(name, remote_home, launcher, num_executors="1",
+ node_mode="Normal", desc="", labels=[], ret_strategy="Always"):
"""
Jenkins node state method
@@ -176,7 +178,8 @@
"launcher": launcher_string,
"node_mode": node_mode.upper(),
"ret_strategy": ret_strategy if ret_strategy else "Always"})
- if call_result["code"] == 200 and call_result["msg"] in ["CREATED", "EXISTS"]:
+ if call_result["code"] == 200 and call_result["msg"] in [
+ "CREATED", "EXISTS"]:
status = call_result["msg"]
if call_result["msg"] == "CREATED":
ret['changes'][name] = status
@@ -217,7 +220,8 @@
else:
call_result = __salt__['jenkins_common.call_groovy_script'](
configure_master_groovy, {'num_executors': num_executors, 'labels': " ".join(labels), 'node_mode': node_mode.upper()})
- if call_result["code"] == 200 and call_result["msg"] in ["CREATED", "EXISTS"]:
+ if call_result["code"] == 200 and call_result["msg"] in [
+ "CREATED", "EXISTS"]:
status = call_result["msg"]
if status == "CREATED":
ret['changes'][name] = status
diff --git a/_states/jenkins_plugin.py b/_states/jenkins_plugin.py
index cb54633..d9fe8e9 100644
--- a/_states/jenkins_plugin.py
+++ b/_states/jenkins_plugin.py
@@ -1,4 +1,5 @@
import logging
+
logger = logging.getLogger(__name__)
install_plugin_groovy = """\
@@ -8,43 +9,43 @@
def logger = Logger.getLogger("")
def installed = false
def exists = false
-def pluginName="{plugin}"
+def pluginName="${plugin}"
def instance = Jenkins.getInstance()
def pm = instance.getPluginManager()
def uc = instance.getUpdateCenter()
-def needUpdateSites(maxOldInSec = 1800){{
+def needUpdateSites(maxOldInSec = 1800){
long oldestTs = 0
- for (UpdateSite s : Jenkins.instance.updateCenter.siteList) {{
- if(oldestTs == 0 || s.getDataTimestamp()<oldestTs){{
+ for (UpdateSite s : Jenkins.instance.updateCenter.siteList) {
+ if(oldestTs == 0 || s.getDataTimestamp()<oldestTs){
oldestTs = s.getDataTimestamp()
- }}
- }}
+ }
+ }
return (System.currentTimeMillis()-oldestTs)/1000 > maxOldInSec
-}}
+}
-if (!pm.getPlugin(pluginName)) {{
- if(needUpdateSites()) {{
+if (!pm.getPlugin(pluginName)) {
+ if(needUpdateSites()) {
uc.updateAllSites()
- }}
+ }
def plugin = uc.getPlugin(pluginName)
- if (plugin) {{
+ if (plugin) {
plugin.deploy()
installed = true
- }}
-}}else{{
+ }
+}else{
exists = true
print("EXISTS")
-}}
-if (installed) {{
+}
+if (installed) {
instance.save()
- if({restart}){{
+ if({restart}){
instance.doSafeRestart()
- }}
+ }
print("INSTALLED")
-}}else if(!exists){{
+}else if(!exists){
print("FAILED")
-}}
-""" # noqa
+}
+""" # noqa
remove_plugin_groovy = """
import jenkins.model.*
@@ -54,27 +55,27 @@
def installed = false
def initialized = false
-def pluginName="{plugin}"
+def pluginName="${plugin}"
def instance = Jenkins.getInstance()
def pm = instance.getPluginManager()
def actPlugin = pm.getPlugin(pluginName)
-if (!actPlugin) {{
+if (!actPlugin) {
def pluginToInstall = Jenkins.instance.updateCenter.getPlugin(pluginName)
- if(!pluginToInstall){{
+ if(!pluginToInstall){
print("FAILED")
- }}else{{
+ }else{
print("NOT PRESENT")
- }}
-}} else {{
+ }
+} else {
actPlugin.disable()
actPlugin.archive.delete()
- if({restart}){{
+ if({restart}){
instance.doSafeRestart()
- }}
+ }
print("REMOVED")
-}}
-""" # noqa
+}
+""" # noqa
def __virtual__():
@@ -97,7 +98,8 @@
:param restart: do you want to restart jenkins after plugin install?
:returns: salt-specified state dict
"""
- return _plugin_call(name, restart, install_plugin_groovy, ["INSTALLED", "EXISTS"])
+ return _plugin_call(name, restart, install_plugin_groovy, [
+ "INSTALLED", "EXISTS"])
def absent(name, restart=False):
@@ -108,7 +110,8 @@
:param restart: do you want to restart jenkins after plugin remove?
:returns: salt-specified state dict
"""
- return _plugin_call(name, restart, remove_plugin_groovy, ["REMOVED", "NOT PRESENT"])
+ return _plugin_call(name, restart, remove_plugin_groovy, [
+ "REMOVED", "NOT PRESENT"])
def _plugin_call(name, restart, template, success_msgs):
@@ -131,13 +134,14 @@
status = call_result["msg"]
if status == success_msgs[0]:
ret['changes'][name] = status
- ret['comment'] = 'Jenkins plugin %s %s%s' % (name, status.lower(), ", jenkins restarted" if status == success_msgs[0] and restart else "")
+ ret['comment'] = 'Jenkins plugin %s %s%s' % (name, status.lower(
+ ), ", jenkins restarted" if status == success_msgs[0] and restart else "")
result = True
else:
status = 'FAILED'
logger.error(
"Jenkins plugin API call failure: %s", call_result["msg"])
ret['comment'] = 'Jenkins plugin API call failure: %s' % (call_result[
- "msg"])
+ "msg"])
ret['result'] = None if test else result
return ret
diff --git a/_states/jenkins_security.py b/_states/jenkins_security.py
index 6442e2b..98e8a70 100644
--- a/_states/jenkins_security.py
+++ b/_states/jenkins_security.py
@@ -1,4 +1,5 @@
import logging
+
logger = logging.getLogger(__name__)
set_ldap_groovy = """\
@@ -6,24 +7,24 @@
import hudson.security.*
import org.jenkinsci.plugins.*
-def server = '{server}'
-def rootDN = '{rootDN}'
-def userSearchBase = '{userSearchBase}'
-def userSearch = '{userSearch}'
-def groupSearchBase = '{groupSearchBase}'
-def managerDN = '{managerDN}'
-def managerPassword = '{managerPassword}'
+def server = '${server}'
+def rootDN = '${rootDN}'
+def userSearchBase = '${userSearchBase}'
+def userSearch = '${userSearch}'
+def groupSearchBase = '${groupSearchBase}'
+def managerDN = '${managerDN}'
+def managerPassword = '${managerPassword}'
boolean inhibitInferRootDN = {inhibitInferRootDN}
-try{{
+try{
ldapRealm = Class.forName("hudson.security.LDAPSecurityRealm").getConstructor(String.class, String.class, String.class, String.class, String.class, String.class, String.class, Boolean.TYPE)
.newInstance(server, rootDN, userSearchBase, userSearch, groupSearchBase, managerDN, managerPassword, inhibitInferRootDN)
Jenkins.instance.setSecurityRealm(ldapRealm)
Jenkins.instance.save()
print("SUCCESS")
-}}catch(ClassNotFoundException e){{
+}catch(ClassNotFoundException e){
print("Cannot instantiate LDAPSecurityRealm, maybe ldap plugin not installed")
-}}
+}
""" # noqa
set_matrix_groovy = """\
@@ -32,15 +33,15 @@
import com.cloudbees.plugins.credentials.*
def instance = Jenkins.getInstance()
-try{{
-def strategy = Class.forName("hudson.security.{matrix_class}").newInstance()
-{strategies}
+try{
+def strategy = Class.forName("hudson.security.${matrix_class}").newInstance()
+${strategies}
instance.setAuthorizationStrategy(strategy)
instance.save()
print("SUCCESS")
-}}catch(ClassNotFoundException e){{
- print("Cannot instantiate {matrix_class}, maybe auth-matrix plugin not installed")
-}}
+}catch(ClassNotFoundException e){
+ print("Cannot instantiate ${matrix_class}, maybe auth-matrix plugin not installed")
+}
""" # noqa
@@ -56,7 +57,8 @@
return True
-def ldap(name, server, root_dn, user_search_base, manager_dn, manager_password, user_search="", group_search_base="", inhibit_infer_root_dn=False):
+def ldap(name, server, root_dn, user_search_base, manager_dn, manager_password,
+ user_search="", group_search_base="", inhibit_infer_root_dn=False):
"""
Jenkins ldap state method
@@ -93,7 +95,7 @@
"managerDN": manager_dn if manager_dn else "",
"managerPassword": manager_password if manager_password else "",
"userSearch": user_search if user_search else "",
- "groupSearchBase": group_search_base if group_search_base else "",
+ "groupSearchBase": group_search_base if group_search_base else "",
"inhibitInferRootDN": "true" if inhibit_infer_root_dn else "false"})
if call_result["code"] == 200 and call_result["msg"] == "SUCCESS":
status = call_result["msg"]
@@ -155,7 +157,8 @@
def _build_strategies(permissions):
strategies_str = ""
- for strategy in _to_strategies_list("strategy.add({},\"{}\")", _to_one_dict(permissions, "")):
+ for strategy in _to_strategies_list(
+ "strategy.add({},\"{}\")", _to_one_dict(permissions, "")):
strategies_str += "{}\n".format(strategy)
return strategies_str
diff --git a/_states/jenkins_slack.py b/_states/jenkins_slack.py
index cbe52ec..d0d5636 100644
--- a/_states/jenkins_slack.py
+++ b/_states/jenkins_slack.py
@@ -1,29 +1,30 @@
import logging
+
logger = logging.getLogger(__name__)
config_slack_groovy = """\
jenkins = jenkins.model.Jenkins.getInstance()
-try{{
+try{
slack = jenkins.getDescriptorByType(jenkins.plugins.slack.SlackNotifier.DescriptorImpl)
-if(slack.teamDomain.equals("{team_domain}") &&
- slack.token.equals("{token}") &&
- slack.tokenCredentialId.equals("{token_credential_id}") &&
- slack.room.equals("{room}") &&
- slack.sendAs.equals("{send_as}")){{
+if(slack.teamDomain.equals("${team_domain}") &&
+ slack.token.equals("${token}") &&
+ slack.tokenCredentialId.equals("${token_credential_id}") &&
+ slack.room.equals("${room}") &&
+ slack.sendAs.equals("${send_as}")){
print("EXISTS")
-}}else{{
- slack.teamDomain = "{team_domain}"
- slack.token = "{token}"
- slack.tokenCredentialId = "{token_credential_id}"
- slack.room = "{room}"
- slack.sendAs = "{send_as}"
+}else{
+ slack.teamDomain = "${team_domain}"
+ slack.token = "${token}"
+ slack.tokenCredentialId = "${token_credential_id}"
+ slack.room = "${room}"
+ slack.sendAs = "${send_as}"
slack.save()
print("SUCCESS")
-}}
-}}catch(all){{
+}
+}catch(all){
print("Cannot instantiate Jenkins Slack plugin, maybe plugin is not installed")
-}}
-""" # noqa
+}
+""" # noqa
def __virtual__():
@@ -38,7 +39,8 @@
return True
-def config(name, team_domain, token, token_credential_id="", room="", send_as=None):
+def config(name, team_domain, token,
+ token_credential_id="", room="", send_as=None):
"""
Jenkins Slack config state method
@@ -64,22 +66,24 @@
ret['comment'] = 'Jenkins Slack config %s %s' % (name, status.lower())
else:
call_result = __salt__['jenkins_common.call_groovy_script'](
- config_slack_groovy, {"team_domain":team_domain,
- "token":token,
+ config_slack_groovy, {"team_domain": team_domain,
+ "token": token,
"token_credential_id": token_credential_id if token_credential_id else "",
"room": room if room else "",
"send_as": send_as if send_as else ""})
- if call_result["code"] == 200 and call_result["msg"] in ["SUCCESS", "EXISTS"]:
+ 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 Slack config %s %s' % (name, status.lower())
+ ret['comment'] = 'Jenkins Slack config %s %s' % (
+ name, status.lower())
result = True
else:
status = 'FAILED'
logger.error(
"Jenkins slack API call failure: %s", call_result["msg"])
ret['comment'] = 'Jenkins slack API call failure: %s' % (call_result[
- "msg"])
+ "msg"])
ret['result'] = None if test else result
return ret
diff --git a/_states/jenkins_smtp.py b/_states/jenkins_smtp.py
index f27972e..b3029b7 100644
--- a/_states/jenkins_smtp.py
+++ b/_states/jenkins_smtp.py
@@ -1,48 +1,49 @@
import logging
+
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}"))){{
+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}")
- }}
+ }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
+""" # noqa
set_admin_email_groovy = """
def jenkinsLocationConfiguration = JenkinsLocationConfiguration.get()
-if(jenkinsLocationConfiguration.getAdminAddress().equals("{email}")){{
+if(jenkinsLocationConfiguration.getAdminAddress().equals("${email}")){
print("EXISTS")
-}}else{{
- jenkinsLocationConfiguration.setAdminAddress("{email}")
+}else{
+ jenkinsLocationConfiguration.setAdminAddress("${email}")
jenkinsLocationConfiguration.save()
print("SUCCESS")
-}}
-""" # noqa
+}
+""" # noqa
def __virtual__():
@@ -57,7 +58,8 @@
return True
-def config(name, host, username, password, reply_to=None, port=25, ssl=False, charset="UTF-8"):
+def config(name, host, username, password, reply_to=None,
+ port=25, ssl=False, charset="UTF-8"):
"""
Jenkins SMTP server config state method
@@ -85,24 +87,26 @@
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,
+ 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"]:
+ 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())
+ 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"])
+ "msg"])
ret['result'] = None if test else result
return ret
@@ -125,15 +129,18 @@
if test:
status = "SUCCESS"
ret['changes'][name] = status
- ret['comment'] = 'Jenkins admin email config %s %s' % (name, status.lower())
+ 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"]:
+ 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())
+ ret['comment'] = 'Jenkins admin email config %s %s' % (
+ name, status.lower())
result = True
else:
status = 'FAILED'
diff --git a/_states/jenkins_theme.py b/_states/jenkins_theme.py
index 2f0208b..c27b0a2 100644
--- a/_states/jenkins_theme.py
+++ b/_states/jenkins_theme.py
@@ -2,26 +2,27 @@
logger = logging.getLogger(__name__)
set_theme_groovy = """\
-try{{
- if(Class.forName("org.codefirst.SimpleThemeDecorator")){{
+try{
+ if(Class.forName("org.codefirst.SimpleThemeDecorator")){
def state;
- for (pd in PageDecorator.all()) {{
- if (pd instanceof org.codefirst.SimpleThemeDecorator) {{
- if(!pd.cssUrl.equals("{css_url}") || !pd.jsUrl.equals("{js_url}")){{
- pd.cssUrl = "{css_url}"
- pd.jsUrl = "{js_url}"
+ for (pd in PageDecorator.all()) {
+ if (pd instanceof org.codefirst.SimpleThemeDecorator) {
+ if(!pd.cssUrl.equals("${css_url}") || !pd.jsUrl.equals("${js_url}")){
+ pd.cssUrl = "${css_url}"
+ pd.jsUrl = "${js_url}"
state="SUCCESS"
- }}else{{
+ }else{
state="EXISTS"
- }}
- }}
- }}
+ }
+ }
+ }
print(state)
- }}
-}}catch(ClassNotFoundException e){{
+ }
+}catch(ClassNotFoundException e){
print("Cannot user SimpleThemeDecorator, maybe Simple Theme Plugin not installed")
-}}
-""" # noqa
+}
+""" # noqa
+
def __virtual__():
'''
@@ -59,17 +60,19 @@
else:
call_result = __salt__['jenkins_common.call_groovy_script'](
set_theme_groovy, {"css_url": css_url, "js_url": js_url})
- if call_result["code"] == 200 and call_result["msg"] in ["SUCCESS", "EXISTS"]:
+ 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 theme config %s %s' % (name, status.lower())
+ ret['comment'] = 'Jenkins theme config %s %s' % (
+ name, status.lower())
result = True
else:
status = 'FAILED'
logger.error(
"Jenkins theme API call failure: %s", call_result["msg"])
ret['comment'] = 'Jenkins theme API call failure: %s' % (call_result[
- "msg"])
+ "msg"])
ret['result'] = None if test else result
return ret
diff --git a/_states/jenkins_user.py b/_states/jenkins_user.py
index c2f2d9b..ed34877 100644
--- a/_states/jenkins_user.py
+++ b/_states/jenkins_user.py
@@ -1,40 +1,41 @@
import logging
+
logger = logging.getLogger(__name__)
create_admin_groovy = u"""\
import jenkins.model.*
import hudson.security.*
def instance = Jenkins.getInstance()
-if(hudson.model.User.getAll().find{{u->u.fullName.equals("{username}")}}){{
+if(hudson.model.User.getAll().find{u->u.fullName.equals("${username}")}){
print("EXISTS")
-}}else{{
+}else{
def hudsonRealm = new HudsonPrivateSecurityRealm(false)
- def result=hudsonRealm.createAccount("{username}","{password}")
+ def result=hudsonRealm.createAccount("${username}","${password}")
instance.setSecurityRealm(hudsonRealm)
def strategy = new hudson.security.FullControlOnceLoggedInAuthorizationStrategy()
strategy.setAllowAnonymousRead(false)
instance.setAuthorizationStrategy(strategy)
instance.save()
- if(result.toString().equals("{username}")){{
+ if(result.toString().equals("${username}")){
print("SUCCESS")
- }}else{{
+ }else{
print("FAILED")
- }}
-}}
+ }
+}
""" # noqa
create_user_groovy = u"""\
-if(hudson.model.User.getAll().find{{u->u.fullName.equals("{username}")}}){{
+if(hudson.model.User.getAll().find{u->u.fullName.equals("${username}")}){
print("EXISTS")
-}}else{{
- def result=jenkins.model.Jenkins.instance.securityRealm.createAccount("{username}", "{password}")
- if(result.toString().equals("{username}")){{
+}else{
+ def result=jenkins.model.Jenkins.instance.securityRealm.createAccount("${username}", "${password}")
+ if(result.toString().equals("${username}")){
print("SUCCESS")
- }}else{{
+ }else{
print("FAILED")
- }}
-}}
+ }
+}
""" # noqa
@@ -75,7 +76,8 @@
else:
call_result = __salt__['jenkins_common.call_groovy_script'](
create_admin_groovy if admin else create_user_groovy, {"username": username, "password": password})
- if call_result["code"] == 200 and call_result["msg"] in ["SUCCESS", "EXISTS"]:
+ if call_result["code"] == 200 and call_result["msg"] in [
+ "SUCCESS", "EXISTS"]:
if call_result["msg"] == "SUCCESS":
status = "CREATED" if not admin else "ADMIN CREATED"
ret['changes'][username] = status
diff --git a/_states/jenkins_view.py b/_states/jenkins_view.py
index dc941e9..e229a11 100644
--- a/_states/jenkins_view.py
+++ b/_states/jenkins_view.py
@@ -1,73 +1,75 @@
import logging
+
from json import dumps
+
logger = logging.getLogger(__name__)
add_view_groovy = """\
import java.util.stream.Collectors
import org.jenkinsci.plugins.categorizedview.CategorizedJobsView
import org.jenkinsci.plugins.categorizedview.GroupingRule
-view = Jenkins.instance.getView("{view_name}")
-if(view){{
- if(view.getClass().getName().equals("hudson.model.ListView")){{
- include_regex="{include_regex}"
- if(include_regex != "" && !view.getIncludeRegex().equals(include_regex)){{
+view = Jenkins.instance.getView("${view_name}")
+if(view){
+ if(view.getClass().getName().equals("hudson.model.ListView")){
+ include_regex="${include_regex}"
+ if(include_regex != "" && !view.getIncludeRegex().equals(include_regex)){
view.setIncludeRegex(include_regex)
print("ADDED/CHANGED")
- }}else{{
+ }else{
print("EXISTS")
- }}
- }}else if(view.getClass().getName().equals("org.jenkinsci.plugins.categorizedview.CategorizedJobsView")){{
+ }
+ }else if(view.getClass().getName().equals("org.jenkinsci.plugins.categorizedview.CategorizedJobsView")){
def jsonSlurper = new groovy.json.JsonSlurper()
- def inputCategories = jsonSlurper.parseText('{categories_string}')
- def groupRegexes = inputCategories.stream().map{{e -> e["group_regex"]}}.collect(Collectors.toList())
- def namingRules = inputCategories.stream().map{{e -> e["naming_rule"]}}.collect(Collectors.toList())
+ def inputCategories = jsonSlurper.parseText('${categories_string}')
+ def groupRegexes = inputCategories.stream().map{e -> e["group_regex"]}.collect(Collectors.toList())
+ def namingRules = inputCategories.stream().map{e -> e["naming_rule"]}.collect(Collectors.toList())
def actualCategories = view.categorizationCriteria
def equals = !actualCategories.isEmpty()
- def include_regex="{include_regex}"
- if(include_regex != "" && !view.getIncludeRegex().equals(include_regex)){{
+ def include_regex="${include_regex}"
+ if(include_regex != "" && !view.getIncludeRegex().equals(include_regex)){
view.setIncludeRegex(include_regex)
equals = false
- }}
- for(int i=0;i<actualCategories.size();i++){{
- if(!groupRegexes.contains(actualCategories[i].groupRegex) || !namingRules.contains(actualCategories[i].namingRule)){{
+ }
+ for(int i=0;i<actualCategories.size();i++){
+ if(!groupRegexes.contains(actualCategories[i].groupRegex) || !namingRules.contains(actualCategories[i].namingRule)){
equals = false
- }}
- }}
- if(!equals){{
+ }
+ }
+ if(!equals){
view.categorizationCriteria.clear()
- for(int i=0;i<inputCategories.size();i++){{
+ for(int i=0;i<inputCategories.size();i++){
view.categorizationCriteria.add(new GroupingRule(inputCategories[i].group_regex,inputCategories[i].naming_rule))
- }}
+ }
print("ADDED/CHANGED")
- }}else{{
+ }else{
print("EXISTS")
- }}
- }}else{{
+ }
+ }else{
print("EXISTS")
- }}
-}}else{{
- try{{
- {view_def}
+ }
+}else{
+ try{
+ ${view_def}
Jenkins.instance.addView(view)
print("ADDED/CHANGED")
- }}catch(Exception e){{
+ }catch(Exception e){
print("FAILED")
- }}
-}}
+ }
+}
""" # noqa
remove_view_groovy = """\
-view = Jenkins.instance.getView("{view_name}")
-if(view){{
- try{{
+view = Jenkins.instance.getView("${view_name}")
+if(view){
+ try{
Jenkins.instance.deleteView(view)
print("REMOVED")
- }}catch(Exception e){{
+ }catch(Exception e){
print("FAILED")
- }}
-}}else{{
+ }
+}else{
print("NOT PRESENT")
-}}
+}
""" # noqa
@@ -91,7 +93,8 @@
:param type: view type (default ListView)
:returns: salt-specified state dict
"""
- return _plugin_call(name, type, add_view_groovy, ["ADDED/CHANGED", "EXISTS"], **kwargs)
+ return _plugin_call(name, type, add_view_groovy, [
+ "ADDED/CHANGED", "EXISTS"], **kwargs)
def absent(name, **kwargs):
@@ -101,7 +104,8 @@
:param name: view name
:returns: salt-specified state dict
"""
- return _plugin_call(name, None, remove_view_groovy, ["REMOVED", "NOT PRESENT"], **kwargs)
+ return _plugin_call(name, None, remove_view_groovy, [
+ "REMOVED", "NOT PRESENT"], **kwargs)
def _plugin_call(name, type, template, success_msgs, **kwargs):