如何在管道兼容的jenkins SimpleBuildStep插件中获取环境参数?

时间:2018-05-21 05:10:10

标签: java jenkins jenkins-pipeline

我刚刚添加了管道兼容性,但我无法获得任何env参数。 我的班级定义如下:

public class JobBuildStep extends Builder implements SimpleBuildStep

并执行方法:

public void perform(@Nonnull Run<?, ?> run, @Nonnull FilePath workspace, @Nonnull Launcher launcher, @Nonnull TaskListener listener) throws AbortException

有人可以告诉我有哪些方法可以解决这个问题? 我也发现了一个问题 - https://issues.jenkins-ci.org/browse/JENKINS-29144 最后一条评论说我应该实现Step,而不是来自

org.jenkinsci.plugins.workflow.steps.Step
<dependency>
  <groupId>org.jenkins-ci.plugins.workflow</groupId>
  <artifactId>workflow-basic-steps</artifactId>
  <version>2.7</version>
</dependency>

包?如果是这样,我该如何使用 @Override public StepExecution start(StepContext stepContext) throws Exception 方法

1 个答案:

答案 0 :(得分:1)

这是通过Step extend:

完成的

public class ExampleBuildStep extends Step

并使用EnvVars创建perform方法作为输入:

public void perform(@Nonnull Run<?, ?> run, @Nonnull FilePath workspace, @Nonnull Launcher launcher, @Nonnull TaskListener listener, @Nonnull EnvVars environment) throws AbortException

以下是Step class实现的方法:

@Override
public StepExecution start(StepContext stepContext) {

  return new Execution(stepContext, this);
}

private final static class Execution extends SynchronousNonBlockingStepExecution<Void> {

  private transient final ExampleBuildStep step;

  protected Execution(
    @Nonnull StepContext context,
    ExampleBuildStep step) {
    super(context);
    this.step = step;
  }

  @Override
  protected Void run() throws Exception {

    FilePath workspace = getContext().get(FilePath.class);
    workspace.mkdirs();
    step.perform(
      getContext().get(Run.class),
      workspace,
      getContext().get(Launcher.class),
      getContext().get(TaskListener.class),
      getContext().get(EnvVars.class));
    return null;
  }
}

然后您将能够通过StepDescriptor中的getFunctionName()返回的名称使用它:

@Extension
public static class DescriptorImpl extends StepDescriptor {

  @Override
  public Set<? extends Class<?>> getRequiredContext() {
    return ImmutableSet.of(FilePath.class, Run.class, Launcher.class, TaskListener.class, EnvVars.class);
  }

  @Override
  public String getFunctionName() {
    return "run_your_step";
  }

  public boolean isApplicable(Class<? extends AbstractProject> aClass) {
    // Indicates that this builder can be used with all kinds of project types
    return true;
  }

  public String getDisplayName() {
    return "Example of step plugin";
  }
}