Skip to content
Back to skills

Jenkins Job Dsl Jcasc

ASecurity

Jenkins Job DSL API and Configuration as Code (JCasC) integration for programmatic job management. Covers Job DSL seed job generation, JCasC inline DSL to bypass Groovy Sandbox approval, multibranchPipelineJob and organizationFolder authoring, SCM branch source trait configuration (BranchDiscoveryTrait, OriginPullRequestDiscoveryTrait, ForkPullRequestDiscoveryTrait with TrustPermission/TrustContributors/TrustNobody), configure block for raw XML manipulation, and security best practices (crede...

  • 2 stars
  • 0 votes
  • 0 copies
  • 3 views
  • Added September 29, 2026
ai-agentsrustgoshellnodetestinggitapici/cdsecurity

Works with

  • api

Security analysis

A100/100

Scanned September 29, 2026

npx -y skills add talkops-ai/opscode --skill jenkins-job-dsl-jcasc --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Jenkins Job Dsl Jcasc?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Jenkins Job Dsl Jcasc
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/talkops-ai-jenkins-job-dsl-jcasc/badge)](https://www.skillsdirectory.com/skills/talkops-ai-jenkins-job-dsl-jcasc)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: jenkins-job-dsl-jcasc
description: >
  Jenkins Job DSL API and Configuration as Code (JCasC) integration for programmatic
  job management. Covers Job DSL seed job generation, JCasC inline DSL to bypass
  Groovy Sandbox approval, multibranchPipelineJob and organizationFolder authoring,
  SCM branch source trait configuration (BranchDiscoveryTrait, OriginPullRequestDiscoveryTrait,
  ForkPullRequestDiscoveryTrait with TrustPermission/TrustContributors/TrustNobody),
  configure block for raw XML manipulation, and security best practices (credentials()
  binding, no Jenkins.instance access, no controller execution). Use when:
  (1) generating Job DSL Groovy scripts for automated job creation, (2) integrating
  Job DSL inline in JCasC YAML to bypass sandbox approvals, (3) configuring
  multibranch pipeline jobs with branch and PR discovery traits, (4) setting up
  GitHub/Bitbucket organization folders, (5) using the configure block for raw
  XML trait manipulation, or (6) enforcing CI/CD security best practices. Do NOT
  use for pipeline authoring (use jenkins-pipeline-generation), shared libraries
  (use jenkins-shared-libraries), or unit testing (use jenkins-pipeline-testing).
license: MIT
compatibility: designed for opscode
---

# Jenkins Job DSL & Configuration as Code (JCasC)

Define build jobs, folders, and views programmatically. Integrate Job DSL with JCasC for autonomous, sandbox-free deployment.

---

## Core Principles

1. **Configuration as Code**: Never create jobs through the Jenkins UI — generate Job DSL scripts.
2. **JCasC Integration**: Load DSL inline in JCasC YAML to bypass Groovy Sandbox manual approvals.
3. **Trait Mastery**: Explicitly configure branch discovery, PR discovery, and fork trust classes.
4. **Security First**: Never run builds on the controller, never access `Jenkins.instance`, always use `credentials()` bindings.

---

## Job DSL Basics

### Freestyle Job

```groovy
job('my-freestyle-job') {
    description('Generated by CI Automated agent')
    scm {
        git {
            remote {
                url('https://github.com/org/repo.git')
                credentials('github-creds')
            }
            branches('*/main')
        }
    }
    triggers {
        scm('H/5 * * * *')
    }
    steps {
        shell('make build')
        shell('make test')
    }
    publishers {
        archiveArtifacts('build/**/*')
    }
}
```

### Pipeline Job

```groovy
pipelineJob('my-pipeline') {
    description('Pipeline generated by CI Automated agent')
    definition {
        cpsScm {
            scm {
                git {
                    remote {
                        url('https://github.com/org/repo.git')
                        credentials('github-creds')
                    }
                    branches('*/main')
                }
            }
            scriptPath('Jenkinsfile')
        }
    }
    properties {
        disableConcurrentBuilds {
            abortPrevious(true)
        }
    }
}
```

---

## Multibranch Pipeline Jobs

Automatically create jobs for every branch with a Jenkinsfile:

```groovy
multibranchPipelineJob('my-multibranch') {
    displayName('My Service Multibranch')
    description('Auto-discovers branches with Jenkinsfiles')

    branchSources {
        github {
            id('my-service-github')
            repoOwner('my-org')
            repository('my-service')
            scanCredentialsId('github-app-creds')

            buildOriginBranch(true)
            buildOriginBranchWithPR(false)
            buildOriginPRMerge(true)
            buildForkPRMerge(false)
        }
    }

    orphanedItemStrategy {
        discardOldItems {
            numToKeep(20)
        }
    }

    triggers {
        periodic(2)    // Scan every 2 minutes
    }
}
```

---

## SCM Branch Source Traits

### BranchDiscoveryTrait

Dictates which branches are scanned and built:

| `strategyId` | Behaviour |
|---|---|
| `1` | Discover all branches **except** those filed as PRs |
| `2` | Discover **only** branches filed as PRs |
| `3` | Discover **all** branches unconditionally |

### OriginPullRequestDiscoveryTrait

Governs PRs originating from the **source repository**:

| `strategyId` | Behaviour |
|---|---|
| `1` | Build the PR **merged** with the target branch revision |
| `2` | Build the **raw PR head** revision |
| `3` | Build **both** merged and head revisions |

### ForkPullRequestDiscoveryTrait ⚠️ Security-Sensitive

Governs PRs from **untrusted external forks**. Requires explicit trust class configuration:

| Trust Class | Security Posture |
|---|---|
| `TrustPermission` | Trust only users with **repository write access** |
| `TrustContributors` | Trust **historical contributors** |
| `TrustEveryone` | Trust all — for **fully trusted enterprise** instances only |
| `TrustNobody` | Trust **nobody** — safest for open-source projects |

---

## configure Block — Raw XML Manipulation

When standard DSL methods are insufficient, deprecated, or impacted by plugin bugs, use the `configure` block to manipulate the underlying Jenkins XML directly:

```groovy
multibranchPipelineJob('secure-multibranch') {
    branchSources {
        github {
            id('secure-github')
            repoOwner('my-org')
            repository('my-service')
            scanCredentialsId('github-creds')
        }
    }

    configure { node ->
        // Navigate to the branch source's traits list
        def traits = node / sources / data /
            'jenkins.branch.BranchSource' / source / traits

        // Configure BranchDiscoveryTrait — discover all branches
        traits << 'org.jenkinsci.plugins.github__branch__source.BranchDiscoveryTrait' {
            strategyId(3)
        }

        // Configure OriginPullRequestDiscoveryTrait — merge with target
        traits << 'org.jenkinsci.plugins.github__branch__source.OriginPullRequestDiscoveryTrait' {
            strategyId(1)
        }

        // Configure ForkPullRequestDiscoveryTrait — with TrustPermission
        traits << 'org.jenkinsci.plugins.github__branch__source.ForkPullRequestDiscoveryTrait' {
            strategyId(1)
            trust(class: 'org.jenkinsci.plugins.github_branch_source.ForkPullRequestDiscoveryTrait$TrustPermission')
        }
    }
}
```

---

## Organization Folders

Scan entire GitHub organisations or Bitbucket teams, auto-creating multibranch pipelines for each repository:

```groovy
organizationFolder('my-org-folder') {
    displayName('My Organization')
    description('Auto-discovers all repositories with Jenkinsfiles')

    organizations {
        github {
            repoOwner('my-org')
            scanCredentialsId('github-app-creds')
            apiUri('https://api.github.com')

            traits {
                gitHubBranchDiscovery {
                    strategyId(3)
                }
                gitHubPullRequestDiscovery {
                    strategyId(1)
                }
                gitHubForkDiscovery {
                    strategyId(1)
                    trust {
                        gitHubTrustPermissions()
                    }
                }
            }
        }
    }

    projectFactories {
        workflowMultiBranchProjectFactory {
            scriptPath('Jenkinsfile')
        }
    }

    orphanedItemStrategy {
        discardOldItems {
            numToKeep(10)
        }
    }
}
```

---

## JCasC Integration — Bypass Groovy Sandbox

Running Job DSL via seed jobs triggers Jenkins' Script Security, requiring manual admin approval. Bypass this by embedding DSL **inline in JCasC YAML**:

```yaml
# jenkins.yaml (JCasC configuration)
jobs:
  - script: |
      multibranchPipelineJob('my-service') {
        branchSources {
          github {
            id('my-service-github')
            repoOwner('my-org')
            repository('my-service')
            scanCredentialsId('github-app-creds')
          }
        }
        orphanedItemStrategy {
          discardOldItems { numToKeep(20) }
        }
      }
  - script: |
      pipelineJob('deploy-production') {
        definition {
          cpsScm {
            scm {
              git {
                remote {
                  url('https://github.com/my-org/deploy.git')
                  credentials('github-creds')
                }
                branches('*/main')
              }
            }
            scriptPath('deploy/Jenkinsfile')
          }
        }
      }
```

**Why this works**: JCasC is trusted by Jenkins — DSL scripts loaded via the `jobs:` block bypass the Groovy Sandbox entirely, eliminating the need for manual "In-process Script Approval."

---

## Security Best Practices

### Never Run on the Controller

```groovy
// ❌ DANGEROUS — builds execute on the controller's filesystem
pipeline {
    agent any    // May select the controller node
}

// ✅ CORRECT — always target a labelled agent or container
pipeline {
    agent none
    stages {
        stage('Build') {
            agent { label 'linux-build-agent' }
            steps { sh 'make build' }
        }
    }
}
```

### Credentials Binding

```groovy
// ❌ NEVER — plaintext secrets in environment
environment {
    API_KEY = 'sk-live-abc123'
}

// ✅ CORRECT — use credentials() binding
environment {
    API_KEY = credentials('api-key-credential-id')
}
```

### No Jenkins.instance Access

```groovy
// ❌ FATAL SECURITY RISK — circumvents RBAC
def nodes = Jenkins.instance.nodes.collect { it.name }

// ✅ CORRECT — use approved Jenkins steps only
echo "Build running on ${env.NODE_NAME}"
```

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.