How to reduce Yaml boilerplate

#1

As your configuration files become more complex, you may find they become more difficult to manage and update. Drone provides command-line support and plugin support for Jsonnet, a data templating language, which can help simplify complex yaml files. Jsonnet provides support for functions, variables, mixins, imports and more.

Example Jsonnet file uses a function to create step based on input parameters. This can be used to avoid copy/paste duplication of steps in your configuration:

local docker(name, branch, tag) = {
  name: name,
  image: "plugins/docker",
  settings: {
    repo: "octocat/hello-world",
    tags: tag,
    when: {
      branch: branch 
    }
  }
};

{
  kind: "pipeline",
  name: "default",
  steps: [
    {
      name: "build",
      image: "golang",
      commands: [ "go build", "go test" ],
    },
    docker("build-master", "master", "latest"),
    docker("build-develop", "develop", "develop"),
  ]
}

The above Jsonnet file can be convereted to a Yaml configuration file using the official Jsonnet command line utility or by using the Drone Command Line utility:

$ drone jsonnet --stdout

---
kind: pipeline
name: default

platform:
  os: linux
  arch: amd64

steps:
- name: build
  image: golang
  commands:
  - go build
  - go test

- name: build-master
  image: plugins/docker
  settings:
    repo: octocat/hello-world
    tags: latest
    when:
      branch: master

- name: build-develop
  image: plugins/docker
  settings:
    repo: octocat/hello-world
    tags: develop
    when:
      branch: develop

...

Drone can natively parse jsonnet files if you enable the below configuration parameter. Note that includes and imports are not supported. You will also need to rename your configuration file to .drone.jsonnet and update your repository settings in the user interface accordingly.

DRONE_JSONNET_ENABLED=true
2 Likes

Publish Docker image to different repos based on branch?
#2

The example results in:

$ drone jsonnet --stdout
---
kind: pipeline
name: default

platform:
  os: linux
  arch: amd64

steps:
- name: build
  image: golang
  commands:
  - go build
  - go test

- name: build-master
  image: plugins/docker
  settings:
    repo: octocat/hello-world
    tags: latest
    when:
      ~

- name: build-develop
  image: plugins/docker
  settings:
    repo: octocat/hello-world
    tags: develop
    when:
      ~
...
0 Likes

#3

Is Jsonnet and other configuration plugins part of Drone Enterprise version or are they available in CE as well?

0 Likes

#4

@strygin the example I provided came directly from the Drone CLI. Did you check to ensure you are running the latest version of the CLI prior to testing?

0 Likes

#5

Thanks, upgrading from 1.0.1 to 1.0.6 solved the problem :slight_smile:

1 Like