You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

自定义Gradle Task依赖org.hidetake.ssh插件报错求助

How to Access the ssh Extension from a Custom Gradle Task in buildSrc

Alright, let's break down why your custom DeployTask can't access the ssh property and how to fix it properly.

The ssh variable you're trying to use is an extension added by the org.hidetake.ssh plugin directly to your Gradle project. When you put the SSH logic inside doLast in the main build.gradle, it runs in the project's context—so it has automatic access to this extension. But your DeployTask in buildSrc is a standalone class; it doesn't inherit the project's extensions unless you explicitly fetch them.

Step 1: Add SSH Plugin Dependency to buildSrc

First, since your task needs to reference classes from the SSH plugin, you have to declare that dependency in buildSrc/build.gradle (buildSrc is a separate sub-build and needs its own dependencies):

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.hidetake:gradle-ssh-plugin:2.10.1'
}

Step 2: Fetch the SSH Extension from the Project in Your Task

Modify your DeployTask to retrieve the ssh extension using the task's built-in project property. This connects your task to the same extension instance configured in your main build.gradle:

import org.gradle.api.DefaultTask
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.Option
import org.gradle.api.tasks.TaskAction
import org.hidetake.ssh.plugin.SshPluginExtension

class DeployTask extends DefaultTask {
    @Input
    @Option(option = "env", description = "Configures the environment to be used")
    String environment = "dev";
    
    @Input
    @Option(option = "branch", description = "Configures the branch which should be deployed")
    String branch = "master";
    
    @TaskAction
    void deploy() {
        // Retrieve the SSH extension from the parent project
        SshPluginExtension ssh = project.extensions.getByType(SshPluginExtension)
        
        ssh.run {
            session(ssh.remotes[environment]) {
                execute "echo test"
            }
        }
    }
}

Why This Works

Every Gradle task has a reference to its parent Project via the project property. The SSH plugin registers SshPluginExtension as an extension on the project, so using getByType() is a safe way to fetch it (it will fail fast if the extension isn't present, helping you catch configuration issues early).

Your main build.gradle doesn't need any changes—your existing remotes configuration will still be used by the extension we're fetching in the task.

内容的提问来源于stack exchange,提问作者Ayk Borstelmann

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 11:02:40