问题
I want to connect to a remote running Docker container directly with ssh. Normally I can
$ ssh -i privateKey user@host
$ docker ps #which will list all running containers
$ docker exec -it ***** bash deploy.sh # ***** is container id and this line run a deployment script
But I need to run this script from a Jenkins pipeline where I have only one chance. After many trying, I come up with this
$ ssh -tt -i ~/privateKey user@host docker exec -it $(docker ps | grep unique_text | cut -c1-10) /bin/bash deploy.sh
Which have not help my plight because it returns
"docker exec" requires at least 2 arguments.
Which actually mean the command is truncated here $(docker ps | grep ...
My Solution
sh 'ssh -tt -i $FILE -o StrictHostKeyChecking=no $USER@$HOST /bin/bash -c \'"docker exec -it $(docker ps | grep unique_text | cut -c1-10) bash start.sh"\''
回答1:
$ ssh -tt -i ~/privateKey user@host docker exec -it $(docker ps | grep unique_text | cut -c1-10) /bin/bash deploy.sh
That will run the sub shell with the docker ps
command on your local machine, not the remote one. You'll want to process that full command in a shell on the remote server:
$ ssh -tt -i ~/privateKey user@host /bin/sh -c "docker exec -it $(docker ps | grep unique_text | cut -c1-10) /bin/bash deploy.sh"
回答2:
The best solution to this problem is to create a node in Jenkins
Step 1 − Go to the Manage Jenkins section and scroll down to the section of Manage Nodes.
Step 2 − Click on New Node
Step 3 − Give a name for the node, choose the Dumb slave option and click on Ok.
Step 4 − Enter the details of the node slave machine. In the below example, we are considering the slave machine to be a windows machine, hence the option of “Let Jenkins control this Windows slave as a Windows service” was chosen as the launch method. We also need to add the necessary details of the slave node such as the node name and the login credentials for the node machine. Click the Save button. The Labels for which the name is entered as “New_Slave” is what can be used to configure jobs to use this slave machine.
Once the above steps are completed, the new node machine will initially be in an offline state, but will come online if all the settings in the previous screen were entered correctly. One can at any time make the node slave machine as offline if required.
In my Jenkins pipeline
node("build_slave"){
sh 'docker exec -it $(docker ps | grep unique_text | cut -c1-10) bash deploy.sh'
}
来源:https://stackoverflow.com/questions/52408764/how-to-connect-directly-to-a-remote-docker-container-with-ssh