Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to connect directly to a remote docker container with ssh

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"\''

like image 954
Aderemi Dayo Avatar asked Sep 19 '18 14:09

Aderemi Dayo


2 Answers

$ 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"
like image 162
BMitch Avatar answered Oct 21 '22 16:10

BMitch


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.

Manage Jenkins

Step 2 − Click on New Node New Nodes

Step 3 − Give a name for the node, choose the Dumb slave option and click on Ok. Dumb Slave

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.

Slave Machine1

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. Slave Machine2

In my Jenkins pipeline

node("build_slave"){
    sh 'docker exec -it $(docker ps | grep unique_text | cut -c1-10) bash deploy.sh'
}
like image 33
Aderemi Dayo Avatar answered Oct 21 '22 17:10

Aderemi Dayo