/cicd-tooling-skills:jenkins-groovy-scripting-best-practicesfrom cicd-tooling-skills
Covers writing safe, testable Groovy inside Jenkins pipelines and shared libraries, including sandbox approval, unit testing with JenkinsPipelineUnit, CPS quirks, and serialization pitfalls.
Ships in cicd-tooling-skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Jenkins Pipeline (both per-repo Jenkinsfiles and shared libraries) is
written in Groovy, but it does not run like ordinary Groovy: it executes
under the Groovy sandbox (a security boundary that blocks arbitrary
Java/Groovy method calls unless explicitly approved) and under CPS
(Continuation-Passing Style) transformation (so pipelines can pause/
resume across Jenkins restarts), both of which produce failure modes that
look like bugs in your code but are actually artifacts of the execution
model. This skill covers the sandbox/script-approval workflow, how to unit
test shared library Groovy without a running Jenkins controller, and the
specific Groovy/CPS pitfalls (closures capturing this, non-serializable
state, @NonCPS usage) that recur in pipeline code.
org.jenkinsci.plugins.scriptsecurity. sandbox.RejectedAccessException: Scripts not permitted to use ....Jenkinsfile's script {} block or
in a shared library's vars//src/ files (see
jenkins-declarative-pipeline-per-repo
and
jenkins-centralized-shared-library
for where this code lives).NotSerializableException, unexpectedly re-executed code after
a controller restart, or a closure that behaves differently than plain
Groovy would suggest.@NonCPS-annotated.RejectedAccessException
must request approval, not self-approve unless they hold that role).lesfurets:jenkins-pipeline-unit) added as a test dependency, and a
test framework (JUnit 5 or Spock) to drive it.Understand what the sandbox blocks. By default, Pipeline scripts run in a sandbox that only allows a pre-approved allowlist of methods/ constructors/static methods. Calling an unapproved method (e.g. a non-whitelisted Java standard library method, or certain Groovy metaprogramming) throws:
org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException:
Scripts not permitted to use method java.lang.String.format java.lang.String java.lang.Object[]
This is not a bug in your Groovy — it's the sandbox doing its job.
Approve the specific signature, don't disable the sandbox. As an admin, go to Manage Jenkins → In-process Script Approval, review the pending signature request, and approve only that specific method signature if it's legitimately needed and safe:
method java.lang.String format java.lang.String java.lang.Object[]
Never check "Process as though script requests are outside the sandbox" / mark the whole Jenkinsfile as unsandboxed as a workaround — this defeats the security control across every use of that Jenkinsfile/library going forward and is a real security regression, not a convenience.
Prefer Pipeline-provided steps over raw Java/Groovy APIs where an
equivalent step exists (readJSON/writeJSON from the Pipeline
Utility Steps plugin instead of groovy.json.JsonSlurper directly,
sh(script: ..., returnStdout: true) instead of ProcessBuilder) —
these are already sandbox-approved and portable across controllers,
avoiding a per-controller approval request.
Mark pure-computation helper methods @NonCPS when they don't call
pipeline steps and don't need to survive a controller restart mid-
execution — this avoids CPS transformation overhead and sidesteps CPS
limitations on certain Groovy constructs (e.g. some collection methods
with closures):
@NonCPS
def parseVersion(String tag) {
def m = (tag =~ /^v(\d+)\.(\d+)\.(\d+)$/)
return m ? [major: m[0][1] as int, minor: m[0][2] as int, patch: m[0][3] as int] : null
}
Never call a pipeline step (sh, sleep, input) from inside a
@NonCPS method — it will fail or behave incorrectly, since @NonCPS
methods run outside the CPS interpreter that pipeline steps depend on.
Implement Serializable on any src/ class whose instances are held
across pipeline steps, since Jenkins periodically serializes the
pipeline's execution state to disk for durability across restarts:
class DeployTarget implements Serializable {
String environment
String region
}
A class held in a pipeline variable that isn't serializable throws
NotSerializableException at the first checkpoint after it's used.
Unit test shared library code with JenkinsPipelineUnit instead of only validating by pushing to a real Jenkins and watching a build:
// test/groovy/NodeServicePipelineTest.groovy
import com.lesfurets.jenkins.unit.BasePipelineTest
import org.junit.Before
import org.junit.Test
import static org.junit.Assert.assertTrue
class NodeServicePipelineTest extends BasePipelineTest {
@Override
@Before
void setUp() throws Exception {
super.setUp()
}
@Test
void 'fails fast when serviceName is missing'() {
def script = loadScript('vars/nodeServicePipeline.groovy')
def threw = false
try {
script.call([:])
} catch (Exception e) {
threw = true
assertTrue(e.message.contains("'serviceName' is required"))
}
assertTrue(threw)
}
}
Run via ./gradlew test (or Maven equivalent) in CI for the shared
library repo itself — this is what makes the library's own CI (see step
6 of
jenkins-centralized-shared-library)
meaningful rather than just a syntax check.
Avoid closures that implicitly capture non-serializable pipeline
state across step boundaries (e.g. capturing the steps context
object itself in a long-lived closure stored in a class field) — pass
the script/this reference explicitly into helper methods instead of
relying on implicit closure capture, which is both clearer and avoids
subtle serialization failures.
@NonCPS methods pure (no pipeline steps, no side effects on shared
mutable state) — they exist for CPU-bound parsing/computation, not
orchestration.vars/*.groovy entry point's parameter
validation and branching logic using JenkinsPipelineUnit; this catches
regressions before a library version tag goes out to dozens of
consumers.vars/*.groovy file that
has grown to hundreds of lines of nested if/switch logic is a sign
the branching belongs in tested src/ classes instead.error "nodeServicePipeline: expected config.serviceName, got: ${config}") rather than letting a raw
NullPointerException surface — pipeline consumers debugging a shared
library failure have no access to the library's source by default.Symptom:
RejectedAccessException: Scripts not permitted to use staticMethod java.util.UUID randomUUID (or similar) appears the first time a new
helper method runs, even though the same Groovy runs fine in a plain
groovy script outside Jenkins.
Fix: This is expected — the sandbox allowlist is independent of
whether the code is "valid Groovy." Request/approve the specific
signature in In-process Script Approval, or replace the call with an
already-approved Pipeline Utility Steps equivalent.
Symptom: A shared library's helper method that calls sh(...)
fails or hangs when marked @NonCPS.
Fix: @NonCPS methods run outside the CPS interpreter and cannot
call pipeline steps; remove the annotation from any method that invokes
sh, sleep, input, or other steps — reserve @NonCPS strictly for
pure computation.
Symptom: java.io.NotSerializableException thrown partway through a
long-running pipeline, often after several stages have already
succeeded.
Fix: A class instance held in a pipeline-scoped variable across
steps must implement Serializable; audit src/ classes referenced
from vars/*.groovy and add implements Serializable, or mark
genuinely non-serializable fields (e.g. a network client) transient
and re-initialize them lazily.
Symptom: After a Jenkins controller restart, a step appears to re-run from an earlier point, producing duplicate side effects (e.g. a notification sent twice). Fix: This is CPS checkpoint/resume behavior interacting with non-idempotent side effects; make steps with external side effects idempotent where possible, or restructure so the side effect happens once at a clearly-checkpointed boundary rather than inside a loop that could partially replay.
Symptom: A library author "temporarily" enables running the Jenkinsfile without sandbox restrictions to unblock a demo, then it ships that way to production. Fix: This should be flagged as a security regression, not a convenience — running unsandboxed means the pipeline's Groovy has full access to the Jenkins controller's JVM (including credentials store internals); revert to sandboxed execution and go through proper script approval for the specific signatures actually needed.
Scenario: A shared library's vars/nodeServicePipeline.groovy (from
jenkins-centralized-shared-library)
needs a helper to parse a semantic version tag and decide whether a build
is a pre-release, plus a unit test proving the parsing logic works before
it's used by 30 consumer repos.
src/org/example/pipeline/VersionUtil.groovy:
package org.example.pipeline
class VersionUtil implements Serializable {
@NonCPS
static Map parse(String tag) {
def m = (tag =~ /^v(\d+)\.(\d+)\.(\d+)(-rc\.\d+)?$/)
if (!m) {
return null
}
return [
major: m[0][1] as int,
minor: m[0][2] as int,
patch: m[0][3] as int,
isPrerelease: m[0][4] != null
]
}
}
vars/nodeServicePipeline.groovy (excerpt):
script {
def v = org.example.pipeline.VersionUtil.parse(env.GIT_TAG_NAME ?: '')
if (v?.isPrerelease) {
echo "Skipping production deploy for pre-release tag ${env.GIT_TAG_NAME}"
return
}
}
test/groovy/VersionUtilTest.groovy (run in the library's own CI, no
Jenkins controller required):
import org.example.pipeline.VersionUtil
import org.junit.Test
import static org.junit.Assert.assertEquals
import static org.junit.Assert.assertNull
class VersionUtilTest {
@Test
void 'parses a stable version tag'() {
def v = VersionUtil.parse('v1.4.2')
assertEquals(1, v.major)
assertEquals(4, v.minor)
assertEquals(2, v.patch)
assertEquals(false, v.isPrerelease)
}
@Test
void 'flags a release-candidate tag as prerelease'() {
def v = VersionUtil.parse('v2.0.0-rc.1')
assertEquals(true, v.isPrerelease)
}
@Test
void 'returns null for a malformed tag'() {
assertNull(VersionUtil.parse('not-a-version'))
}
}
Because VersionUtil.parse is @NonCPS and does no pipeline I/O, it can
be unit tested as ordinary Groovy/JUnit with no Jenkins controller —
regressions in the tag-parsing regex are caught in the library's own CI
before any of the 30 consumer repos' pipelines run it.
script {} blocks containing this Groovy typically live for a single repo.vars//src/ structure this Groovy code is organized into at org scale.What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
jenkins-pipeline, groovy-sandbox, cps, shared-library, script-approval
13 skills in this plugin
/aws-codepipeline-and-codedeployDesigns AWS CodePipeline stage/action structure and integrates it with CodeDeploy deployment groups and appspec.yml for EC2/on-prem, ECS, or Lambda deploys. Use when the user asks to "set up CodePipeline," "add a CodeDeploy deployment group," "write an appspec.yml," "wire CodePipeline to CodeDeploy," "troubleshoot a stuck/failed CodePipeline action," or "add a manual approval action before an AWS deploy."
/azure-pipelines-yaml-and-multi-stageDesigns Azure Pipelines YAML (azure-pipelines.yml), multi-stage pipelines with environments/approvals, templates for reuse across repos, and self-hosted vs. Microsoft-hosted agent pools. Use when the user asks to "set up Azure Pipelines," "write an azure-pipelines.yml," "add a multi-stage pipeline with approvals," "create a reusable pipeline template," "configure a self-hosted agent pool," or "troubleshoot a stuck/failed Azure DevOps pipeline run."
/bamboo-pipeline-yaml-and-java-specsAuthors Atlassian Bamboo pipeline definitions using either Bamboo Specs (Java DSL, compiled and run to create/update a plan) or Bamboo's YAML specs format, covering plan/job/stage structure and how a Specs definition links to and updates a live Bamboo plan. Use when the user asks to "write a Bamboo Specs plan," "convert our Bamboo plan to code," "add a stage/job to a Bamboo build," "use Bamboo YAML specs," or "troubleshoot a Bamboo Specs plan not updating the linked plan."
/complete-cicd-pipeline-deployment-for-kubernetes-from-scratchBuilds a complete CI/CD pipeline for a Kubernetes-targeted service from an empty repo — source checkout, container image build, SCA/SAST security gates, registry push, and a deploy step that ends at a GitOps handoff (committing a new image tag to a manifests repo) rather than a direct kubectl apply or helm upgrade against the cluster. Use when the user asks to "build a full CI/CD pipeline for Kubernetes from scratch," "set up CI/CD that ends in a GitOps commit, not a cluster deploy," "wire a container build pipeline into Argo CD/Flux," or "go from an empty repo to a Kubernetes service deployed via GitOps end-to-end."
/complete-cicd-pipeline-deployment-for-serverless-from-scratchBuilds a complete CI/CD pipeline for a serverless (AWS Lambda-style) function from an empty repo — source checkout, zip/layer packaging (not a container image), SCA/SAST security gates, package upload, and a SAM/Serverless-Framework/CDK-style deploy step with alias-based canary traffic shifting, distinct from Kubernetes rollout mechanics. Use when the user asks to "build a full CI/CD pipeline for a Lambda function from scratch," "set up serverless CI/CD with canary traffic shifting," "wire SAM/Serverless Framework deploys into a pipeline," or "go from an empty repo to a function deployed with an alias-based canary."
/complete-cicd-pipeline-for-vm-based-workloads-from-scratchBuilds a complete CI/CD pipeline for a VM-based workload from an empty repo — source checkout, build, immutable machine-image baking (Packer-style AMI, not a container image or a zip), SCA/SAST security gates, and a deploy step that's either a blue-green instance-group swap or a config-management push (Ansible) to existing long-lived VMs, distinct from both container and serverless deploy mechanics. Use when the user asks to "build a full CI/CD pipeline for EC2/VM workloads from scratch," "bake an AMI in CI and roll it out blue-green," "push Ansible-managed config to existing VMs from a pipeline," or "go from an empty repo to a VM fleet deployed with a golden image and Auto Scaling Group swap."
npx claudepluginhub selvarajmurugesan90/ops-engineering-skills --plugin cicd-tooling-skillsOther plugins' skills for the same job