Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save stchar/19615e3450920d3b0ad6f3f6311a0e2c to your computer and use it in GitHub Desktop.
Save stchar/19615e3450920d3b0ad6f3f6311a0e2c to your computer and use it in GitHub Desktop.
Jenkins Controller Update ssh known_hosts via groovy script console
// description: Add new fingerprints of some host to ssh known hosts file
// why: sometimes you don't have access to Jenkins controller or agents
// but you need to update system configuration or some other OS specific stuff
// like in this case ~/.ssh/known_hosts file
// you can use groovy script console ${JENKINS_URL}/script
// @argument just output upcomming changes
def dryRun = true
// @argument FQDN name to retrive new ssh fingerprints
def host = "github.com"
import java.text.SimpleDateFormat
def timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date())
println timeStamp
// print previous content
println '======= OLD ===='
println "cat /var/jenkins_home/.ssh/known_hosts".execute().text
println '=======\n\n'
// backup
if (!dryRun) {
println "cp /var/jenkins_home/.ssh/known_hosts.backup_${timeStamp}".execute().text
println "ls -la /var/jenkins_home/.ssh/".execute().text
}
// create a bash script
// I was not able to run complex shell command (wiht output redirection and shell pipelines)
// with standart groovy approach .e.g "some command expression".execute()
new File('/var/jenkins_home/.ssh/update_known_hosts.sh').text="""#!/bin/bash
ssh-keyscan -H ${host} |sort -u - /var/jenkins_home/.ssh/known_hosts >/var/jenkins_home/.ssh/tmp_hosts
"""
// run the script
def sout = new StringBuilder()
def serr = new StringBuilder()
def p = """bash -x /var/jenkins_home/.ssh/update_known_hosts.sh """.execute()
p.consumeProcessOutput(sout, serr)
p.waitForOrKill(1000)
println "text: ${p.text}"
println "Exit code: ${p.exitValue()}"
println "Standard output: $sout"
println "Standard error: $serr"
// show upcomming changes
println '======= NEW ===='
println "cat /var/jenkins_home/.ssh/tmp_hosts".execute().text
println '======='
// replace known_hosts with new content
if (!dryRun) {
println "mv /var/jenkins_home/.ssh/tmp_hosts /var/jenkins_home/.ssh/known_hosts".execute()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment