在Jenkins预构建阶段访问受管文件,本地文件和远程文件ssh

时间:2018-06-06 15:57:25

标签: jenkins groovy jenkins-plugins jenkins-pipeline

我有一个参数化版本,我想根据本地从站和/或通过ssh访问的远程盒子上的文件/目录内容填充参数值。

在构建阶段访问本地和远程文件不是问题,但我需要在Active Choice插件(或类似的东西)中使用它。

显然,sh函数不起作用,但仍然可以使用一些类似Java的Groovy API(如下所述:https://wiki.jenkins.io/display/JENKINS/Active+Choices+Plugin

jenkinsURL=jenkins.model.Jenkins.instance.getRootUrl()

def propFile=vPropFile //name of properties file
def propKey=vPropKey // name of properties key
def relPropFileUrl=vRelPropFileUrl // userContent/properties/
def propAddress="${jenkinsURL}${relPropFileUrl}$propFile"
def props= new Properties()
props.load(new URL(propAddress).openStream())
def choices=[]

props.get(propKey.toString()).split(",").each{
    choices.add(it)
}

return choices

我想知道是否可以以相同的方式或更好地访问托管文件,以便使用SSH远程访问某些内容。

是否有API?

1 个答案:

答案 0 :(得分:1)

在Active Choices参数脚本执行期间,我找不到允许SSH的解决方案。

但是,我能够使用Jenkins管理的配置文件。以下是可以从Active Choices参数脚本运行的代码:

def gcf = org.jenkinsci.plugins.configfiles.GlobalConfigFiles.get()
// Read different file based on referencedParameter ENVIRONMENT
def deploymentFileName = 'deployment.' + ENVIRONMENT + '.properties'
def deploymentFile = gcf.getById(deploymentFileName)
def deploymentProperties = new Properties();
deploymentProperties.load(new java.io.StringReader(deploymentFile.content))
def choices = []
// Make use of Properties object here to return list of choices
return choices

稍后在管道的主要Groovy脚本中,可以以相同的方式更新文件,但是由于脚本上下文不同,必须再次读取/加载文件:

def gcf = org.jenkinsci.plugins.configfiles.GlobalConfigFiles.get()
def deploymentFile = gcf.getById(deploymentFileName)
def deploymentProperties.load(new java.io.StringReader(deploymentFile.content))

// Update deploymentProperties as necessary here.

def stringWriter = new java.io.StringWriter()
deploymentProperties.store(stringWriter, "comments")

// Content of the deploymentFile object is immutable.
// So need to create new instance and reuse the same file id to overwrite the file.
def newDeploymentFile = deploymentFile.getDescriptor().newConfig(
    deploymentFile.id, deploymentFile.name, deploymentFile.comment, stringWriter.toString())
gcf.save(newDeploymentFile)

当然,必须在Jenkins中授予所有必要的API权限。