Below is an example of a Gradle plugin written in Groovy that provides a task for building Docker images. This plugin utilizes Gradle's incremental build feature to cache the task based on input files, meaning the Docker image will only be rebuilt if the inputs (e.g., the Dockerfile or the files being copied into the image) change.
Note: This example assumes you have Docker installed and running on your system. The plugin uses the docker command-line tool to build images.
Step 1: Create the Plugin Directory Structure
First, create the following directory structure for your plugin:
docker-image-builder-plugin/
├── src/
│ └── main/
│ ├── groovy/
│ │ └── com.example.gradle/
│ │ └── DockerImageBuilderPlugin.groovy
│ └── resources/
│ └── META-INF/
│ └── gradle-plugins/
│ └── com.example.docker-image-builder.properties
├── build.gradle
└── settings.gradle
Step 2: settings.gradle
// Set the root project name
rootProject.name = 'docker-image-builder-plugin'
Step 3: build.gradle (for the plugin itself)
// Apply the Groovy Gradle Plugin to build the plugin
plugins {
id 'groovy-gradle-plugin'
}
// Group and version for the plugin
group = 'com.example.gradle'
version = '1.0'
// Maven Central repository for dependencies
repositories {
mavenCentral()
}
// Dependencies needed for the plugin
dependencies {
implementation gradleApi() // Gradle API for plugin development
implementation localGroovy() // Groovy for the plugin's implementation
}
Step 4: DockerImageBuilderPlugin.groovy
// Package declaration for the plugin class
package com.example.gradle
import org.gradle.api.DefaultTask
import org.gradle.api.file.DirectoryProperty
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.model.ObjectFactory
import org.gradle.api.plugins.BasePlugin
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.InputDirectory
import org.gradle.api.tasks.InputFile
import org.gradle.api.tasks.Output
import org.gradle.api.tasks.TaskAction
import org.gradle.api.tasks.TaskProvider
import org.gradle.work.DisableCachingByDefault
import javax.inject.Inject
// Disable caching by default; adjust based on performance needs
@DisableCachingByDefault(because = "Examples, adjust caching according to your needs")
class BuildDockerImageTask extends DefaultTask {
// Input: Docker image tag name
@Input
String dockerTagName
// Input: Directory containing Docker build context
@InputDirectory
final DirectoryProperty contextDir
// Input: Dockerfile for building the image
@InputFile
final RegularFileProperty dockerFile
// Output: File storing the built Docker image ID
@Output
final RegularFileProperty imageIdFile
// Constructor to initialize properties
@Inject
BuildDockerImageTask(ObjectFactory objectFactory) {
contextDir = objectFactory.directoryProperty()
dockerFile = objectFactory.fileProperty()
imageIdFile = objectFactory.fileProperty()
group = "Docker" // Task group for organization
description = "Builds a Docker image." // Task description
}
// Task action to build the Docker image
@TaskAction
void build() {
// Command to build the Docker image
def command = ["docker", "build",
"-t", dockerTagName, // Tag for the Docker image
"-f", dockerFile.get().asFile.absolutePath, // Path to Dockerfile
contextDir.get().asFile.absolutePath] // Build context directory
// Execute the Docker build command
def process = command.execute()
def output = process.in.text
def error = process.err.text
// Handle build failure
if (process.exitValue() != 0) {
throw new RuntimeException("Failed to build Docker image. Exit code: ${process.exitValue()}\nOutput: $output\nError: $error")
}
// Extract and store the Docker image ID
def imageId = output.tokenize('\n').find { it.startsWith('Successfully built') }.split(' ').last()
imageIdFile.set(new File(project.buildDir, "dockerImageId.txt"))
imageIdFile.get().asFile.write(imageId)
}
}
// Main plugin class to apply the task
class DockerImageBuilderPlugin implements Plugin<Project> {
// Apply the plugin to the project
void apply(Project project) {
// Apply the BasePlugin for basic Gradle features
project.plugins.apply(BasePlugin)
// Create a task provider for the Docker image build task
def objectFactory = project.objects
def taskProvider = project.tasks.register('buildDockerImage', BuildDockerImageTask, objectFactory) {
// Default configuration for the task
dockerTagName = 'example/myimage:latest' // Default Docker image tag
contextDir.set(project.layout.projectDirectory.dir('docker-context')) // Default build context directory
dockerFile.set(project.layout.projectDirectory.file('docker-context/Dockerfile')) // Default Dockerfile location
imageIdFile.set(project.layout.buildDirectory.file('dockerImageId.txt')) // Output file for image ID
}
// Optional: Configure task dependencies if needed
project.tasks.named('buildDockerImage', { task ->
// Example: Depend on another task if required
// task.dependsOn('someOtherTask')
})
}
}
Step 5: com.example.docker-image-builder.properties (for plugin metadata)
# Specify the implementation class for the plugin
implementation-class=com.example.gradle.DockerImageBuilderPlugin
Using the Plugin in a Project
-
Build the Plugin:
Navigate to the plugin directory and run ./gradlew publishToMavenLocal to build and publish the plugin to your local Maven repository.
-
Apply the Plugin in Your Project:
In your project's settings.gradle, add:
pluginManagement {
repositories {
mavenLocal() // Use local Maven repository
gradlePluginPortal() // Gradle Plugin Portal
}
}
In your project's build.gradle, apply the plugin and configure the task as needed:
plugins {
id 'com.example.gradle.docker-image-builder' version '1.0'
}
// Configure the buildDockerImage task
buildDockerImage {
dockerTagName = 'myproject/myimage:1.0' // Custom Docker image tag
contextDir = layout.projectDirectory.dir('path/to/context') // Custom build context directory
dockerFile = layout.projectDirectory.file('path/to/Dockerfile') // Custom Dockerfile path
}
-
Run the Task:
Execute the task by running ./gradlew buildDockerImage in your terminal. The first run will build the Docker image, and subsequent runs will only rebuild the image if the inputs (Dockerfile or context directory contents) have changed, thanks to Gradle's incremental build feature.