Pass Jenkins ssh credential into container

I need a solution that will allow Jenkins or users to pass their key to a build command, this will be done with a build argument. Users will cat their key into the argument while Jenkins will set it to a valid credential in the pipeline.

Solution

This solution is created from this ssh-add method, this eval method.

In the Jenkinsfile; You can begin to understand the SSH credential variable in the jenkins docs but the important parts are that the full SSH credential variable is actually a file path so we cat it just like a normal file. We use set +x to hide the printing of our private key, a side effect of cat-ing the variable.

Your Containerfile

ARG SSH_KEY

...

RUN eval $(ssh-agent -s) && ssh-add - <<< "${SSH_KEY}" && GIT_SSH_COMMAND="ssh -oStrictHostKeyChecking=accept-new" git clone ssh://git@bitbucket.com/proj/repo

The manual command line

podman build --build-arg=SSH_KEY="$(cat ~/.ssh/id_ecdsa)" --build-arg-file latest.argfile -t ubi8-project:ssh-test .

Jenkinsfile

pipeline {
    agent {
        label 'buildah'
    }
    environment {
        SSH_KEY = credentials('ssh-cred-ecdsa')
        IMAGE = "contoso/ubi8-project"
        TAG = "${env.BRANCH_NAME == "master" ? "latest" : "${BRANCH_NAME}"}"
    }
    stages {
        stage('Build') {
            steps {
                sh '''
                    set +x && podman build --build-arg=SSH_KEY="$(cat ${SSH_KEY})" --build-arg-file latest.argfile --tag ${IMAGE}:${TAG} .
                '''
            }
        }
        stage('Push') {
            steps {
                sh '''
                    ver=$(git log --pretty=format:'%h' -n 1)
                '''
            }
        }
    }
}

Possibilities

https://stackoverflow.com/questions/72618410/use-ssh-key-from-env-var

GIT_SSH_COMMAND=ssh -i /tmp/TempFileGenerated

Also: https://stackoverflow.com/questions/17846529/could-not-open-a-connection-to-your-authentication-agent/4086756#comment35753332_17848593

eval $(ssh-agent)
ssh-add - <<< "${SSH_PRIVATE_KEY}"

https://stackoverflow.com/questions/4565700/how-to-specify-the-private-ssh-key-to-use-when-executing-shell-command-on-git

GIT_SSH_COMMAND='ssh -i private_key_file -o IdentitiesOnly=yes' git clone user@host:repo.git

https://stackoverflow.com/questions/71019508/how-to-pass-git-ssh-credentials-to-a-docker-image-run-from-jenkins

withCredentials([sshUserPrivateKey(credentialsId: '<credential ID here>', keyFileVariable: 'KEY_FILE_PATH')]) {
    docker.image('MY_IMAGE').inside {
        sh 'cp $KEY_FILE_PATH ~/.ssh/id_rsa'
        sh '/bin/my-command my-args'
    }
}