Go

Learn how to write a Vela plugin with Go.

Overview

From Go documentation:

Go is an open source programming language that makes it easy to build simple, reliable, and efficient software.

Code

To create a plugin using Go, we’ll need to first decide what task we want this plugin to accomplish.

For this example, we’re going to create a program that makes an HTTP request from the provided input:

package main

import (
	"fmt"
	"net/http"
	"os"
	"strings"
)

func main() {
	// import method parameter from environment
	method := os.Getenv("PARAMETER_METHOD")
	// import body parameter from environment
	body := os.Getenv("PARAMETER_BODY")
	// import url parameter from environment
	url := os.Getenv("PARAMETER_URL")

	// create payload from body
	payload := strings.NewReader(body)

	// create new HTTP request from provided input
	request, err := http.NewRequest(method, url, payload)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	// send HTTP request and capture response
	response, err := http.DefaultClient.Do(request)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	// output the response
	fmt.Println(response)
}

Executable

Now that we have the program to accomplish our plugin’s task, we need to compile the code to produce an executable binary for the target platform:

GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -o vela-sample

Image

Once we have the executable needed to accomplish our plugin’s task, we need to create a Dockerfile to produce an image.

This image should contain the binary and be setup to run that binary when the plugin is executed:

FROM golang:alpine

RUN apk add --update --no-cache ca-certificates

COPY vela-sample /bin/vela-sample

ENTRYPOINT ["/bin/vela-sample"]

Publishing

In order to run the plugin in a pipeline, we’ll need to make sure we build and publish it to a Docker registry:

# build the image
docker build -t target/vela-sample:go .

# publish the image
docker push target/vela-sample:go

Troubleshooting

To verify that the plugin performs the desired task, it can be executed locally via the command line:

docker run --rm \
  -e PARAMETER_BODY="This is a sample Vela plugin written with Go" \
  -e PARAMETER_METHOD="POST" \
  -e PARAMETER_URL="http://vela.localhost.com" \
  target/vela-sample:go

Usage

After publishing the image to a Docker registry, it can be referenced in a pipeline:

version: "1"

steps:
  - name: sample go plugin
    image: target/vela-sample:go
    pull: always
    parameters:
      url: http://vela.localhost.com
      method: POST
      body: |
        This is a sample Vela plugin written with Go        
Last modified September 16, 2022: chore: use main as default (#324) (400aa851)