Skip to content

Instantly share code, notes, and snippets.

@apr-1985
Last active March 24, 2024 12:05
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save apr-1985/9b5cf46497f82c11f00e05363ad45107 to your computer and use it in GitHub Desktop.
Save apr-1985/9b5cf46497f82c11f00e05363ad45107 to your computer and use it in GitHub Desktop.
Jenkins Config As Code Examples

Jenkins JCasC Examples

Various examples of how to setup different components using JCasC

---
credentials:
system:
domainCredentials:
- credentials:
- usernamePassword:
scope: GLOBAL
id: "af-user-token"
username: ${service-account-name}
password: ${service-account-artifactory-token}
description: "Artifactory Service account username and API token"
unclassified:
artifactoryBuilder:
jfrogInstances:
- instanceId: "AF"
artifactoryUrl: "https://artifactory.example.com/artifactory"
deployerCredentialsConfig:
credentialsId: "af-user-token"
useCredentialsPlugin: true
x-ec2_anchor: &ec2_anchor
amiType:
unixData:
sshPort: "22"
associatePublicIp: false
connectBySSHProcess: false
connectionStrategy: PRIVATE_IP
deleteRootOnTermination: true
ebsOptimized: false
hostKeyVerificationStrategy: "OFF"
iamInstanceProfile: "${jenkins_agent_profile_arn}"
idleTerminationMinutes: "30"
initScript: |
sudo yum install -y jq zip unzip;
sudo service ecs stop
sudo docker rm ecs-agent
maxTotalUses: -1
mode: NORMAL
monitoring: false
numExecutors: 1
remoteAdmin: "ec2-user"
remoteFS: "/tmp"
securityGroups: "${jenkins_security_group_id}"
tenancy: "Default"
useEphemeralDevices: false
zone: "eu-west-1a"
stopOnTerminate: false
subnetId: "${jenkins_subnet}"
t2Unlimited: false
jenkins:
clouds:
- amazonEC2:
cloudName: "jenkins-agents"
instanceCapStr: "15"
sshKeysCredentialsId: "ssh-agent-key"
region: "eu-west-1"
templates:
- ami: "${jenkins_agent_docker_base_ami_id}"
description: "jenkins-t2micro-agent"
instanceCapStr: "5"
labelString: "docker docker-t2micro"
spotConfig:
spotMaxBidPrice: "0.0126000000"
useBidPrice: true
tags:
- name: "Name"
value: "JenkinsAgentT2Micro"
- name: "Role"
value: "JenkinsAgent"
- name: "instance_type"
value: "T2Micro"
type: "T2Micro"
<<: *ec2_anchor
- ami: "${jenkins_agent_docker_base_ami_id}"
description: "jenkins-t3micro-agent"
instanceCapStr: "5"
labelString: "docker docker-t3micro"
spotConfig:
spotMaxBidPrice: "0.0126000000"
useBidPrice: true
tags:
- name: "Name"
value: "JenkinsAgentT3Micro"
- name: "Role"
value: "JenkinsAgent"
- name: "instance_type"
value: "T3Micro"
type: "T3Micro"
<<: *ec2_anchor
- ami: "${jenkins_agent_docker_base_ami_id}"
description: "jenkins-t3large-agent"
instanceCapStr: "5"
labelString: "docker docker-t3large"
spotConfig:
spotMaxBidPrice: "0.04"
useBidPrice: true
tags:
- name: "Name"
value: "JenkinsAgentT3Large"
- name: "Role"
value: "JenkinsAgent"
- name: "instance_type"
value: "T3Large"
type: "T3Large"
<<: *ec2_anchor
useInstanceProfileForCredentials: true
---
# yamllint disable rule:line-length
jobs:
- script: >
organizationFolder("Python_Modules") {
description('Python Module Build Jobs')
displayName('Python Module Build Jobs')
triggers {
periodic(1440)
}
organizations{
github {
repoOwner("ORG")
credentialsId("github-api-user-token")
traits {
sourceRegexFilter {
regex("python-.*")
}
gitHubBranchDiscovery {
strategyId(3)
}
gitHubPullRequestDiscovery {
strategyId(1)
}
gitHubTagDiscovery()
}
}
}
buildStrategies {
buildAllBranches {
strategies {
buildNamedBranches {
filters {
wildcards {
includes('*')
excludes('release*')
caseSensitive(false)
}
}
}
}
}
buildTags {
atLeastDays '-1'
atMostDays '7'
}
}
orphanedItemStrategy {
discardOldItems {
numToKeep(3)
}
}
}
configure {
def traits = it / 'navigators' / 'org.jenkinsci.plugins.github__branch__source.GitHubSCMNavigator'/ 'traits'
traits << 'org.jenkinsci.plugins.github__branch__source.ForkPullRequestDiscoveryTrait' {
strategyId(1)
trust(class: 'org.jenkinsci.plugins.github_branch_source.ForkPullRequestDiscoveryTrait$TrustEveryone')
}
}
jobs:
- script: >
folder('JFROG');
folder('JFROG/Artifactory');
folder('JFROG/Artifactory/misc-jobs');
pipelineJob('JFROG/Artifactory/misc-jobs/artifactory-ad-groups') {
triggers {
cron('0 H(04-05) * * *')
}
description("Create associated AD groups for each artifactory.")
definition {
cps {
script("""
def org_list = ""
def org_json = ""
pipeline {
agent { label "docker" }
options {
timestamps()
ansiColor('xterm')
}
stages {
stage("Add Artifactories to AD and bootstrap all users group") {
agent {
docker {
image 'python:3.7.3'
reuseNode true
// leave blank for dockerhub but be careful of pull limits
registryUrl 'artifactory.example.com'
}
}
environment {
HOME = "/tmp"
}
steps {
// Library Step
pipInstallFromArtifactory(python_modules: 'LDAPHelper')
withAWSParameterStore(naming: 'basename', path: '/jenkins/', regionName: 'us-east-1') {
wrap([\$class: 'MaskPasswordsBuildWrapper', varPasswordPairs: [[password: SERVICE_ACCOUNT_PASSWORD, var: 'SECRET']]]) {
script {
['af1', 'af2'].each {
sh "\$env.HOME/.local/bin/ldap_cli --password '\$SERVICE_ACCOUNT_PASSWORD' --search_base 'OU=Infrastructure,OU=Groups,DC=example,DC=com' add-ou-to-ou --base_ou_name Artifactory --ou_name_to_add \$it"
sh "\$env.HOME/.local/bin/ldap_cli --password '\$SERVICE_ACCOUNT_PASSWORD' --search_base 'OU=Artifactory,OU=TIO,OU=Infrastructure,OU=Groups,DC=example,DC=com' add-group-to-ou --base_ou_name \$it --group_name_to_add 'Artifactory-" + it + "-all-users'"
}
}
}
}
}
}
}
}
""")
sandbox()
}
}
}
---
credentials:
system:
domainCredentials:
- credentials:
- basicSSHUserPrivateKey:
description: "Key used to bootstrap the Jenkins Server"
id: "bootstrap-github-key"
privateKeySource:
directEntry:
privateKey: ${id_rsa}
scope: GLOBAL
username: "git"
- string:
description: "Token used for configuration reload"
id: "jcasc-reload-token"
secret: ${jcasc_reload_token}
scope: GLOBAL
- usernamePassword:
scope: GLOBAL
id: "github-api-user-token"
username: ${github-api-service-account-name}
password: ${github-api-service-account-token}
description: "API Service account api user and token for org scan"
- basicSSHUserPrivateKey:
description: "SSH key for agent access"
id: "ssh-agent-key"
privateKeySource:
directEntry:
privateKey: ${agent_key}
scope: GLOBAL
- usernamePassword:
scope: GLOBAL
id: "artifactory-api-user-token"
username: ${service-account-name}
password: ${service-account-artifactory-token}
description: "Service account user and token for artifactory"
- string:
scope: GLOBAL
id: opsgenie-api-key
secret: "${opsgenie_api_key}"
description: OpsGenie API Access Key
---
# yamllint disable rule:line-length
jobs:
- script: >
folder('common');
multibranchPipelineJob('common/jcasc-deploy') {
factory {
workflowBranchProjectFactory {
scriptPath('Jenkinsfile')
}
}
branchSources {
branchSource {
source {
github {
configuredByUrl(true)
repoOwner('ORG')
repository('jenkinscontrol')
repositoryUrl('https://github.com/ORG/jenkinscontrol.git')
credentialsId('github-api-user-token')
id('jcasc-deploy')
traits {
gitHubBranchDiscovery {
strategyId(3)
}
gitHubTagDiscovery()
}
}
}
buildStrategies {
buildAllBranches {
strategies {
skipInitialBuildOnFirstBranchIndexing()
}
}
}
}
}
orphanedItemStrategy {
discardOldItems {
numToKeep(3)
}
}
triggers {
periodicFolderTrigger {
interval('1440')
}
}
}
---
# yamllint disable rule:line-length
jobs:
- script: >
folder('monitoring');
folder('monitoring/sre');
folder('monitoring/sre/dashboards');
pipelineJob('monitoring/sre/dashboards/generate_dashboards') {
// disabled()
triggers {
cron('H 07 * * *')
}
definition {
cpsScm {
lightweight(true)
scm {
scriptPath('dashboards/Jenkinsfile')
git {
remote {
url('git@github.com:ORG/monitoring.git')
credentials('bootstrap-github-key')
}
branches('*/main')
}
}
}
}
}
---
jenkins:
authorizationStrategy:
roleBased:
roles:
global:
- name: "admin"
description: "Jenkins administrators"
permissions:
- "Overall/Administer"
assignments:
- "MY ADMIN AD GROUP"
- name: "read"
description: "Jenkins readers"
permissions:
- "Overall/Read"
- "Job/Read"
assignments:
- "MY READER AD GROUP"
- "READER USER 1"
- "READER USER 2"
- name: "builders"
description: "Jenkins builders"
permissions:
- "Overall/Read"
- "Job/Read"
- "Job/Build"
- "Job/Cancel"
assignments:
- "BUILDER USER 1"
items:
- name: "maintenance"
description: "Access to jobs for production maintenance"
pattern: "Maintenance/.*"
permissions:
- "Job/Build"
- "Job/Cancel"
assignments:
- "ON CALL TEAM AD GROUP"
- name: "Non-Prod Terraform"
description: "Access to Non Prod Terraform jobs"
pattern: "terraform/infrastructure/non-prod/.*"
permissions:
- "Job/Build"
- "Job/Cancel"
assignments:
- "SRE 1"
- name: "Sandbox"
description: "Access to jobs sandbox"
pattern: "sandbox/.*"
permissions:
- "Job/Build"
- "Job/Cancel"
- "Job/Create"
- "Job/Read"
- "Job/Configure"
- "Job/Delete"
assignments:
- "DEVELOPER 1""
- "DEVELOPER 2"
- "DEVELOPER 3"
---
# yamllint disable rule:line-length
unclassified:
globalLibraries:
libraries:
- defaultVersion: "main"
name: "jenkins-libraries"
implicit: true
retriever:
modernSCM:
scm:
git:
credentialsId: "bootstrap-github-key"
remote: "git@github.com:ORG/jenkins-libraries.git"
---
credentials:
system:
domainCredentials:
- credentials:
- string:
description: "Slack auth token"
scope: GLOBAL
id: "slack-token"
secret: ${slack-token}
unclassified:
slackNotifier:
teamDomain: "MY SLACK DOMAIN"
tokenCredentialId: slack-token
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment