dockerfilegenerator

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 14, 2020 License: GPL-3.0 Imports: 8 Imported by: 1

README

dfg - Dockerfile Generator

dfg is both a go library and an executable that produces valid Dockerfiles using various input channels.

Build Status GoDoc Coverage Status Go Report Card Mentioned in Awesome Go

Table of Contents

Overview

dfg is a Dockerfile generator that accepts input data from various sources, produces and redirects the generated Dockerfile to an output target such as a file or stdout.

It is especially useful for generating Dockerfile instructions conditionally since Dockerfile language has no control flow logic.

Installation

Installing as an Executable
  • MacOS
curl -o dfg -L https://github.com/ozankasikci/dockerfile-generator/releases/download/v0.1.0/dfg_v0.1.0_darwin_amd64
chmod +x dfg && sudo mv dfg /usr/local/bin
  • Linux
curl -o dfg -L https://github.com/ozankasikci/dockerfile-generator/releases/download/v0.1.0/dfg_v0.1.0_linux_amd64
chmod +x dfg && sudo mv dfg /usr/local/bin
  • Windows
curl -o dfg.exe -L https://github.com/ozankasikci/dockerfile-generator/releases/download/v0.1.0/dfg_v0.1.0_windows_amd64.exe
Installing as a Library

go get -u github.com/ozankasikci/dockerfile-generator

Getting Started

Using dfg as an Executable

Available commands:

dfg generate --input path/to/yaml --out Dockerfile generates a file named Dockerfile

dfg generate --input path/to/yaml --target-field ".server.dockerfile" --out Dockerfile generates a file named Dockerfile reading the .server.dockerfile field of the YAML file.

dfg generate --help lists available flags

Using dfg as a Library

When using dfg as a go library, you need to pass a []dfg.Stage slice as data. This approach enables and encourages multi staged Dockerfiles. Dockerfile instructions will be generated in the same order as in the []dfg.Instruction slice.

Some Instructions accept a runForm field which specifies if the Instruction should be run in the shell form or the exec form. If the runForm is not specified, it will be chosen based on Dockerfile best practices.

For detailed usage example please see Library Usage Example

Examples

Single YAML File per Dockerfile Example
stages:
  final:
    - from:
        image: kstaken/apache2
    - run:
        runForm: shell
        params:
          - apt-get update &&
          - apt-get install -y
          - php5
          - libapache2-mod-php5 &&
          - apt-get clean &&
          - rm -rf /var/lib/apt/lists/*
    - cmd:
        params:
          - /usr/sbin/apache2
          - -D
          - FOREGROUND

Use dfg as binary:

dfg generate -i ./example-input-files/apache-php.yaml --stdout

Or as a library

data, err := dfg.NewDockerFileDataFromYamlFile("./example-input-files/apache-php.yaml")
tmpl := dfg.NewDockerfileTemplate(data)
err = tmpl.Render(output)
Output
FROM kstaken/apache2
RUN apt-get update && apt-get install -y php5 libapache2-mod-php5 && apt-get clean && rm -rf /var/lib/apt/lists/*
CMD ["/usr/sbin/apache2", "-D", "FOREGROUND"]
YAML File Example With Multiple Configurations (Allows using an existing YAML file)
someConfig:
  key: value
serverConfig:
  dockerfile:
    stages:
      final:
        - from:
            image: kstaken/apache2
        - run:
            runForm: shell
            params:
              - apt-get update &&
              - apt-get clean &&
              - rm -rf /var/lib/apt/lists/*

Use dfg as binary:

dfg generate -i ./example-input-files/test-input-with-target-key-6.yaml --target-field ".serverConfig.dockerfile" --stdout

Or as a library

data, err := dfg.NewDockerFileDataFromYamlField("./example-input-files/test-input-with-target-key-6.yaml", ".serverConfig.dockerfile")
tmpl := dfg.NewDockerfileTemplate(data)
err = tmpl.Render(output)
Output
FROM kstaken/apache2
RUN apt-get update && apt-get clean && rm -rf /var/lib/apt/lists/*
Library Usage Example
package main

import dfg "github.com/ozankasikci/dockerfile-generator"

func main() {
	data := &dfg.DockerfileData{
		Stages: []dfg.Stage{
			// Stage 1 - Builder Image
			// An instruction is just an interface, so you can pass custom structs as well
			[]dfg.Instruction{
				dfg.From{
					Image: "golang:1.7.3", As: "builder",
				},
				dfg.User{
					User: "ozan",
				},
				dfg.Workdir{
					Dir: "/go/src/github.com/ozankasikci/dockerfile-generator/",
				},
				dfg.RunCommand{
					Params: []string{"go", "get", "-d", "-v", "golang.org/x/net/html"},
				},
				dfg.CopyCommand{
					Sources: []string{"app.go"}, Destination: ".",
				},
				dfg.RunCommand{
					Params: []string{"CGO_ENABLED=0", "GOOS=linux", "go", "build", "-a", "-installsuffix", "cgo", "-o", "app", "."},
				},
			},
			// Stage 2 - Final Image
			[]dfg.Instruction{
				dfg.From{
					Image: "alpine:latest", As: "final",
				},
				dfg.RunCommand{
					Params: []string{"apk", "--no-cache", "add", "ca-certificates"},
				},
				dfg.User{
					User: "root", Group: "admin",
				},
				dfg.Workdir{
					Dir: "/root/",
				},
				dfg.CopyCommand{
					From: "builder", Sources: []string{"/go/src/github.com/ozankasikci/dockerfile-generator/app"}, Destination: ".",
				},
				dfg.Cmd{
					Params: []string{"./app"},
				},
			},
		},
	}
	tmpl := dfg.NewDockerfileTemplate(data)
	
	// write to a file
	file, err := os.Create("Dockerfile")
	err = tmpl.Render(file)
	
	// or write to stdout
	err = tmpl.Render(os.Stdout)
}
Output
FROM golang:1.7.3 as builder
USER ozan
WORKDIR /go/src/github.com/ozankasikci/dockerfile-generator/
RUN go get -d -v golang.org/x/net/html
COPY app.go .
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o app .

FROM alpine:latest as final
RUN apk --no-cache add ca-certificates
USER root:admin
WORKDIR /root/
COPY --from=builder /go/src/github.com/ozankasikci/dockerfile-generator/app .
CMD ["./app"]

TODO

  • Add reading Dockerfile data from an existing yaml file support
  • Implement json file input channel
  • Implement stdin input channel
  • Implement toml file input channel

Documentation

Overview

Package dockerfilegenerator is a Dockerfile generation library. It receives any kind of Dockerfile instructions and spits out a generated Dockerfile.

Index

Constants

View Source
const (
	// ExecForm is essentially a json array of string, e.g. ["echo", "1"]
	ExecForm RunForm = "ExecForm"

	// ShellForm is the form of a usual terminal command, e.g. echo 1
	ShellForm RunForm = "ShellForm"

	// RunCommandDefaultRunForm is the default RunForm for RunCommand
	RunCommandDefaultRunForm = ShellForm

	// CmdDefaultRunForm is the default RunForm for Cmd
	CmdDefaultRunForm = ExecForm

	// EntrypointDefaultRunForm is the default RunForm for Entrypoint
	EntrypointDefaultRunForm = ExecForm
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Arg

type Arg struct {
	Name        string `yaml:"name"`
	Value       string `yaml:"value"`
	Test        bool   `yaml:"test,omitempty"`
	EnvVariable bool   `yaml:"envVariable,omitempty"`
}

Arg represents a Dockerfile instruction, see https://docs.docker.com/engine/reference/builder/#arg

func (Arg) Render

func (a Arg) Render() string

Render returns a string in the form of ARG <name>[=<default value>]

type Cmd

type Cmd struct {
	Params  `yaml:"params"`
	RunForm `yaml:"runForm"`
}

Cmd represents a Dockerfile instruction, see https://docs.docker.com/engine/reference/builder/#cmd

func (Cmd) Render

func (c Cmd) Render() string

Render returns a string in the form of CMD ["executable","param1","param2"]

type CopyCommand

type CopyCommand struct {
	Sources     []string `yaml:"sources"`
	Destination string   `yaml:"destination"`
	Chown       string   `yaml:"chown"`
	From        string   `yaml:"from"`
}

CopyCommand represents a Dockerfile instruction, see https://docs.docker.com/engine/reference/builder/#copy

func (CopyCommand) Render

func (c CopyCommand) Render() string

Render returns a string in the form of COPY [--chown=<user>:<group>] <src>... <dest>

type DockerfileData

type DockerfileData struct {
	Stages []Stage `yaml:"stages,omitempty"`
}

DockerfileData struct can hold multiple stages for a multi-staged Dockerfile Check https://docs.docker.com/develop/develop-images/multistage-build/ for more information

func NewDockerFileDataFromYamlField added in v1.0.0

func NewDockerFileDataFromYamlField(filename, targetField string) (*DockerfileData, error)

NewDockerFileDataFromYamlField reads a YAML file and tries to extract Dockerfile data from the specified targetField option, examples: --target-field ".dev.dockerfileConfig" --target-field ".serverConfigs[0].docker.server"

func NewDockerFileDataFromYamlFile

func NewDockerFileDataFromYamlFile(filename string) (*DockerfileData, error)

NewDockerFileDataFromYamlFile reads a file and return a *DockerfileData

type DockerfileDataYaml

type DockerfileDataYaml struct {
	Stages map[string]Stage `yaml:"stages"`
}

DockerfileDataYaml is used to decode yaml data. It has a Stages map instead of a slice for that purpose.

type DockerfileTemplate

type DockerfileTemplate struct {
	Data *DockerfileData
}

DockerfileTemplate defines the template struct that generates Dockerfile output

func NewDockerfileTemplate

func NewDockerfileTemplate(data *DockerfileData) *DockerfileTemplate

NewDockerfileTemplate return a new NewDockerfileTemplate instance

func (*DockerfileTemplate) Render

func (d *DockerfileTemplate) Render(writer io.Writer) error

Render iterates through the given dockerfile instruction instances and executes the template. The output would be a generated Dockerfile.

type Entrypoint

type Entrypoint struct {
	Params  `yaml:"params"`
	RunForm `yaml:"runForm"`
}

Entrypoint represents a Dockerfile instruction, see https://docs.docker.com/engine/reference/builder/#entrypoint

func (Entrypoint) Render

func (e Entrypoint) Render() string

Render returns a string in the form of ENTRYPOINT ["executable", "param1", "param2"]

type EnvVariable

type EnvVariable struct {
	Name  string `yaml:"name"`
	Value string `yaml:"value"`
}

EnvVariable represents a Dockerfile instruction, see https://docs.docker.com/engine/reference/builder/#env

func (EnvVariable) Render

func (e EnvVariable) Render() string

Render returns a string in the form of ENV <key> <value>

type From

type From struct {
	Image string `yaml:"image"`
	As    string `yaml:"as"`
}

From represents a Dockerfile instruction, see https://docs.docker.com/engine/reference/builder/#from

func (From) Render

func (f From) Render() string

Render returns a string in the form of FROM <image> [AS <name>]

type HealthCheck

type HealthCheck struct {
	Params `yaml:"params"`
}

HealthCheck represents a Dockerfile instruction, see https://docs.docker.com/engine/reference/builder/#healthcheck

func (HealthCheck) Render

func (h HealthCheck) Render() string

Render returns a string in the form of HEALTHCHECK [OPTIONS] CMD command

type Instruction

type Instruction interface {
	Render() string
}

Instruction represents a Dockerfile instruction, e.g. FROM alpine:latest

type Label

type Label struct {
	Name  string `yaml:"name"`
	Value string `yaml:"value"`
}

Label represents a Dockerfile instruction, see https://docs.docker.com/engine/reference/builder/#from

func (Label) Render

func (l Label) Render() string

Render returns a string in the form of LABEL <key>=<value>

type Onbuild

type Onbuild struct {
	Params `yaml:"params"`
}

Onbuild represents a Dockerfile instruction, see https://docs.docker.com/engine/reference/builder/#onbuuild

func (Onbuild) Render

func (o Onbuild) Render() string

Render returns a string in the form of ONBUILD [INSTRUCTION]

type Params

type Params []string

Params is struct that supports rendering exec and shell form string

func (Params) ExecForm

func (p Params) ExecForm() string

ExecForm joins params slice in exec form

func (Params) ShellForm

func (p Params) ShellForm() string

ShellForm joins params slice in shell form

type RunCommand

type RunCommand struct {
	Params  `yaml:"params"`
	RunForm `yaml:"runForm"`
}

RunCommand represents a Dockerfile instruction, see https://docs.docker.com/engine/reference/builder/#run

func (RunCommand) Render

func (r RunCommand) Render() string

Render returns a string in the form of RUN <command>

type RunForm

type RunForm string

RunForm specifies in which form the instruction string should be constructed. Check Dockerfile exec and shell forms for more information

type Shell

type Shell struct {
	Params `yaml:"params"`
}

Shell represents a Dockerfile instruction, see https://docs.docker.com/engine/reference/builder/#shell

func (Shell) Render

func (s Shell) Render() string

Render returns a string in the form of SHELL ["executable", "parameters"]

type Stage

type Stage []Instruction

Stage is a set of instructions, the purpose is to keep the order of the given instructions and generate a Dockerfile using the output of these instructions

func (*Stage) UnmarshalYAML

func (s *Stage) UnmarshalYAML(unmarshal func(interface{}) error) error

UnmarshalYAML implements an interface to let go-yaml be able to decode Stages in to Stage struct

type User

type User struct {
	User  string `yaml:user`
	Group string `yaml:group`
}

User represents a Dockerfile instruction, see https://docs.docker.com/engine/reference/builder/#user

func (User) Render

func (u User) Render() string

Render returns a string in the form of WORKDIR /path/to/workdir

type Volume

type Volume struct {
	Source      string `yaml:"source"`
	Destination string `yaml:"destination"`
}

Volume represents a Dockerfile instruction, see https://docs.docker.com/engine/reference/builder/#volume

func (Volume) Render

func (v Volume) Render() string

Render returns a string in the form of VOLUME <source> <destination>

type Workdir

type Workdir struct {
	Dir string `yaml:"dir"`
}

Workdir represents a Dockerfile instruction, see https://docs.docker.com/engine/reference/builder/#workdir

func (Workdir) Render

func (w Workdir) Render() string

Render returns a string in the form of WORKDIR /path/to/workdir

Directories

Path Synopsis
cmd
dfg

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL