R P
R P

Reputation: 348

how to run docker commands in remote machine via jenkins and SSH?

I am new to jenkins and I am trying to execute docker command on ubuntu 18.04 Live Server. I've installed docker on it and able to run docker command via ssh. Now what i need is to run the same command on server through Jenkins. I've jenkins installed on my local ubuntu 20.04 desktop machine. I also have install docker on it. When i try to run any command over SSH from jenkins, its working but when i try to run docker command (docker -v), its say

[SSH] executing... bash: line 1: docker: command not found

i use echo $USER and get that jenkins user is trying to run the command but i've not installed jenkins on remote server and there is no user name jenkins on server, so might be its not able to run

Then i've created a jenkns user (sudo useradd -s /sbin/nologin jenkins) on remote server and add it in docker group (sudo useradd -aG docker jenkins) but its still not working. what im doing wrong! or is there any other better way instead of SSH to run docker container on remote server using jenkins that is installed on different machine. or do i need to install jenkins on remote server?

i solved by using command

sudo ln -s /snap/bin/docker /usr/bin/docker

Upvotes: 1

Views: 2782

Answers (2)

R P
R P

Reputation: 348

sudo ln -s /snap/bin/docker /usr/bin/docker

This command help me to solve my issue

Upvotes: 0

Dmitriy Tarasevich
Dmitriy Tarasevich

Reputation: 1242

To make jenkins execute commands remotely you need to add remote host to jenkins Configuration. Go to Manage Jenkins -> Configure System -> SSH remote hosts -> Add.

Add hostname or it's ip, port and credentials. Check your settings, if everything is ok you will pass it.

Next step is to configure your job. For a test porpose use freestyle job. In configuration of the job go to Build section and choose Execute shell script on remote host using ssh. Choose your ssh host and type command you want.

Remote host should have docker installed and user should be added to docker group.

For pipeline job you can find examples here

UPDATE:

Check this code

node {
  def remote = [:]
  remote.name = 'docker-srv'
  remote.host = '192.168.1.40'
  remote.user = 'vagrant'
  remote.password = 'vagrant'
  remote.allowAnyHosts = true
  stage('Remote SSH') {
    sshCommand remote: remote, command: "ls -lrt"
    sshCommand remote: remote, command: "docker -v"
    sshCommand remote: remote, command: "for i in {1..5}; do echo -n \"Loop \$i \"; date ; sleep 1; done"
  }
}

Result should be like Executing command on docker-srv[192.168.1.40]: docker -v sudo: false Docker version 19.03.9, build 9d988398e7

Upvotes: 1

Related Questions