Tools to make Jenkins jobs from templates
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

4793 lines
188 KiB

# Copyright 2012 Hewlett-Packard Development Company, L.P.
# Copyright 2012 Varnish Software AS
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
Builders define actions that the Jenkins job should execute. Examples
include shell scripts or maven targets. The ``builders`` attribute in
the :ref:`Job` definition accepts a list of builders to invoke. They
may be components defined below, locally defined macros (using the top
level definition of ``builder:``, or locally defined components found
via the ``jenkins_jobs.builders`` entry point.
**Component**: builders
:Macro: builder
:Entry Point: jenkins_jobs.builders
Example::
job:
name: test_job
builders:
- shell: "make test"
"""
import logging
import sys
import xml.etree.ElementTree as XML
import six
from jenkins_jobs.errors import is_sequence
from jenkins_jobs.errors import InvalidAttributeError
from jenkins_jobs.errors import JenkinsJobsException
from jenkins_jobs.errors import MissingAttributeError
import jenkins_jobs.modules.base
import jenkins_jobs.modules.helpers as helpers
import pkg_resources
from jenkins_jobs.modules import hudson_model
from jenkins_jobs.modules.publishers import ssh
from jenkins_jobs.modules.publishers import cifs
logger = logging.getLogger(__name__)
def shell(registry, xml_parent, data):
"""yaml: shell
Execute a shell command.
There are two ways of configuring the builder, with a plain string to
execute:
:arg str parameter: the shell command to execute
Or with a mapping that allows other parameters to be passed:
:arg str command: the shell command to execute
:arg int unstable-return:
the shell exit code to interpret as an unstable build result
Example:
.. literalinclude:: /../../tests/builders/fixtures/shell.yaml
:language: yaml
.. literalinclude::
/../../tests/builders/fixtures/shell-unstable-return.yaml
:language: yaml
"""
shell = XML.SubElement(xml_parent, "hudson.tasks.Shell")
if isinstance(data, six.string_types):
XML.SubElement(shell, "command").text = data
else:
mappings = [
("command", "command", None),
("unstable-return", "unstableReturn", 0),
]
helpers.convert_mapping_to_xml(shell, data, mappings, fail_required=True)
def python(registry, xml_parent, data):
"""yaml: python
Execute a python command. Requires the Jenkins :jenkins-plugins:`Python plugin
<python>`.
:arg str parameter: the python command to execute
Example:
.. literalinclude:: /../../tests/builders/fixtures/python.yaml
:language: yaml
"""
python = XML.SubElement(xml_parent, "hudson.plugins.python.Python")
XML.SubElement(python, "command").text = data
def copyartifact(registry, xml_parent, data):
"""yaml: copyartifact
Copy artifact from another project. Requires the :jenkins-plugins:`Copy
Artifact plugin <copyartifact>`.
Please note using the multijob-build for which-build argument requires
the :jenkins-plugins:`Multijob plugin <jenkins-multijob-plugin>`
:arg str project: Project to copy from
:arg str filter: what files to copy
:arg str target: Target base directory for copy, blank means use workspace
:arg bool flatten: Flatten directories (default false)
:arg bool optional: If the artifact is missing (for any reason) and
optional is true, the build won't fail because of this builder
(default false)
:arg bool do-not-fingerprint: Disable automatic fingerprinting of copied
artifacts (default false)
:arg str which-build: which build to get artifacts from
(optional, default last-successful)
:which-build values:
* **last-successful**
* **last-completed**
* **specific-build**
* **last-saved**
* **upstream-build**
* **permalink**
* **workspace-latest**
* **build-param**
* **downstream-build**
* **multijob-build**
:arg str build-number: specifies the build number to get when
when specific-build is specified as which-build
:arg str permalink: specifies the permalink to get when
permalink is specified as which-build
:permalink values:
* **last**
* **last-stable**
* **last-successful**
* **last-failed**
* **last-unstable**
* **last-unsuccessful**
:arg bool stable: specifies to get only last stable build when
last-successful is specified as which-build
:arg bool fallback-to-last-successful: specifies to fallback to
last successful build when upstream-build is specified as which-build
:arg str param: specifies to use a build parameter to get the build when
build-param is specified as which-build
:arg str upstream-project-name: specifies the project name of downstream
when downstream-build is specified as which-build
:arg str upstream-build-number: specifies the number of the build to
find its downstream build when downstream-build is specified as
which-build
:arg str parameter-filters: Filter matching jobs based on these
parameters (optional)
:arg str exclude: Specify paths or patterns of artifacts to
exclude, even if specified in "Artifacts to copy". (default '')
:arg str result-var-suffix: The build number of the selected build
will be recorded into the variable named
COPYARTIFACT_BUILD_NUMBER_(SUFFIX)
for later build steps to reference. (default '')
Example:
.. literalinclude:: ../../tests/builders/fixtures/copy-artifact001.yaml
:language: yaml
Multijob Example:
.. literalinclude:: ../../tests/builders/fixtures/copy-artifact004.yaml
:language: yaml
"""
t = XML.SubElement(xml_parent, "hudson.plugins.copyartifact.CopyArtifact")
mappings = [
# Warning: this only works with copy artifact version 1.26+,
# for copy artifact version 1.25- the 'projectName' element needs
# to be used instead of 'project'
("project", "project", None),
("filter", "filter", ""),
("target", "target", ""),
("flatten", "flatten", False),
("optional", "optional", False),
("do-not-fingerprint", "doNotFingerprintArtifacts", False),
("parameter-filters", "parameters", ""),
("exclude", "exclude", ""),
("result-var-suffix", "resultVariableSuffix", ""),
]
helpers.convert_mapping_to_xml(t, data, mappings, fail_required=True)
helpers.copyartifact_build_selector(t, data)
def change_assembly_version(registry, xml_parent, data):
"""yaml: change-assembly-version
Change the assembly version.
Requires the Jenkins :jenkins-plugins:`Change Assembly Version
<change-assembly-version-plugin>`.
:arg str version: Set the new version number for replace (default 1.0.0)
:arg str assemblyFile: The file name to search (default AssemblyInfo.cs)
Minimal Example:
.. literalinclude::
/../../tests/builders/fixtures/changeassemblyversion-minimal.yaml
:language: yaml
Full Example:
.. literalinclude::
/../../tests/builders/fixtures/changeassemblyversion-full.yaml
:language: yaml
"""
cav_builder_tag = (
"org.jenkinsci.plugins.changeassemblyversion." "ChangeAssemblyVersion"
)
cav = XML.SubElement(xml_parent, cav_builder_tag)
mappings = [
("version", "task", "1.0.0"),
("assembly-file", "assemblyFile", "AssemblyInfo.cs"),
]
helpers.convert_mapping_to_xml(cav, data, mappings, fail_required=True)
def fingerprint(registry, xml_parent, data):
"""yaml: fingerprint
Adds the ability to generate fingerprints as build steps instead of waiting
for a build to complete.
Requires the Jenkins :jenkins-plugins:`Fingerprint Plugin
<create-fingerprint>`.
:arg str targets: Files to fingerprint (default '')
Full Example:
.. literalinclude::
/../../tests/builders/fixtures/fingerprint-full.yaml
:language: yaml
Minimal Example:
.. literalinclude::
/../../tests/builders/fixtures/fingerprint-minimal.yaml
:language: yaml
"""
fingerprint = XML.SubElement(
xml_parent, "hudson.plugins.createfingerprint.CreateFingerprint"
)
fingerprint.set("plugin", "create-fingerprint")
mapping = [("targets", "targets", "")]
helpers.convert_mapping_to_xml(fingerprint, data, mapping, fail_required=True)
def ant(registry, xml_parent, data):
"""yaml: ant
Execute an ant target. Requires the Jenkins :jenkins-plugins:`Ant Plugin
<ant>`.
To setup this builder you can either reference the list of targets
or use named parameters. Below is a description of both forms:
*1) Listing targets:*
After the ant directive, simply pass as argument a space separated list
of targets to build.
:Parameter: space separated list of Ant targets
Example to call two Ant targets:
.. literalinclude:: ../../tests/builders/fixtures/ant001.yaml
:language: yaml
The build file would be whatever the Jenkins Ant Plugin is set to use
per default (i.e build.xml in the workspace root).
*2) Using named parameters:*
:arg str targets: the space separated list of ANT targets.
:arg str buildfile: the path to the ANT build file.
:arg list properties: Passed to ant script using -Dkey=value (optional)
:arg str ant-name: the name of the ant installation,
(default 'default') (optional)
:arg str java-opts: java options for ant, can have multiples,
must be in quotes (optional)
Example specifying the build file too and several targets:
.. literalinclude:: ../../tests/builders/fixtures/ant002.yaml
:language: yaml
"""
ant = XML.SubElement(xml_parent, "hudson.tasks.Ant")
if type(data) is str:
# Support for short form: -ant: "target"
data = {"targets": data}
mapping = [
("targets", "targets", None),
("buildfile", "buildFile", None),
("ant-name", "antName", "default"),
]
helpers.convert_mapping_to_xml(ant, data, mapping, fail_required=False)
mapping = []
for setting, value in sorted(data.items()):
if setting == "properties":
properties = value
prop_string = ""
for prop, val in properties.items():
prop_string += "%s=%s\n" % (prop, val)
mapping.append(("", "properties", prop_string))
if setting == "java-opts":
jopt_string = "\n".join(value)
mapping.append(("", "antOpts", jopt_string))
helpers.convert_mapping_to_xml(ant, data, mapping, fail_required=True)
def trigger_remote(registry, xml_parent, data):
"""yaml: trigger-remote
Trigger build of job on remote Jenkins instance.
Requires the Jenkins :jenkins-plugins:`Parameterized Remote Trigger Plugin
<Parameterized-Remote-Trigger>`
Please note that this plugin requires system configuration on the Jenkins
Master that is unavailable from individual job views; specifically, one
must add remote jenkins servers whose 'Display Name' field are what make up
valid fields on the `remote-jenkins-name` attribute below.
:arg str remote-jenkins-name: the remote Jenkins server (required)
:arg str job: the Jenkins project to trigger on the remote Jenkins server
(required)
:arg bool should-not-fail-build: if true, remote job failure will not lead
current job to fail (default false)
:arg bool prevent-remote-build-queue: if true, wait to trigger remote
builds until no other builds (default false)
:arg bool block: whether to wait for the trigger jobs to finish or not
(default true)
:arg str poll-interval: polling interval in seconds for checking statues of
triggered remote job, only necessary if current job is configured to
block (default 10)
:arg str connection-retry-limit: number of connection attempts to remote
Jenkins server before giving up. (default 5)
:arg bool enhanced-logging: if this option is enabled,
the console output of the remote job is also logged. (default false)
:arg str predefined-parameters: predefined parameters to send to the remote
job when triggering it (optional)
:arg str property-file: file in workspace of current job containing
additional parameters to be set on remote job
(optional)
Example:
.. literalinclude::
/../../tests/builders/fixtures/trigger-remote/trigger-remote001.yaml
:language: yaml
"""
triggerr = XML.SubElement(
xml_parent,
"org.jenkinsci.plugins."
"ParameterizedRemoteTrigger."
"RemoteBuildConfiguration",
)
mappings = [
("remote-jenkins-name", "remoteJenkinsName", None),
("token", "token", ""),
("job", "job", None),
("should-not-fail-build", "shouldNotFailBuild", False),
("poll-interval", "pollInterval", 10),
("connection-retry-limit", "connectionRetryLimit", 5),
("enhanced-logging", "enhancedLogging", False),
("prevent-remote-build-queue", "preventRemoteBuildQueue", False),
("block", "blockBuildUntilComplete", True),
]
helpers.convert_mapping_to_xml(triggerr, data, mappings, fail_required=True)
mappings = []
if "predefined-parameters" in data:
parameters = data.get("predefined-parameters", "")
XML.SubElement(triggerr, "parameters").text = parameters
params_list = parameters.split("\n")
parameter_list = XML.SubElement(triggerr, "parameterList")
for param in params_list:
if param == "":
continue
tmp = XML.SubElement(parameter_list, "string")
tmp.text = param
if "property-file" in data and data["property-file"] != "":
mappings.append(("", "loadParamsFromFile", "true"))
mappings.append(("property-file", "parameterFile", None))
else:
mappings.append(("", "loadParamsFromFile", "false"))
mappings.append(("", "overrideAuth", "false"))
helpers.convert_mapping_to_xml(triggerr, data, mappings, fail_required=True)
def trigger_builds(registry, xml_parent, data):
"""yaml: trigger-builds
Trigger builds of other jobs.
Requires the Jenkins :jenkins-plugins:`Parameterized Trigger Plugin
<parameterized-trigger>`.
:arg list project: the Jenkins project to trigger
:arg str predefined-parameters: key/value pairs to be passed to the job
(optional)
:arg list bool-parameters:
:Bool:
* **name** (`str`) -- Parameter name
* **value** (`bool`) -- Value to set (default false)
:arg str property-file:
Pass properties from file to the other job (optional)
:arg bool property-file-fail-on-missing:
Don't trigger if any files are missing (default true)
:arg bool current-parameters: Whether to include the parameters passed
to the current build to the triggered job.
:arg str node-label-name: Define a name for the NodeLabel parameter to be
set. Used in conjunction with node-label. Requires NodeLabel Parameter
Plugin (optional)
:arg str node-label: Label of the nodes where build should be triggered.
Used in conjunction with node-label-name. Requires NodeLabel Parameter
Plugin (optional)
:arg str restrict-matrix-project: Filter that restricts the subset
of the combinations that the triggered job will run (optional)
:arg bool svn-revision: Whether to pass the svn revision to the triggered
job (optional)
:arg dict git-revision: Passes git revision to the triggered job
(optional).
* **combine-queued-commits** (bool): Whether to combine queued git
hashes or not (default false)
:arg bool block: whether to wait for the triggered jobs to finish or not
(default false)
:arg dict block-thresholds: Fail builds and/or mark as failed or unstable
based on thresholds. Only apply if block parameter is true (optional)
:block-thresholds:
* **build-step-failure-threshold** (`str`) - build step failure
threshold, valid values are 'never', 'SUCCESS', 'UNSTABLE', or
'FAILURE'. (default 'FAILURE')
* **unstable-threshold** (`str`) - unstable threshold, valid
values are 'never', 'SUCCESS', 'UNSTABLE', or 'FAILURE'.
(default 'UNSTABLE')
* **failure-threshold** (`str`) - overall failure threshold, valid
values are 'never', 'SUCCESS', 'UNSTABLE', or 'FAILURE'.
(default 'FAILURE')
:arg bool same-node: Use the same node for the triggered builds that was
used for this build (optional)
:arg list parameter-factories: list of parameter factories
:Factory:
* **factory** (`str`) **filebuild** -- For every property file,
invoke one build
* **file-pattern** (`str`) -- File wildcard pattern
* **no-files-found-action** (`str`) -- Action to perform when
no files found. Valid values 'FAIL', 'SKIP', or 'NOPARMS'.
(default 'SKIP')
:Factory:
* **factory** (`str`) **binaryfile** -- For every matching
file, invoke one build
* **file-pattern** (`str`) -- Artifact ID of the artifact
* **no-files-found-action** (`str`) -- Action to perform when
no files found. Valid values 'FAIL', 'SKIP', or 'NOPARMS'.
(default 'SKIP')
:Factory:
* **factory** (`str`) **counterbuild** -- Invoke i=0...N builds
* **from** (`int`) -- Artifact ID of the artifact
* **to** (`int`) -- Version of the artifact
* **step** (`int`) -- Classifier of the artifact
* **parameters** (`str`) -- KEY=value pairs, one per line
(default '')
* **validation-fail** (`str`) -- Action to perform when
stepping validation fails. Valid values 'FAIL', 'SKIP', or
'NOPARMS'. (default 'FAIL')
:Factory:
* **factory** (`str`) **allnodesforlabel** -- Trigger a build
on all nodes having specific label. Requires NodeLabel
Parameter Plugin (optional)
* **name** (`str`) -- Name of the parameter to set (optional)
* **node-label** (`str`) -- Label of the nodes where build
should be triggered
* **ignore-offline-nodes** (`bool`) -- Don't trigger build on
offline nodes (default true)
:Factory:
* **factory** (`str`) **allonlinenodes** -- Trigger a build on
every online node. Requires NodeLabel Parameter Plugin (optional)
Examples:
Basic usage with yaml list of projects.
.. literalinclude::
/../../tests/builders/fixtures/trigger-builds/project-list.yaml
:language: yaml
Basic usage with passing svn revision through.
.. literalinclude:: /../../tests/builders/fixtures/trigger-builds001.yaml
:language: yaml
Basic usage with passing git revision through.
.. literalinclude:: /../../tests/builders/fixtures/trigger-builds006.yaml
:language: yaml
Example with all supported parameter factories.
.. literalinclude::
/../../tests/builders/fixtures/trigger-builds-configfactory-multi.yaml
:language: yaml
"""
tbuilder = XML.SubElement(
xml_parent, "hudson.plugins.parameterizedtrigger." "TriggerBuilder"
)
configs = XML.SubElement(tbuilder, "configs")
for project_def in data:
if "project" not in project_def or project_def["project"] == "":
logger.debug("No project specified - skipping trigger-build")
continue
tconfig = XML.SubElement(
configs,
"hudson.plugins.parameterizedtrigger." "BlockableBuildTriggerConfig",
)
tconfigs = XML.SubElement(tconfig, "configs")
if project_def.get("current-parameters"):
XML.SubElement(
tconfigs,
"hudson.plugins.parameterizedtrigger." "CurrentBuildParameters",
)
if project_def.get("svn-revision"):
XML.SubElement(
tconfigs,
"hudson.plugins.parameterizedtrigger."
"SubversionRevisionBuildParameters",
)
if project_def.get("git-revision"):
helpers.append_git_revision_config(tconfigs, project_def["git-revision"])
if project_def.get("same-node"):
XML.SubElement(
tconfigs, "hudson.plugins.parameterizedtrigger." "NodeParameters"
)
if "property-file" in project_def:
params = XML.SubElement(
tconfigs, "hudson.plugins.parameterizedtrigger." "FileBuildParameters"
)
mapping = [
("property-file", "propertiesFile", None),
("property-file-fail-on-missing", "failTriggerOnMissing", True),
]
helpers.convert_mapping_to_xml(
params, project_def, mapping, fail_required=True
)
if "predefined-parameters" in project_def:
params = XML.SubElement(
tconfigs,
"hudson.plugins.parameterizedtrigger." "PredefinedBuildParameters",
)
mapping = [("predefined-parameters", "properties", None)]
helpers.convert_mapping_to_xml(
params, project_def, mapping, fail_required=True
)
if "bool-parameters" in project_def:
params = XML.SubElement(
tconfigs, "hudson.plugins.parameterizedtrigger." "BooleanParameters"
)
configs = XML.SubElement(params, "configs")
for bool_param in project_def["bool-parameters"]:
param = XML.SubElement(
configs,
"hudson.plugins.parameterizedtrigger." "BooleanParameterConfig",
)
mapping = [("name", "name", None), ("value", "value", False)]
helpers.convert_mapping_to_xml(
param, bool_param, mapping, fail_required=True
)
if "node-label-name" in project_def and "node-label" in project_def:
node = XML.SubElement(
tconfigs,
"org.jvnet.jenkins.plugins."
"nodelabelparameter.parameterizedtrigger."
"NodeLabelBuildParameter",
)
mapping = [
("node-label-name", "name", None),
("node-label", "nodeLabel", None),
]
helpers.convert_mapping_to_xml(
node, project_def, mapping, fail_required=True
)
if "restrict-matrix-project" in project_def:
params = XML.SubElement(
tconfigs,
"hudson.plugins.parameterizedtrigger."
"matrix.MatrixSubsetBuildParameters",
)
mapping = [("restrict-matrix-project", "filter", None)]
helpers.convert_mapping_to_xml(
params, project_def, mapping, fail_required=True
)
if len(list(tconfigs)) == 0:
tconfigs.set("class", "java.util.Collections$EmptyList")
if "parameter-factories" in project_def:
fconfigs = XML.SubElement(tconfig, "configFactories")
supported_factories = [
"filebuild",
"binaryfile",
"counterbuild",
"allnodesforlabel",
"allonlinenodes",
]
supported_actions = ["SKIP", "NOPARMS", "FAIL"]
for factory in project_def["parameter-factories"]:
if factory["factory"] not in supported_factories:
raise InvalidAttributeError(
"factory", factory["factory"], supported_factories
)
if factory["factory"] == "filebuild":
params = XML.SubElement(
fconfigs,
"hudson.plugins.parameterizedtrigger."
"FileBuildParameterFactory",
)
if factory["factory"] == "binaryfile":
params = XML.SubElement(
fconfigs,
"hudson.plugins.parameterizedtrigger."
"BinaryFileParameterFactory",
)
mapping = [("parameter-name", "parameterName", None)]
helpers.convert_mapping_to_xml(
params, factory, mapping, fail_required=True
)
if (
factory["factory"] == "filebuild"
or factory["factory"] == "binaryfile"
):
mapping = [
("file-pattern", "filePattern", None),
(
"no-files-found-action",
"noFilesFoundAction",
"SKIP",
supported_actions,
),
]
helpers.convert_mapping_to_xml(
params, factory, mapping, fail_required=True
)
if factory["factory"] == "counterbuild":
params = XML.SubElement(
fconfigs,
"hudson.plugins.parameterizedtrigger."
"CounterBuildParameterFactory",
)
mapping = [
("from", "from", None),
("to", "to", None),
("step", "step", None),
("parameters", "paramExpr", ""),
(
"validation-fail",
"validationFail",
"FAIL",
supported_actions,
),
]
helpers.convert_mapping_to_xml(
params, factory, mapping, fail_required=True
)
if factory["factory"] == "allnodesforlabel":
params = XML.SubElement(
fconfigs,
"org.jvnet.jenkins.plugins.nodelabelparameter."
"parameterizedtrigger."
"AllNodesForLabelBuildParameterFactory",
)
mapping = [
("name", "name", ""),
("node-label", "nodeLabel", None),
("ignore-offline-nodes", "ignoreOfflineNodes", True),
]
helpers.convert_mapping_to_xml(
params, factory, mapping, fail_required=True
)
if factory["factory"] == "allonlinenodes":
params = XML.SubElement(
fconfigs,
"org.jvnet.jenkins.plugins.nodelabelparameter."
"parameterizedtrigger."
"AllNodesBuildParameterFactory",
)
projects = XML.SubElement(tconfig, "projects")
if isinstance(project_def["project"], list):
projects.text = ",".join(project_def["project"])
else:
projects.text = project_def["project"]
mapping = [
("", "condition", "ALWAYS"),
("", "triggerWithNoParameters", False),
("", "buildAllNodesWithLabel", False),
]
helpers.convert_mapping_to_xml(tconfig, {}, mapping, fail_required=True)
block = project_def.get("block", False)
if block:
block = XML.SubElement(tconfig, "block")
supported_thresholds = [
[
"build-step-failure-threshold",
"buildStepFailureThreshold",
"FAILURE",
],
["unstable-threshold", "unstableThreshold", "UNSTABLE"],
["failure-threshold", "failureThreshold", "FAILURE"],
]
supported_threshold_values = [
"never",
hudson_model.SUCCESS["name"],
hudson_model.UNSTABLE["name"],
hudson_model.FAILURE["name"],
]
thrsh = project_def.get("block-thresholds", False)
for toptname, txmltag, tvalue in supported_thresholds:
if thrsh:
tvalue = thrsh.get(toptname, tvalue)
if tvalue.lower() == supported_threshold_values[0]:
continue
if tvalue.upper() not in supported_threshold_values:
raise InvalidAttributeError(
toptname, tvalue, supported_threshold_values
)
th = XML.SubElement(block, txmltag)
mapping = [
("name", "name", None),
("ordinal", "ordinal", None),
("color", "color", None),
("", "completeBuild", True),
]
helpers.convert_mapping_to_xml(
th,
hudson_model.THRESHOLDS[tvalue.upper()],
mapping,
fail_required=True,
)
# If configs is empty, remove the entire tbuilder tree.
if len(configs) == 0:
logger.debug("Pruning empty TriggerBuilder tree.")
xml_parent.remove(tbuilder)
def builders_from(registry, xml_parent, data):
"""yaml: builders-from
Use builders from another project.
Requires the Jenkins :jenkins-plugins:`Template Project Plugin
<template-project>`.
:arg str projectName: the name of the other project
Example:
.. literalinclude:: ../../tests/builders/fixtures/builders-from.yaml
:language: yaml
"""
pbs = XML.SubElement(xml_parent, "hudson.plugins.templateproject.ProxyBuilder")
mapping = [("", "projectName", data)]
helpers.convert_mapping_to_xml(pbs, {}, mapping, fail_required=True)
def http_request(registry, xml_parent, data):
"""yaml: http-request
This plugin sends a http request to an url with some parameters.
Requires the Jenkins :jenkins-plugins:`HTTP Request Plugin
<http_request>`.
:arg str url: Specify an URL to be requested (required)
:arg str mode: The http mode of the request (default GET)
:mode values:
* **GET**
* **POST**
* **PUT**
* **DELETE**
* **HEAD**
:arg str content-type: Add 'Content-type: foo' HTTP request headers
where foo is the http content-type the request is using.
(default NOT_SET)
:arg str accept-type: Add 'Accept: foo' HTTP request headers
where foo is the http content-type to accept (default NOT_SET)
:content-type and accept-type values:
* **NOT_SET**
* **TEXT_HTML**
* **APPLICATION_JSON**
* **APPLICATION_TAR**
* **APPLICATION_ZIP**
* **APPLICATION_OCTETSTREAM**
:arg str output-file: Name of the file in which to write response data
(default '')
:arg int time-out: Specify a timeout value in seconds (default 0)
:arg bool console-log: This allows you to turn off writing the response
body to the log (default false)
:arg bool pass-build: Should build parameters be passed to the URL
being called (default false)
:arg str valid-response-codes: Configure response code to mark an
execution as success. You can configure simple code such as "200"
or multiple codes separated by comma(',') e.g. "200,404,500"
Interval of codes should be in format From:To e.g. "100:399".
The default (as if empty) is to fail to 4xx and 5xx.
That means success from 100 to 399 "100:399"
To ignore any response code use "100:599". (default '')
:arg str valid-response-content: If set response must contain this string
to mark an execution as success (default '')
:arg str authentication-key: Authentication that will be used before this
request. Authentications are created in global configuration under a
key name that is selected here.
:arg list custom-headers: list of header parameters
:custom-header:
* **name** (`str`) -- Name of the header
* **value** (`str`) -- Value of the header
Example:
.. literalinclude:: ../../tests/builders/fixtures/http-request-minimal.yaml
:language: yaml
.. literalinclude::
../../tests/builders/fixtures/http-request-full.yaml
:language: yaml
"""
http_request = XML.SubElement(
xml_parent, "jenkins.plugins.http__request.HttpRequest"
)
http_request.set("plugin", "http_request")
valid_modes = ["GET", "POST", "PUT", "DELETE", "HEAD"]
valid_types = [
"NOT_SET",
"TEXT_HTML",
"APPLICATION_JSON",
"APPLICATION_TAR",
"APPLICATION_ZIP",
"APPLICATION_OCTETSTREAM",
]
mappings = [
("url", "url", None),
("mode", "httpMode", "GET", valid_modes),
("content-type", "contentType", "NOT_SET", valid_types),
("accept-type", "acceptType", "NOT_SET", valid_types),
("output-file", "outputFile", ""),
("console-log", "consoleLogResponseBody", False),
("pass-build", "passBuildParameters", False),
("time-out", "timeout", 0),
("valid-response-codes", "validResponseCodes", ""),
("valid-response-content", "validResponseContent", ""),
]
helpers.convert_mapping_to_xml(http_request, data, mappings, fail_required=True)
if "authentication-key" in data:
XML.SubElement(http_request, "authentication").text = data["authentication-key"]
if "custom-headers" in data:
customHeader = XML.SubElement(http_request, "customHeaders")
header_mappings = [("name", "name", None), ("value", "value", None)]
for customhead in data["custom-headers"]:
pair = XML.SubElement(customHeader, "pair")
helpers.convert_mapping_to_xml(
pair, customhead, header_mappings, fail_required=True
)
def inject(registry, xml_parent, data):
"""yaml: inject
Inject an environment for the job.
Requires the Jenkins :jenkins-plugins:`EnvInject Plugin <envinject>`.
:arg str properties-file: the name of the property file (optional)
:arg str properties-content: the properties content (optional)
:arg str script-file: the name of a script file to run (optional)
:arg str script-content: the script content (optional)
Example:
.. literalinclude:: ../../tests/builders/fixtures/inject.yaml
:language: yaml
"""
eib = XML.SubElement(xml_parent, "EnvInjectBuilder")
info = XML.SubElement(eib, "info")
mapping = [
("properties-file", "propertiesFilePath", None),
("properties-content", "propertiesContent", None),
("script-file", "scriptFilePath", None),
("script-content", "scriptContent", None),
]
helpers.convert_mapping_to_xml(info, data, mapping, fail_required=False)
def kmap(registry, xml_parent, data):
"""yaml: kmap
Publish mobile applications to your Keivox KMAP Private Mobile App Store.
Requires the Jenkins :jenkins-plugins:`Keivox KMAP Private Mobile App Store
Plugin <kmap-jenkins>`.
:arg str username: KMAP's user email with permissions to upload/publish
applications to KMAP (required)
:arg str password: Password for the KMAP user uploading/publishing
applications (required)
:arg str url: KMAP's url. This url must always end with "/kmap-client/".
For example: http://testing.example.org/kmap-client/ (required)
:arg str categories: Categories' names. If you want to add the application
to more than one category, write the categories between commas.
(required)
:arg str file-path: Path to the application's file (required)
:arg str app-name: KMAP's application name (required)
:arg str bundle: Bundle indentifier (default '')
:arg str version: Application's version (required)
:arg str description: Application's description (default '')
:arg str icon-path: Path to the application's icon (default '')
:arg bool publish-optional: Publish application after it has been uploaded
to KMAP (default false)
:publish-optional:
* **groups** ('str') -- groups' names to publish the application
(default '')
* **users** ('str') -- users' names to publish the application
(default '')
* **notify-users** ('bool') -- Send notifications to the users and
groups when publishing the application (default false)
Minimal Example:
.. literalinclude:: ../../tests/builders/fixtures/kmap-minimal.yaml
:language: yaml
Full Example:
.. literalinclude:: ../../tests/builders/fixtures/kmap-full.yaml
:language: yaml
"""
kmap = XML.SubElement(xml_parent, "org.jenkinsci.plugins.KmapJenkinsBuilder")
kmap.set("plugin", "kmap-jenkins")
publish = data.get("publish-optional", False)
mapping = [
("username", "username", None),
("password", "password", None),
("url", "kmapClient", None),
("categories", "categories", None),
("file-path", "filePath", None),
("app-name", "appName", None),
("bundle", "bundle", ""),
("version", "version", None),
("description", "description", ""),
("icon-path", "iconPath", ""),
]
helpers.convert_mapping_to_xml(kmap, data, mapping, fail_required=True)
if publish is True:
publish_optional = XML.SubElement(kmap, "publishOptional")
publish_mapping = [
("groups", "teams", ""),
("users", "users", ""),
("notify-users", "sendNotifications", False),
]
helpers.convert_mapping_to_xml(
publish_optional, data, publish_mapping, fail_required=True
)
def artifact_resolver(registry, xml_parent, data):
"""yaml: artifact-resolver
Allows one to resolve artifacts from a maven repository like nexus
(without having maven installed)
Requires the Jenkins :jenkins-plugins:`Repository Connector Plugin
<repository-connector>`.
:arg bool fail-on-error: Whether to fail the build on error (default false)
:arg bool repository-logging: Enable repository logging (default false)
:arg str target-directory: Where to resolve artifacts to (required)
:arg list artifacts: list of artifacts to resolve
:Artifact:
* **group-id** (`str`) -- Group ID of the artifact (required)
* **artifact-id** (`str`) -- Artifact ID of the artifact (required)
* **version** (`str`) -- Version of the artifact (required)
* **classifier** (`str`) -- Classifier of the artifact (default '')
* **extension** (`str`) -- Extension of the artifact
(default 'jar')
* **target-file-name** (`str`) -- What to name the artifact
(default '')
Minimal Example:
.. literalinclude::
../../tests/builders/fixtures/artifact-resolver-minimal.yaml
:language: yaml
Full Example:
.. literalinclude::
../../tests/builders/fixtures/artifact-resolver-full.yaml
:language: yaml
"""
ar = XML.SubElement(
xml_parent, "org.jvnet.hudson.plugins.repositoryconnector.ArtifactResolver"
)
mapping = [
("target-directory", "targetDirectory", None),
("fail-on-error", "failOnError", False),
("repository-logging", "enableRepoLogging", False),
("", "snapshotUpdatePolicy", "never"),
("", "releaseUpdatePolicy", "never"),
("", "snapshotChecksumPolicy", "warn"),
("", "releaseChecksumPolicy", "warn"),
]
helpers.convert_mapping_to_xml(ar, data, mapping, fail_required=True)
artifact_top = XML.SubElement(ar, "artifacts")
artifacts = data["artifacts"]
artifacts_mapping = [
("group-id", "groupId", None),
("artifact-id", "artifactId", None),
("version", "version", None),
("classifier", "classifier", ""),
("extension", "extension", "jar"),
("target-file-name", "targetFileName", ""),
]
for artifact in artifacts:
rcartifact = XML.SubElement(
artifact_top, "org.jvnet.hudson.plugins.repositoryconnector.Artifact"
)
helpers.convert_mapping_to_xml(
rcartifact, artifact, artifacts_mapping, fail_required=True
)
def doxygen(registry, xml_parent, data):
"""yaml: doxygen
Builds doxygen HTML documentation.
Requires the Jenkins :jenkins-plugins:`Doxygen plugin <doxygen>`.
:arg str doxyfile: The doxyfile path (required)
:arg str install: The doxygen installation to use (required)
:arg bool ignore-failure: Keep executing build even on doxygen generation
failure (default false)
:arg bool unstable-warning: Mark the build as unstable if warnings are
generated (default false)
Example:
.. literalinclude:: /../../tests/builders/fixtures/doxygen001.yaml
:language: yaml
"""
doxygen = XML.SubElement(xml_parent, "hudson.plugins.doxygen.DoxygenBuilder")
mappings = [
("doxyfile", "doxyfilePath", None),
("install", "installationName", None),
("ignore-failure", "continueOnBuildFailure", False),
("unstable-warning", "unstableIfWarnings", False),
]
helpers.convert_mapping_to_xml(doxygen, data, mappings, fail_required=True)
def gradle(registry, xml_parent, data):
"""yaml: gradle
Execute gradle tasks.
Requires the Jenkins :jenkins-plugins:`Gradle Plugin <gradle>`.
:arg str tasks: List of tasks to execute
:arg str gradle-name: Use a custom gradle name (default '')
:arg bool wrapper: use gradle wrapper (default false)
:arg bool executable: make gradlew executable (default false)
:arg list switches: Switches for gradle, can have multiples
:arg bool use-root-dir: Whether to run the gradle script from the
top level directory or from a different location (default false)
:arg str root-build-script-dir: If your workspace has the
top-level build.gradle in somewhere other than the module
root directory, specify the path (relative to the module
root) here, such as ${workspace}/parent/ instead of just
${workspace}.
:arg str build-file: name of gradle build script (default 'build.gradle')
:arg bool pass-system-properties: Pass all parameters as
System properties (default false)
:arg bool pass-project-properties: Pass all parameters as
Project properties (default false)
Example:
.. literalinclude:: ../../tests/builders/fixtures/gradle.yaml
:language: yaml
"""
gradle = XML.SubElement(xml_parent, "hudson.plugins.gradle.Gradle")
XML.SubElement(gradle, "description").text = ""
mappings = [
("build-file", "buildFile", "build.gradle"),
("tasks", "tasks", None),
("root-build-script-dir", "rootBuildScriptDir", ""),
("gradle-name", "gradleName", ""),
("wrapper", "useWrapper", False),
("executable", "makeExecutable", False),
("use-root-dir", "fromRootBuildScriptDir", False),
("pass-system-properties", "passAllAsSystemProperties", False),
("pass-project-properties", "passAllAsProjectProperties", False),
]
helpers.convert_mapping_to_xml(gradle, data, mappings, fail_required=True)
XML.SubElement(gradle, "switches").text = "\n".join(data.get("switches", []))
def _groovy_common_scriptSource(data):
"""Helper function to generate the XML element common to groovy builders."""
scriptSource = XML.Element("scriptSource")
if "command" in data and "file" in data:
raise JenkinsJobsException("Use just one of 'command' or 'file'")
if "command" in data:
mapping = [("command", "command", None)]
helpers.convert_mapping_to_xml(scriptSource, data, mapping, fail_required=True)
scriptSource.set("class", "hudson.plugins.groovy.StringScriptSource")
elif "file" in data:
mapping = [("file", "scriptFile", None)]
helpers.convert_mapping_to_xml(scriptSource, data, mapping, fail_required=True)
scriptSource.set("class", "hudson.plugins.groovy.FileScriptSource")
else:
raise JenkinsJobsException("A groovy command or file is required")
return scriptSource
def groovy(registry, xml_parent, data):
"""yaml: groovy
Execute a groovy script or command.
Requires the Jenkins :jenkins-plugins:`Groovy Plugin <groovy>`.
:arg str file: Groovy file to run. (Alternative: you can chose a command
instead)
:arg str command: Groovy command to run. (Alternative: you can chose a
script file instead)
:arg str version: Groovy version to use. (default '(Default)')
:arg str parameters: Parameters for the Groovy executable. (default '')
:arg str script-parameters: These parameters will be passed to the script.
(default '')
:arg str properties: Instead of passing properties using the -D parameter
you can define them here. (default '')
:arg str java-opts: Direct access to JAVA_OPTS. Properties allows only
-D properties, while sometimes also other properties like -XX need to
be setup. It can be done here. This line is appended at the end of
JAVA_OPTS string. (default '')
:arg str class-path: Specify script classpath here. Each line is one
class path item. (default '')
Minimal Example:
.. literalinclude:: ../../tests/builders/fixtures/groovy-minimal.yaml
:language: yaml
Full Example:
.. literalinclude:: ../../tests/builders/fixtures/groovy-full.yaml
:language: yaml
"""
root_tag = "hudson.plugins.groovy.Groovy"
groovy = XML.SubElement(xml_parent, root_tag)
groovy.append(_groovy_common_scriptSource(data))
mappings = [
("version", "groovyName", "(Default)"),
("parameters", "parameters", ""),
("script-parameters", "scriptParameters", ""),
("properties", "properties", ""),
("java-opts", "javaOpts", ""),
("class-path", "classPath", ""),
]
helpers.convert_mapping_to_xml(groovy, data, mappings, fail_required=True)
def system_groovy(registry, xml_parent, data):
"""yaml: system-groovy
Execute a system groovy script or command.
Requires the Jenkins :jenkins-plugins:`Groovy Plugin <groovy>`.
:arg str file: Groovy file to run. (Alternative: you can chose a command
instead)
:arg str command: Groovy command to run. (Alternative: you can choose a
script file instead)
:arg bool sandbox: Execute script inside of groovy sandbox (>=2.0)
(default false)
:arg str bindings: Define variable bindings (in the properties file
format). Specified variables can be addressed from the script.
(optional)
:arg (list str) class-path: List of script class paths.
(optional)
Examples:
.. literalinclude:: ../../tests/builders/fixtures/system-groovy001.yaml
:language: yaml
.. literalinclude:: ../../tests/builders/fixtures/system-groovy002.yaml
:language: yaml
"""
root_tag = "hudson.plugins.groovy.SystemGroovy"
sysgroovy = XML.SubElement(xml_parent, root_tag)
if "file" in data:
scriptSource = _groovy_common_scriptSource(data)
if "command" in data:
scriptSource = XML.Element("source")
scriptSource.set("class", "hudson.plugins.groovy.StringSystemScriptSource")
script = XML.SubElement(scriptSource, "script")
mapping = [("command", "script", None), ("sandbox", "sandbox", False)]
helpers.convert_mapping_to_xml(script, data, mapping, fail_required=True)
classpath = XML.SubElement(script, "classpath")
classpaths = data.get("class-path", [])
if isinstance(classpaths, str):
classpaths = [classpaths]
for path in classpaths:
entry = XML.SubElement(classpath, "entry")
XML.SubElement(entry, "url").text = path
sysgroovy.append(scriptSource)
mapping = [("bindings", "bindings", "")]
helpers.convert_mapping_to_xml(sysgroovy, data, mapping, fail_required=True)
def batch(registry, xml_parent, data):
"""yaml: batch
Execute a batch command.
:Parameter: the batch command to execute
Example:
.. literalinclude:: ../../tests/builders/fixtures/batch.yaml
:language: yaml
"""
batch = XML.SubElement(xml_parent, "hudson.tasks.BatchFile")
XML.SubElement(batch, "command").text = data
def powershell(registry, xml_parent, data):
"""yaml: powershell
Execute a powershell command.
Requires the :jenkins-plugins:`Powershell Plugin <powershell>`.
:Parameter: the powershell command to execute
Example:
.. literalinclude:: ../../tests/builders/fixtures/powershell.yaml
:language: yaml
"""
ps = XML.SubElement(xml_parent, "hudson.plugins.powershell.PowerShell")
XML.SubElement(ps, "command").text = data
def msbuild(registry, xml_parent, data):
"""yaml: msbuild
Build .NET project using msbuild.
Requires the Jenkins :jenkins-plugins:'MSBuild Plugin <msbuild>`.
:arg str msbuild-version: which msbuild configured in Jenkins to use
(default '(Default)')
:arg str solution-file: location of the solution file to build (required)
:arg str extra-parameters: extra parameters to pass to msbuild (default '')
:arg bool pass-build-variables: should build variables be passed
to msbuild (default true)
:arg bool continue-on-build-failure: should the build continue if
msbuild returns an error (default false)
:arg bool unstable-if-warnings: If set to true and warnings on compilation,
the build will be unstable (>=1.20) (default false)
Full Example:
.. literalinclude:: ../../tests/builders/fixtures/msbuild-full.yaml
:language: yaml
Minimal Example:
.. literalinclude:: ../../tests/builders/fixtures/msbuild-minimal.yaml
:language: yaml
"""
msbuilder = XML.SubElement(xml_parent, "hudson.plugins.msbuild.MsBuildBuilder")
msbuilder.set("plugin", "msbuild")
mapping = [
("msbuild-version", "msBuildName", "(Default)"),
("solution-file", "msBuildFile", None),
("extra-parameters", "cmdLineArgs", ""),
("pass-build-variables", "buildVariablesAsProperties", True),
("continue-on-build-failure", "continueOnBuildFailure", False),
("unstable-if-warnings", "unstableIfWarnings", False),
]
helpers.convert_mapping_to_xml(msbuilder, data, mapping, fail_required=True)
def create_builders(registry, step):
dummy_parent = XML.Element("dummy")
registry.dispatch("builder", dummy_parent, step)
return list(dummy_parent)
def conditional_step(registry, xml_parent, data):
"""yaml: conditional-step
Conditionally execute some build steps.
Requires the Jenkins :jenkins-plugins:`Conditional BuildStep Plugin
<conditional-buildstep>`.
Depending on the number of declared steps, a `Conditional step (single)`
or a `Conditional steps (multiple)` is created in Jenkins.
:arg str condition-kind: Condition kind that must be verified before the
steps are executed. Valid values and their additional attributes are
described in the conditions_ table.
:arg str on-evaluation-failure: What should be the outcome of the build
if the evaluation of the condition fails. Possible values are `fail`,
`mark-unstable`, `run-and-mark-unstable`, `run` and `dont-run`.
(default 'fail').
:arg list steps: List of steps to run if the condition is verified. Items
in the list can be any builder known by Jenkins Job Builder.
.. _conditions:
================== ====================================================
Condition kind Description
================== ====================================================
always Condition is always verified
never Condition is never verified
boolean-expression Run the step if the expression expends to a
representation of true
:condition-expression: Expression to expand (required)
build-cause Run if the current build has a specific cause
:cause: The cause why the build was triggered.
Following causes are supported -
:USER_CAUSE: build was triggered by a manual
interaction. (default)
:SCM_CAUSE: build was triggered by a SCM change.
:TIMER_CAUSE: build was triggered by a timer.
:CLI_CAUSE: build was triggered by via CLI interface
:REMOTE_CAUSE: build was triggered via remote
interface.
:UPSTREAM_CAUSE: build was triggered by an upstream
project.
Following supported if XTrigger plugin installed:
:FS_CAUSE: build was triggered by a file system
change (FSTrigger Plugin).
:URL_CAUSE: build was triggered by a URL change
(URLTrigger Plugin)
:IVY_CAUSE: build triggered by an Ivy dependency
version has change (IvyTrigger Plugin)
:SCRIPT_CAUSE: build was triggered by a script
(ScriptTrigger Plugin)
:BUILDRESULT_CAUSE: build was triggered by a
result of another job (BuildResultTrigger Plugin)
:exclusive-cause: (bool) There might by multiple
causes causing a build to be triggered, with
this true, the cause must be the only one
causing this build this build to be triggered.
(default false)
day-of-week Only run on specific days of the week.
:day-selector: Days you want the build to run on.
Following values are supported -
:weekend: Saturday and Sunday (default).
:weekday: Monday - Friday.
:select-days: Selected days, defined by 'days'
below.
:days: True for days for which the build should
run. Definition needed only for 'select-days'
day-selector, at the same level as day-selector.
Define the days to run under this.
:SUN: Run on Sunday (default false)
:MON: Run on Monday (default false)
:TUES: Run on Tuesday (default false)
:WED: Run on Wednesday (default false)
:THURS: Run on Thursday (default false)
:FRI: Run on Friday (default false)
:SAT: Run on Saturday (default false)
:use-build-time: (bool) Use the build time instead of
the the time that the condition is evaluated.
(default false)
execution-node Run only on selected nodes.
:nodes: (list) List of nodes to execute on. (required)
strings-match Run the step if two strings match
:condition-string1: First string (optional)
:condition-string2: Second string (optional)
:condition-case-insensitive: Case insensitive
(default false)
current-status Run the build step if the current build status is
within the configured range
:condition-worst: Accepted values are SUCCESS,
UNSTABLE, FAILURE, NOT_BUILD, ABORTED
(default SUCCESS)
:condition-best: Accepted values are SUCCESS,
UNSTABLE, FAILURE, NOT_BUILD, ABORTED
(default SUCCESS)
shell Run the step if the shell command succeed
:condition-command: Shell command to execute
(optional)
windows-shell Similar to shell, except that commands will be
executed by cmd, under Windows
:condition-command: Command to execute (optional)
file-exists Run the step if a file exists
:condition-filename: Check existence of this file
(required)
:condition-basedir: If condition-filename is
relative, it will be considered relative to
either `workspace`, `artifact-directory`,
or `jenkins-home`. (default 'workspace')
files-match Run if one or more files match the selectors.
:include-pattern: (list str) List of Includes
Patterns. Since the separator in the patterns is
hardcoded as ',', any use of ',' would need
escaping. (optional)
:exclude-pattern: (list str) List of Excludes
Patterns. Since the separator in the patterns is
hardcoded as ',', any use of ',' would need
escaping. (optional)
:condition-basedir: Accepted values are `workspace`,
`artifact-directory`, or `jenkins-home`.
(default 'workspace')
num-comp Run if the numerical comparison is true.
:lhs: Left Hand Side. Must evaluate to a number.
(required)
:rhs: Right Hand Side. Must evaluate to a number.
(required)
:comparator: Accepted values are `less-than`,
`greater-than`, `equal`, `not-equal`,
`less-than-equal`, `greater-than-equal`.
(default 'less-than')
regex-match Run if the Expression matches the Label.
:regex: The regular expression used to match the label
(optional)
:label: The label that will be tested by the regular
expression. (optional)
time Only run during a certain period of the day.
:earliest-hour: Starting hour (default "09")
:earliest-min: Starting min (default "00")
:latest-hour: Ending hour (default "17")
:latest-min: Ending min (default "30")
:use-build-time: (bool) Use the build time instead of
the the time that the condition is evaluated.
(default false)
not Run the step if the inverse of the condition-operand
is true
:condition-operand: Condition to evaluate. Can be
any supported conditional-step condition. (required)
and Run the step if logical and of all conditional-operands
is true
:condition-operands: (list) Conditions to evaluate.
Can be any supported conditional-step condition.
(required)
or Run the step if logical or of all conditional-operands
is true
:condition-operands: (list) Conditions to evaluate.
Can be any supported conditional-step condition.
(required)
================== ====================================================
Examples:
.. literalinclude::
/../../tests/builders/fixtures/conditional-step-multiple-steps.yaml
:language: yaml
.. literalinclude::
/../../tests/builders/fixtures/conditional-step-success-failure.yaml
:language: yaml
.. literalinclude::
/../../tests/builders/fixtures/conditional-step-not-file-exists.yaml
:language: yaml
.. literalinclude::
/../../tests/builders/fixtures/conditional-step-day-of-week001.yaml
:language: yaml
.. literalinclude::
/../../tests/builders/fixtures/conditional-step-day-of-week003.yaml
:language: yaml
.. literalinclude::
/../../tests/builders/fixtures/conditional-step-time.yaml
:language: yaml
.. literalinclude::
/../../tests/builders/fixtures/conditional-step-regex-match.yaml
:language: yaml
.. literalinclude::
/../../tests/builders/fixtures/conditional-step-or.yaml
:language: yaml
.. literalinclude::
/../../tests/builders/fixtures/conditional-step-and.yaml
:language: yaml
"""
def build_condition(cdata, cond_root_tag, condition_tag):
kind = cdata["condition-kind"]
ctag = XML.SubElement(cond_root_tag, condition_tag)
core_prefix = "org.jenkins_ci.plugins.run_condition.core."
logic_prefix = "org.jenkins_ci.plugins.run_condition.logic."
if kind == "always":
ctag.set("class", core_prefix + "AlwaysRun")
elif kind == "never":
ctag.set("class", core_prefix + "NeverRun")
elif kind == "boolean-expression":
ctag.set("class", core_prefix + "BooleanCondition")
mapping = [("condition-expression", "token", None)]
helpers.convert_mapping_to_xml(ctag, cdata, mapping, fail_required=True)
elif kind == "build-cause":
ctag.set("class", core_prefix + "CauseCondition")
cause_list = (
"USER_CAUSE",
"SCM_CAUSE",
"TIMER_CAUSE",
"CLI_CAUSE",
"REMOTE_CAUSE",
"UPSTREAM_CAUSE",
"FS_CAUSE",
"URL_CAUSE",
"IVY_CAUSE",
"SCRIPT_CAUSE",
"BUILDRESULT_CAUSE",
)
mapping = [
("cause", "buildCause", "USER_CAUSE", cause_list),
("exclusive-cause", "exclusiveCause", False),
]
helpers.convert_mapping_to_xml(ctag, cdata, mapping, fail_required=True)
elif kind == "day-of-week":
ctag.set("class", core_prefix + "DayCondition")
day_selector_class_prefix = core_prefix + "DayCondition$"
day_selector_classes = {
"weekend": day_selector_class_prefix + "Weekend",
"weekday": day_selector_class_prefix + "Weekday",
"select-days": day_selector_class_prefix + "SelectDays",
}
day_selector = cdata.get("day-selector", "weekend")
if day_selector not in day_selector_classes:
raise InvalidAttributeError(
"day-selector", day_selector, day_selector_classes
)
day_selector_tag = XML.SubElement(ctag, "daySelector")
day_selector_tag.set("class", day_selector_classes[day_selector])
if day_selector == "select-days":
days_tag = XML.SubElement(day_selector_tag, "days")
day_tag_text = (
"org.jenkins__ci.plugins.run__condition." "core.DayCondition_-Day"
)
inp_days = cdata.get("days") if cdata.get("days") else {}
days = ["SUN", "MON", "TUES", "WED", "THURS", "FRI", "SAT"]
for day_no, day in enumerate(days, 1):
day_tag = XML.SubElement(days_tag, day_tag_text)
mapping = [("", "day", day_no), (day, "selected", False)]
helpers.convert_mapping_to_xml(
day_tag, inp_days, mapping, fail_required=True
)
mapping = [("use-build-time", "useBuildTime", False)]
helpers.convert_mapping_to_xml(ctag, cdata, mapping, fail_required=True)
elif kind == "execution-node":
ctag.set("class", core_prefix + "NodeCondition")
allowed_nodes_tag = XML.SubElement(ctag, "allowedNodes")
for node in cdata["nodes"]:
mapping = [("", "string", node)]
helpers.convert_mapping_to_xml(
allowed_nodes_tag, cdata, mapping, fail_required=True
)
elif kind == "strings-match":
ctag.set("class", core_prefix + "StringsMatchCondition")
mapping = [
("condition-string1", "arg1", ""),
("condition-string2", "arg2", ""),
("condition-case-insensitive", "ignoreCase", False),
]
helpers.convert_mapping_to_xml(ctag, cdata, mapping, fail_required=True)
elif kind == "current-status":
ctag.set("class", core_prefix + "StatusCondition")
wr = XML.SubElement(ctag, "worstResult")
wr_name = cdata.get("condition-worst", "SUCCESS")
if wr_name not in hudson_model.THRESHOLDS:
raise InvalidAttributeError(
"condition-worst", wr_name, hudson_model.THRESHOLDS.keys()
)
wr_threshold = hudson_model.THRESHOLDS[wr_name]
mapping = [
("name", "name", None),
("ordinal", "ordinal", None),
("color", "color", "color"),
("complete", "completeBuild", None),
]
helpers.convert_mapping_to_xml(
wr, wr_threshold, mapping, fail_required=True
)
br = XML.SubElement(ctag, "bestResult")
br_name = cdata.get("condition-best", "SUCCESS")
if br_name not in hudson_model.THRESHOLDS:
raise InvalidAttributeError(
"condition-best", br_name, hudson_model.THRESHOLDS.keys()
)
br_threshold = hudson_model.THRESHOLDS[br_name]
mapping = [
("name", "name", None),
("ordinal", "ordinal", None),
("color", "color", "color"),
("complete", "completeBuild", None),
]
helpers.convert_mapping_to_xml(
br, br_threshold, mapping, fail_required=True
)
elif kind == "shell":
ctag.set(
"class",
"org.jenkins_ci.plugins.run_condition.contributed." "ShellCondition",
)
mapping = [("condition-command", "command", "")]
helpers.convert_mapping_to_xml(ctag, cdata, mapping, fail_required=True)
elif kind == "windows-shell":
ctag.set(
"class",
"org.jenkins_ci.plugins.run_condition.contributed."
"BatchFileCondition",
)
mapping = [("condition-command", "command", "")]
helpers.convert_mapping_to_xml(ctag, cdata, mapping, fail_required=True)
elif kind == "file-exists" or kind == "files-match":
if kind == "file-exists":
ctag.set("class", core_prefix + "FileExistsCondition")
mapping = [("condition-filename", "file", None)]
helpers.convert_mapping_to_xml(ctag, cdata, mapping, fail_required=True)
else:
ctag.set("class", core_prefix + "FilesMatchCondition")
XML.SubElement(ctag, "includes").text = ",".join(
cdata.get("include-pattern", "")
)
XML.SubElement(ctag, "excludes").text = ",".join(
cdata.get("exclude-pattern", "")
)
basedir_class_prefix = (
"org.jenkins_ci.plugins.run_condition." "common.BaseDirectory$"
)
basedir_classes = {
"workspace": basedir_class_prefix + "Workspace",
"artifact-directory": basedir_class_prefix + "ArtifactsDir",
"jenkins-home": basedir_class_prefix + "JenkinsHome",
}
basedir = cdata.get("condition-basedir", "workspace")
if basedir not in basedir_classes:
raise InvalidAttributeError(
"condition-basedir", basedir, basedir_classes
)
XML.SubElement(ctag, "baseDir").set("class", basedir_classes[basedir])
elif kind == "num-comp":
ctag.set("class", core_prefix + "NumericalComparisonCondition")
mapping = [("lhs", "lhs", None), ("rhs", "rhs", None)]
helpers.convert_mapping_to_xml(ctag, cdata, mapping, fail_required=True)
comp_class_prefix = core_prefix + "NumericalComparisonCondition$"
comp_classes = {
"less-than": comp_class_prefix + "LessThan",
"greater-than": comp_class_prefix + "GreaterThan",
"equal": comp_class_prefix + "EqualTo",
"not-equal": comp_class_prefix + "NotEqualTo",
"less-than-equal": comp_class_prefix + "LessThanOrEqualTo",
"greater-than-equal": comp_class_prefix + "GreaterThanOrEqualTo",
}
comp = cdata.get("comparator", "less-than")
if comp not in comp_classes:
raise InvalidAttributeError("comparator", comp, comp_classes)
XML.SubElement(ctag, "comparator").set("class", comp_classes[comp])
elif kind == "regex-match":
ctag.set("class", core_prefix + "ExpressionCondition")
mapping = [("regex", "expression", ""), ("label", "label", "")]
helpers.convert_mapping_to_xml(ctag, cdata, mapping, fail_required=True)
elif kind == "time":
ctag.set("class", core_prefix + "TimeCondition")
mapping = [
("earliest-hour", "earliestHours", "09"),
("earliest-min", "earliestMinutes", "00"),
("latest-hour", "latestHours", "17"),
("latest-min", "latestMinutes", "30"),
("use-build-time", "useBuildTime", False),
]
helpers.convert_mapping_to_xml(ctag, cdata, mapping, fail_required=True)
elif kind == "not":
ctag.set("class", logic_prefix + "Not")
try:
notcondition = cdata["condition-operand"]
except KeyError:
raise MissingAttributeError("condition-operand")
build_condition(notcondition, ctag, "condition")
elif kind == "and" or "or":
if kind == "and":
ctag.set("class", logic_prefix + "And")
else:
ctag.set("class", logic_prefix + "Or")
conditions_tag = XML.SubElement(ctag, "conditions")
container_tag_text = (
"org.jenkins__ci.plugins.run__condition." "logic.ConditionContainer"
)
try:
conditions_list = cdata["condition-operands"]
except KeyError:
raise MissingAttributeError("condition-operands")
for condition in conditions_list:
conditions_container_tag = XML.SubElement(
conditions_tag, container_tag_text
)
build_condition(condition, conditions_container_tag, "condition")
cond_builder_tag = (
"org.jenkinsci.plugins.conditionalbuildstep."
"singlestep.SingleConditionalBuilder"
)
cond_builders_tag = (
"org.jenkinsci.plugins.conditionalbuildstep." "ConditionalBuilder"
)
# A builder could be a macro, so it's required to create builders at first
# to set `has_multiple_steps` flag correctly.
edited_nodes = [
edited_node
for step in data["steps"]
for edited_node in create_builders(registry, step)
]
has_multiple_steps = len(edited_nodes) > 1
if has_multiple_steps:
root_tag = XML.SubElement(xml_parent, cond_builders_tag)
steps_parent = XML.SubElement(root_tag, "conditionalbuilders")
condition_tag = "runCondition"
else:
root_tag = XML.SubElement(xml_parent, cond_builder_tag)
steps_parent = root_tag
condition_tag = "condition"
build_condition(data, root_tag, condition_tag)
evaluation_classes_pkg = "org.jenkins_ci.plugins.run_condition"
evaluation_classes = {
"fail": evaluation_classes_pkg + ".BuildStepRunner$Fail",
"mark-unstable": evaluation_classes_pkg + ".BuildStepRunner$Unstable",
"run-and-mark-unstable": evaluation_classes_pkg
+ ".BuildStepRunner$RunUnstable",
"run": evaluation_classes_pkg + ".BuildStepRunner$Run",
"dont-run": evaluation_classes_pkg + ".BuildStepRunner$DontRun",
}
evaluation_class = evaluation_classes[data.get("on-evaluation-failure", "fail")]
XML.SubElement(root_tag, "runner").set("class", evaluation_class)
for edited_node in edited_nodes:
if not has_multiple_steps:
edited_node.set("class", edited_node.tag)
edited_node.tag = "buildStep"
steps_parent.append(edited_node)
def maven_builder(registry, xml_parent, data):
"""yaml: maven-builder
Execute Maven3 builder
Allows your build jobs to deploy artifacts automatically to Artifactory.
Requires the Jenkins `Artifactory Plugin
<https://www.jfrog.com/confluence/display/RTF/Jenkins+Artifactory+Plug-in>`_.
:arg str name: Name of maven installation from the configuration (required)
:arg str pom: Location of pom.xml (default 'pom.xml')
:arg str goals: Goals to execute (required)
:arg str maven-opts: Additional options for maven (default '')
Example:
.. literalinclude:: /../../tests/builders/fixtures/maven-builder001.yaml
:language: yaml
"""
maven = XML.SubElement(xml_parent, "org.jfrog.hudson.maven3.Maven3Builder")
mapping = [
("name", "mavenName", None),
("goals", "goals", None),
("pom", "rootPom", "pom.xml"),
("maven-opts", "mavenOpts", ""),
]
helpers.convert_mapping_to_xml(maven, data, mapping, fail_required=True)
def jira_issue_updater(registry, xml_parent, data):
"""yaml: jenkins-jira-issue-updater
Updates issues in Atlassian JIRA as part of a Jenkins job.
Requires the Jenkins :jenkins-plugins:`Jira Issue Updater Plugin
<jenkins-jira-issue-updater>`.
:arg str base-url: The base url of the rest API. (default '')
:arg str username: The Jira username (required)
:arg str password: The Jira password (required)
:arg str jql: The JQL used to select the issues to update. (required)
:arg str workflow: The Name of the workflow action to be executed.
(default '')
:arg str comment: The Jira comment to be added. (default '')
:arg str custom-Id: The Jira custom field to be edited. (default '')
:arg str custom-value: Jira custom field value. (default '')
:arg bool fail-if-error: Fail this build if JQL returns error.
((default false)
:arg bool fail-if-no-match: Fail this build if no issues are matched.
(default false)
:arg bool fail-if-no-connection: Fail this build if can't connect to Jira.
(default false)
Minimal Example:
.. literalinclude::
/../../tests/builders/fixtures/jenkins-jira-issue-updater-minimal.yaml
:language: yaml
Full Example:
.. literalinclude::
/../../tests/builders/fixtures/jenkins-jira-issue-updater-full.yaml
:language: yaml
"""
issue_updater = XML.SubElement(
xml_parent, "info.bluefloyd.jenkins." "IssueUpdatesBuilder"
)
issue_updater.set("plugin", "jenkins-jira-issue-updater")
mapping = [
("base-url", "restAPIUrl", ""),
("username", "userName", None),
("password", "password", None),
("jql", "jql", None),
("workflow", "workflowActionName", ""),
("comment", "comment", ""),
("custom-Id", "customFieldId", ""),
("custom-value", "customFieldValue", ""),
("fail-if-error", "failIfJqlFails", False),
("fail-if-no-match", "failIfNoIssuesReturned", False),
("fail-if-no-connection", "failIfNoJiraConnection", False),
]
helpers.convert_mapping_to_xml(issue_updater, data, mapping, fail_required=True)
def maven_target(registry, xml_parent, data):
"""yaml: maven-target
Execute top-level Maven targets.
Requires the Jenkins :jenkins-plugins:`Config File Provider Plugin
<config-file-provider>` for the Config File Provider "settings"
and "global-settings" config.
:arg str goals: Goals to execute
:arg str properties: Properties for maven, can have multiples
:arg str pom: Location of pom.xml (default 'pom.xml')
:arg bool private-repository: Use private maven repository for this
job (default false)
:arg str maven-version: Installation of maven which should be used
(optional)
:arg str java-opts: java options for maven, can have multiples,
must be in quotes (optional)
:arg str settings: Path to use as user settings.xml
It is possible to provide a ConfigFileProvider settings file, such as
see CFP Example below. (optional)
:arg str settings-type: Type of settings file file|cfp. (default file)
:arg str global-settings: Path to use as global settings.xml
It is possible to provide a ConfigFileProvider settings file, such as
see CFP Example below. (optional)
:arg str global-settings-type: Type of settings file file|cfp. (default
file)
Example:
.. literalinclude:: /../../tests/builders/fixtures/maven-target-doc.yaml
:language: yaml
CFP Example:
.. literalinclude:: /../../tests/builders/fixtures/maven-target002.yaml
:language: yaml
"""
maven = XML.SubElement(xml_parent, "hudson.tasks.Maven")
XML.SubElement(maven, "targets").text = data["goals"]
prop_string = "\n".join(data.get("properties", []))
XML.SubElement(maven, "properties").text = prop_string
mapping = [
("maven-version", "mavenName", None),
("pom", "pom", None),
("private-repository", "usePrivateRepository", False),
]
helpers.convert_mapping_to_xml(maven, data, mapping, fail_required=False)
if "java-opts" in data:
javaoptions = " ".join(data.get("java-opts", []))
XML.SubElement(maven, "jvmOptions").text = javaoptions
helpers.config_file_provider_settings(maven, data)
def multijob(registry, xml_parent, data):
"""yaml: multijob
Define a multijob phase.
Requires the Jenkins :jenkins-plugins:`Multijob Plugin
<jenkins-multijob-plugin>`.
This builder may only be used in
:py:class:`jenkins_jobs.modules.project_multijob.MultiJob` projects.
:arg str name: MultiJob phase name
:arg str condition: when to trigger the other job.
Can be: 'SUCCESSFUL', 'UNSTABLE', 'COMPLETED', 'FAILURE', 'ALWAYS'.
(default 'SUCCESSFUL')
:arg str execution-type: Define how to run jobs in a phase:
sequentially or parallel.
Can be: 'PARALLEL', 'SEQUENTIALLY'
(default 'PARALLEL')
:arg list projects: list of projects to include in the MultiJob phase
:Project:
* **name** (`str`) -- Project name
* **alias** (`str`) -- Project alias, which will be shown
in MultiJob Overview. Helpful when working with the same
project multiple times with different configurations
* **current-parameters** (`bool`) -- Pass current build
parameters to the other job (default false)
* **node-label-name** (`str`) -- Define a list of nodes
on which the job should be allowed to be executed on.
Requires NodeLabel Parameter Plugin (optional)
* **node-label** (`str`) -- Define a label
of 'Restrict where this project can be run' on the fly.
Requires NodeLabel Parameter Plugin (optional)
* **node-parameters** (`bool`) -- Use the same Node for
the triggered builds that was used for this build. (optional)
* **git-revision** (`bool`) -- Pass current git-revision
to the other job (default false)
* **property-file** (`str`) -- Pass properties from file
to the other job (optional)
* **predefined-parameters** (`str`) -- Pass predefined
parameters to the other job (optional)
* **abort-all-job** (`bool`) -- Kill allsubs job and the phase job,
if this subjob is killed (default false)
* **aggregate-results** (`bool`) -- Aggregate test results.
(default false)
* **enable-condition** (`str`) -- Condition to run the
job in groovy script format (optional)
* **kill-phase-on** (`str`) -- Stop the phase execution
on specific job status. Can be 'FAILURE', 'UNSTABLE',
'NEVER'. (optional)
* **restrict-matrix-project** (`str`) -- Filter that
restricts the subset of the combinations that the
downstream project will run (optional)
* **retry** (`dict`): Enable retry strategy (optional)
:retry:
* **max-retry** (`int`) -- Max number of retries
(default 0)
* **strategy-path** (`str`) -- Parsing rules path
(required)
Example:
.. literalinclude:: /../../tests/builders/fixtures/multibuild.yaml
:language: yaml
"""
builder = XML.SubElement(
xml_parent, "com.tikal.jenkins.plugins.multijob." "MultiJobBuilder"
)
conditions_available = ("SUCCESSFUL", "UNSTABLE", "COMPLETED", "FAILURE", "ALWAYS")
job_execution_type_available = ("PARALLEL", "SEQUENTIALLY")
mapping = [
("name", "phaseName", None),
("condition", "continuationCondition", "SUCCESSFUL", conditions_available),
("execution-type", "executionType", "PARALLEL", job_execution_type_available),
]
helpers.convert_mapping_to_xml(builder, data, mapping, fail_required=True)
phaseJobs = XML.SubElement(builder, "phaseJobs")
kill_status_list = ("FAILURE", "UNSTABLE", "NEVER")
for project in data.get("projects", []):
phaseJob = XML.SubElement(
phaseJobs, "com.tikal.jenkins.plugins." "multijob.PhaseJobsConfig"
)
mapping = [
("name", "jobName", None),
# Pass through the current build params
("current-parameters", "currParams", False),
]
helpers.convert_mapping_to_xml(phaseJob, project, mapping, fail_required=True)
# Pass through other params
if project.get("alias"):
mapping = [("alias", "jobAlias", None)]
helpers.convert_mapping_to_xml(
phaseJob, project, mapping, fail_required=True
)
configs = XML.SubElement(phaseJob, "configs")
nodeLabelName = project.get("node-label-name")
nodeLabel = project.get("node-label")
if nodeLabelName and nodeLabel:
node = XML.SubElement(
configs,
"org.jvnet.jenkins.plugins.nodelabelparameter."
"parameterizedtrigger.NodeLabelBuildParameter",
)
mapping = [("", "name", nodeLabelName), ("", "nodeLabel", nodeLabel)]
helpers.convert_mapping_to_xml(node, project, mapping, fail_required=True)
# Node parameter
if project.get("node-parameters", False):
XML.SubElement(
configs, "hudson.plugins.parameterizedtrigger." "NodeParameters"
)
# Git Revision
if project.get("git-revision", False):
param = XML.SubElement(
configs, "hudson.plugins.git." "GitRevisionBuildParameters"
)
mapping = [("", "combineQueuedCommits", False)]
helpers.convert_mapping_to_xml(param, project, mapping, fail_required=True)
# Properties File
properties_file = project.get("property-file", False)
if properties_file:
param = XML.SubElement(
configs, "hudson.plugins.parameterizedtrigger." "FileBuildParameters"
)
mapping = [
("", "propertiesFile", properties_file),
("", "failTriggerOnMissing", True),
]
helpers.convert_mapping_to_xml(param, project, mapping, fail_required=True)
# Predefined Parameters
predefined_parameters = project.get("predefined-parameters", False)
if predefined_parameters:
param = XML.SubElement(
configs,
"hudson.plugins.parameterizedtrigger." "PredefinedBuildParameters",
)
mapping = [("", "properties", predefined_parameters)]
helpers.convert_mapping_to_xml(param, project, mapping, fail_required=True)
mapping = [
("abort-all-job", "abortAllJob", False),
("aggregate-results", "aggregatedTestResults", False),
]
helpers.convert_mapping_to_xml(phaseJob, project, mapping, fail_required=True)
# Retry job
retry = project.get("retry", False)
if retry:
max_retry = retry.get("max-retry", 0)
mapping = [
("strategy-path", "parsingRulesPath", None),
("", "maxRetries", int(max_retry)),
("", "enableRetryStrategy", True),
]
helpers.convert_mapping_to_xml(phaseJob, retry, mapping, fail_required=True)
else:
XML.SubElement(phaseJob, "enableRetryStrategy").text = "false"
# Restrict matrix jobs to a subset
if project.get("restrict-matrix-project") is not None:
subset = XML.SubElement(
configs,
"hudson.plugins.parameterizedtrigger."
"matrix.MatrixSubsetBuildParameters",
)
mapping = [("restrict-matrix-project", "filter", None)]
helpers.convert_mapping_to_xml(subset, project, mapping, fail_required=True)
# Enable Condition
enable_condition = project.get("enable-condition")
if enable_condition is not None:
mapping = [
("", "enableCondition", True),
("", "condition", enable_condition),
]
helpers.convert_mapping_to_xml(
phaseJob, project, mapping, fail_required=True
)
# Kill phase on job status
kill_status = project.get("kill-phase-on")
if kill_status is not None:
kill_status = kill_status.upper()
mapping = [
("", "killPhaseOnJobResultCondition", kill_status, kill_status_list)
]
helpers.convert_mapping_to_xml(
phaseJob, project, mapping, fail_required=True
)
def config_file_provider(registry, xml_parent, data):
"""yaml: config-file-provider
Provide configuration files (i.e., settings.xml for maven etc.)
which will be copied to the job's workspace.
Requires the Jenkins :jenkins-plugins:`Config File Provider Plugin
<config-file-provider>`.
:arg list files: List of managed config files made up of three
parameters
:files:
* **file-id** (`str`) -- The identifier for the managed config
file
* **target** (`str`) -- Define where the file should be created
(default '')
* **variable** (`str`) -- Define an environment variable to be
used (default '')
* **replace-tokens** (`bool`) -- Replace tokens in config file. For
example "password: ${PYPI_JENKINS_PASS}" will be replaced with
the global variable configured in Jenkins.
Full Example:
.. literalinclude::
../../tests/builders/fixtures/config-file-provider-full.yaml
:language: yaml
Minimal Example:
.. literalinclude::
../../tests/builders/fixtures/config-file-provider-minimal.yaml
:language: yaml
"""
cfp = XML.SubElement(
xml_parent, "org.jenkinsci.plugins.configfiles.builder." "ConfigFileBuildStep"
)
cfp.set("plugin", "config-file-provider")
helpers.config_file_provider_builder(cfp, data)
def grails(registry, xml_parent, data):
"""yaml: grails
Execute a grails build step.
Requires the :jenkins-plugins:`Jenkins Grails Plugin <grails>`.
:arg bool use-wrapper: Use a grails wrapper (default false)
:arg str name: Select a grails installation to use (default '(Default)')
:arg bool force-upgrade: Run 'grails upgrade --non-interactive'
first (default false)
:arg bool non-interactive: append --non-interactive to all build targets
(default false)
:arg str targets: Specify target(s) to run separated by spaces (required)
:arg str server-port: Specify a value for the server.port system
property (default '')
:arg str work-dir: Specify a value for the grails.work.dir system
property (default '')
:arg str project-dir: Specify a value for the grails.project.work.dir
system property (default '')
:arg str base-dir: Specify a path to the root of the Grails
project (default '')
:arg str properties: Additional system properties to set (default '')
:arg bool plain-output: append --plain-output to all build targets
(default false)
:arg bool stack-trace: append --stack-trace to all build targets
(default false)
:arg bool verbose: append --verbose to all build targets
(default false)
:arg bool refresh-dependencies: append --refresh-dependencies to all
build targets (default false)
Full Example:
.. literalinclude:: ../../tests/builders/fixtures/grails-full.yaml
:language: yaml
Minimal Example:
.. literalinclude:: ../../tests/builders/fixtures/grails-minimal.yaml
:language: yaml
"""
grails = XML.SubElement(xml_parent, "com.g2one.hudson.grails." "GrailsBuilder")
grails.set("plugin", "grails")
mappings = [
("targets", "targets", None),
("name", "name", "(Default)"),
("work-dir", "grailsWorkDir", ""),
("project-dir", "projectWorkDir", ""),
("base-dir", "projectBaseDir", ""),
("server-port", "serverPort", ""),
("properties", "properties", ""),
("force-upgrade", "forceUpgrade", False),
("non-interactive", "nonInteractive", False),
("use-wrapper", "useWrapper", False),
("plain-output", "plainOutput", False),
("stack-trace", "stackTrace", False),
("verbose", "verbose", False),
("refresh-dependencies", "refreshDependencies", False),
]
helpers.convert_mapping_to_xml(grails, data, mappings, fail_required=True)
def sbt(registry, xml_parent, data):
"""yaml: sbt
Execute a sbt build step.
Requires the Jenkins :jenkins-plugins:`Sbt Plugin <sbt>`.
:arg str name: Select a sbt installation to use. If no name is
provided, the first in the list of defined SBT builders will be
used. (default to first in list)
:arg str jvm-flags: Parameters to pass to the JVM (default '')
:arg str actions: Select the sbt tasks to execute (default '')
:arg str sbt-flags: Add flags to SBT launcher
(default '-Dsbt.log.noformat=true')
:arg str subdir-path: Path relative to workspace to run sbt in
(default '')
Example:
.. literalinclude:: ../../tests/builders/fixtures/sbt.yaml
:language: yaml
"""
sbt = XML.SubElement(xml_parent, "org.jvnet.hudson.plugins." "SbtPluginBuilder")
mappings = [
("name", "name", ""),
("jvm-flags", "jvmFlags", ""),
("sbt-flags", "sbtFlags", "-Dsbt.log.noformat=true"),
("actions", "actions", ""),
("subdir-path", "subdirPath", ""),
]
helpers.convert_mapping_to_xml(sbt, data, mappings, fail_required=True)
def critical_block_start(registry, xml_parent, data):
"""yaml: critical-block-start
Designate the start of a critical block. Must be used in conjunction with
critical-block-end.
Must also add a build wrapper (exclusion), specifying the resources that
control the critical block. Otherwise, this will have no effect.
Requires the Jenkins :jenkins-plugins:`Exclusion Plugin <Exclusion>`.
Example:
.. literalinclude::
../../tests/yamlparser/fixtures/critical_block_complete001.yaml
:language: yaml
"""
cbs = XML.SubElement(
xml_parent, "org.jvnet.hudson.plugins.exclusion.CriticalBlockStart"
)
cbs.set("plugin", "Exclusion")
def critical_block_end(registry, xml_parent, data):
"""yaml: critical-block-end
Designate the end of a critical block. Must be used in conjunction with
critical-block-start.
Must also add a build wrapper (exclusion), specifying the resources that
control the critical block. Otherwise, this will have no effect.
Requires the Jenkins :jenkins-plugins:`Exclusion Plugin <Exclusion>`.
Example:
.. literalinclude::
../../tests/yamlparser/fixtures/critical_block_complete001.yaml
:language: yaml
"""
cbs = XML.SubElement(
xml_parent, "org.jvnet.hudson.plugins.exclusion.CriticalBlockEnd"
)
cbs.set("plugin", "Exclusion")
def publish_over_ssh(registry, xml_parent, data):
"""yaml: publish-over-ssh
Send files or execute commands over SSH.
Requires the Jenkins :jenkins-plugins:`Publish over SSH Plugin
<publish-over-ssh>`.
:arg str site: name of the ssh site
:arg str target: destination directory
:arg bool target-is-date-format: whether target is a date format. If true,
raw text should be quoted (default false)
:arg bool clean-remote: should the remote directory be deleted before
transferring files (default false)
:arg str source: source path specifier
:arg str command: a command to execute on the remote server (optional)
:arg int timeout: timeout in milliseconds for the Exec command (optional)
:arg bool use-pty: run the exec command in pseudo TTY (default false)
:arg str excludes: excluded file pattern (optional)
:arg str remove-prefix: prefix to remove from uploaded file paths
(optional)
:arg bool fail-on-error: fail the build if an error occurs (default false)
Example:
.. literalinclude:: /../../tests/builders/fixtures/publish-over-ssh.yaml
:language: yaml
"""
ssh(registry, xml_parent, data)
def publish_over_cifs(registry, xml_parent, data):
"""yaml: publish-over-cifs
Upload files via CIFS.
Requires the Jenkins :jenkins-plugins:`Publish over CIFS Plugin
<publish-over-cifs>`.
:arg str site: name of the ssh site
:arg str target: destination directory
:arg bool target-is-date-format: whether target is a date format. If true,
raw text should be quoted (default false)
:arg bool clean-remote: should the remote directory be deleted before
transferring files (default false)
:arg str source: source path specifier
:arg str excludes: excluded file pattern (optional)
:arg str remove-prefix: prefix to remove from uploaded file paths
(optional)
:arg bool fail-on-error: fail the build if an error occurs (default false)
:arg bool flatten: only create files on the server, don't create
directories (default false)
Example:
.. literalinclude:: /../../tests/builders/fixtures/publish-over-cifs.yaml
:language: yaml
"""
cifs(registry, xml_parent, data)
def saltstack(parser, xml_parent, data):
"""yaml: saltstack
Send a message to Salt API.
Requires the Jenkins :jenkins-plugins:`saltstack plugin <saltstack>`.
:arg str servername: Salt master server name (required)
:arg str authtype: Authentication type ('pam' or 'ldap', default 'pam')
:arg str credentials: Credentials ID for which to authenticate to Salt
master (required)
:arg str target: Target minions (default '')
:arg str targettype: Target type ('glob', 'pcre', 'list', 'grain',
'pillar', 'nodegroup', 'range', or 'compound', default 'glob')
:arg str function: Function to execute (default '')
:arg str arguments: Salt function arguments (default '')
:arg str kwarguments: Salt keyword arguments (default '')
:arg bool saveoutput: Save Salt return data into environment variable
(default false)
:arg str clientinterface: Client interface type ('local', 'local-batch',
or 'runner', default 'local')
:arg bool wait: Wait for completion of command (default false)
:arg str polltime: Number of seconds to wait before polling job completion
status (default '')
:arg str batchsize: Salt batch size, absolute value or %-age (default 100%)
:arg str mods: Mods to runner (default '')
:arg bool setpillardata: Set Pillar data (default false)
:arg str pillarkey: Pillar key (default '')
:arg str pillarvalue: Pillar value (default '')
Minimal Example:
.. literalinclude:: ../../tests/builders/fixtures/saltstack-minimal.yaml
:language: yaml
Full Example:
.. literalinclude:: ../../tests/builders/fixtures/saltstack-full.yaml
:language: yaml
"""
saltstack = XML.SubElement(xml_parent, "com.waytta.SaltAPIBuilder")
supported_auth_types = ["pam", "ldap"]