Jenkins – Active Choice: SSH – Return remote command values

For a parameterized assembly with an image tag selection, you will need the Active Choices plugin

Go to “Manage Jenkins

 

Section “Manage Plugins

 

Go to the “Available” tab and select “Active Choices” in the search.

Install it.

 

Create a “New Item” – “Pipeline“, indicate that it will be a parameterized assembly, and add the parameter “Active Choices Parameter

 

 

 

We indicate that this is “Groovy Script” and paste the following into it:

import com.cloudbees.plugins.credentials.Credentials;
import com.cloudbees.plugins.credentials.CredentialsNameProvider;
import com.cloudbees.plugins.credentials.common.StandardCredentials;
import com.cloudbees.jenkins.plugins.sshcredentials.SSHUserPrivateKey;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.ChannelExec;
import jenkins.model.*


sshCredentialsId = 'instance_ssh_key'
sshUser = 'artem'
sshInstance = '192.168.1.100'

def sshCreds = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(SSHUserPrivateKey.class, Jenkins.instance, null, null ).find({it.id == sshCredentialsId});

String ssh_key_data = sshCreds.getPrivateKeys()

JSch jsch = new JSch();
jsch.addIdentity("id_rsa", ssh_key_data.getBytes(), null, null);
Session session = jsch.getSession(sshUser, sshInstance, 22);
Properties prop = new Properties();
prop.put("StrictHostKeyChecking", "no");
session.setConfig(prop);

session.connect();

ChannelExec channelssh = (ChannelExec)session.openChannel("exec");
channelssh.setCommand("cat /home/artem/secret_list");
channelssh.connect();

def result = []
InputStream is=channelssh.getInputStream();
is.eachLine {
    result.add(it)
}
channelssh.disconnect();

return result

 

Where is the value of the variables, “sshCredentialsId” – Jenkins Credentials ID with type: “SSH Username with private key”;

sshUser” – username for SSH connection;

sshInstance” – IP address or domain name of the remote instance;

cat /home/artem/secret_list” – the command whose result we want to return

 

Tagged: Tags

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments