#!/usr/bin/env python3 """Upgrade explicitly named managed Jenkins jobs for pinned commits; dry-run by default.""" import argparse, base64, json, os, re, urllib.request, xml.etree.ElementTree as ET from pathlib import Path SHELL = '''set -eu case "$DEPLOY_COMMIT" in *[!0-9a-f]*|"") echo "Invalid pinned commit"; exit 2;; esac [ "${#DEPLOY_COMMIT}" -eq 40 ] || exit 2 if ! git cat-file -e "$DEPLOY_COMMIT^{commit}" 2>/dev/null; then git fetch origin "$DEPLOY_COMMIT" fi git checkout --detach --force "$DEPLOY_COMMIT" test "$(git rev-parse HEAD)" = "$DEPLOY_COMMIT" ''' def upgrade(xml): root = ET.fromstring(xml) node = root.find('./definition/script') if node is None or not node.text: raise ValueError('Only inline Pipeline jobs are supported') script = node.text if "stage('Checkout pinned commit')" not in script: if "stage('Env')" not in script: raise ValueError('Expected Env stage was not found') if re.match(r'\s*pipeline\s*\{', script): stage = "stage('Checkout pinned commit') {\n when { expression { return params.DEPLOY_COMMIT?.trim() } }\n steps { sh '''\n" + SHELL + "''' }\n }\n\n " else: stage = "stage('Checkout pinned commit') {\n if (env.DEPLOY_COMMIT?.trim()) { sh '''\n" + SHELL + "''' }\n }\n\n " node.text = script.replace("stage('Env')",stage+"stage('Env')",1) props=root.find('properties') if props is None: props=ET.SubElement(root,'properties') params=props.find('hudson.model.ParametersDefinitionProperty') if params is None: params=ET.SubElement(props,'hudson.model.ParametersDefinitionProperty') definitions=params.find('parameterDefinitions') if definitions is None: definitions=ET.SubElement(params,'parameterDefinitions') for parameter in ['DEPLOY_COMMIT','DEPLOY_RUN_ID','PROJECT_KEY','DEPLOY_ENVIRONMENT','GIT_REF','OPERATOR']: if not any(p.findtext('name')==parameter for p in definitions): p=ET.SubElement(definitions,'hudson.model.StringParameterDefinition') description='Optional verified full commit SHA for a pinned deployment or rollback' if parameter=='DEPLOY_COMMIT' else 'DevOps platform deployment context' for name,value in [('name',parameter),('description',description),('defaultValue',''),('trim','true')]: ET.SubElement(p,name).text=value if props.find('org.jenkinsci.plugins.workflow.job.properties.DisableConcurrentBuildsJobProperty') is None: ET.SubElement(props,'org.jenkinsci.plugins.workflow.job.properties.DisableConcurrentBuildsJobProperty') return ET.tostring(root,encoding='utf-8',xml_declaration=True) def upgrade_relay(source): old='}/build", method="POST", headers=headers)' new='}/buildWithParameters", method="POST", headers=headers)' if new in source: return source if source.count(old)!=1: raise ValueError('Unexpected direct-build relay layout') return source.replace(old,new,1) def main(): parser=argparse.ArgumentParser();parser.add_argument('--jobs-json',required=True);parser.add_argument('--apply',action='store_true');parser.add_argument('--relay-path');parser.add_argument('--backup-dir',default='/root/devops-jenkins-pinned-backup-20261028');args=parser.parse_args() base=os.environ['JENKINS_BASE_URL'].rstrip('/') auth='Basic '+base64.b64encode((os.environ['JENKINS_USERNAME']+':'+os.environ['JENKINS_API_TOKEN']).encode()).decode() pending=[] for job in json.loads(args.jobs_json): path=''.join('/job/'+urllib.parse.quote(part,safe='') for part in job.split('/'))+'/config.xml' with urllib.request.urlopen(urllib.request.Request(base+path,headers={'Authorization':auth}),timeout=15) as r: original=r.read() pending.append((job,path,original,upgrade(original))) for job,path,original,updated in pending: if args.apply: backup=Path(args.backup_dir);backup.mkdir(mode=0o700,parents=True,exist_ok=True) dest=backup/(job.replace('/','__')+'.xml') if not dest.exists(): dest.write_bytes(original);dest.chmod(0o600) with urllib.request.urlopen(urllib.request.Request(base+path,data=updated,headers={'Authorization':auth,'Content-Type':'application/xml'},method='POST'),timeout=15) as r: assert r.status==200 print(json.dumps({'job':job,'validated':True,'applied':args.apply})) if args.relay_path: relay=Path(args.relay_path);original=relay.read_text();updated=upgrade_relay(original) compile(updated,str(relay),'exec') if args.apply: backup=Path(args.backup_dir);backup.mkdir(mode=0o700,parents=True,exist_ok=True) dest=backup/'relay.py' if not dest.exists():dest.write_text(original);dest.chmod(0o600) relay.write_text(updated) print(json.dumps({'relayValidated':True,'applied':args.apply,'restartRequired':args.apply})) if __name__=='__main__': main()