2017-09-25 65 views
0

剛開始看Jenkins聲明式管道並在Docker容器中運行我的構建。我有一個項目,通過git拉入npm包,因此需要設置ssh密鑰。聲明式Jenkins管道和Docker

從我所遇到的,我可以在我的Dockerfile設置編譯ARGS如--build-arg ssh_pub_key="$(cat ~/.ssh/id_rsa.pub)"然後

ARG ssh_pub_key 

我把我的Jenkinsfile

pipeline { 
    agent { 
    dockerfile { 
     args '''--build-arg ssh_prv_key="$(cat /var/lib/jenkins-git/.ssh/id_rsa)"''' 
    } 
    } 

    stages { 
    stage('Test') { 
     steps { 
     sh 'echo $ssh_prv_key' 
     } 
    } 
    } 
} 

內的下列方法時運行的版本在詹金斯,我在建立圖像時得到下面的輸出(沒有提及--build-arg。)

docker build -t 085eb412f6dd28c1a7843aa9f9ed84e7c4af3e1b -f Dockerfile . 

並沒有任何變數

我沒有正確設置它們嗎?有人以不同的方式處理密鑰的複製嗎?

感謝

UPDATE

MY Jenkinsfile現在看起來像下面,但不會運行爲獲得

Required context class hudson.FilePath is missing 
Perhaps you forgot to surround the code with a step that provides this, such as: node 

看來我不能管線聲明之外運行任何腳本?

def ssh_prv_key = sh script: 'cat /var/lib/jenkins-git/.ssh/id_rsa', returnStdout: true 
def ssh_pub_key = sh script: 'cat /var/lib/jenkins-git/.ssh/id_rsa.pub', returnStdout: true 

pipeline { 
    agent { 
    dockerfile { 
     args """--build-arg ssh_prv_key=\"${ssh_prv_key}\" --build-arg ssh_pub_key=\"${ssh_pub_key}\" """ 
    } 
    } 
    stages { 
     stage('Test') { 
     steps { 
      sh 'echo $ssh_prv_key' 
     } 
     } 
    } 
} 
+0

您還需要添加'ENV ssh_pub_key = $ ssh_pub_key',以便SSH密鑰成爲圖像環境變量的一部分。現在你正在傳遞構建參數,但沒有使用它們,因爲這樣的幫助,我會在哪裏放置這個? –

回答

1

這裏$(cat /var/lib/jenkins-git/.ssh/id_rsa)是一個shell命令。

AFAIK,綁定必須在流水線之外聲明才能在定義代理時使用它們。

因此,使管道工作參數化。

  • 添加ssh_prv_key憑據參數
  • 選擇Secretfile
  • 設置默認值上傳secretfile
  • 重複步驟ssh_pub_key

Parameterized Pipeline

然後在dockerfileadditionalBuildArgs指令使用ssh_prv_key

pipeline { 
    agent { 
    dockerfile { 
     additionalBuildArgs ""--build-arg ssh_prv_key=\"$ssh_prv_key\" --build-arg ssh_pub_key=\"$ssh_pub_key\"" 
    } 
    } 
    stages { 
     stage('Test') { 
     steps { 
      sh "echo $ssh_prv_key" 
     } 
     } 
    } 
} 
+0

感謝您的幫助。在管道塊之外還是在它之內? – Richlewis

+0

我通常將我的變量定義放在管道塊之外的開始部分。 –

+0

我已經更新了我的問題,有興趣知道如何讓它運行?謝謝 – Richlewis

相關問題