Skip to content

Commit

Permalink
Add Helm Chart deployment and probes
Browse files Browse the repository at this point in the history
  • Loading branch information
criscola committed Jan 27, 2022
1 parent fb35865 commit 3f8c3ad
Show file tree
Hide file tree
Showing 14 changed files with 357 additions and 10 deletions.
25 changes: 25 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Build the manager binary
FROM golang:1.17 as builder

WORKDIR /workspace
# Copy the Go Modules manifests
COPY go.mod go.mod
COPY go.sum go.sum
# cache deps before building and copying source so that we don't need to re-download as much
# and so that source changes don't invalidate our downloaded layer
RUN go mod download

# Copy the go source
COPY . .

# Build
RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 GO111MODULE=on go build -a -o cloudflare-ddns main.go

# Use distroless as minimal base image to package the manager binary
# Refer to https://github.com/GoogleContainerTools/distroless for more details
FROM gcr.io/distroless/static:nonroot
WORKDIR /
COPY --from=builder /workspace/cloudflare-ddns .
USER 65532:65532

ENTRYPOINT ["/cloudflare-ddns"]
7 changes: 4 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,9 @@ You can specify your configuration by means of a super simple `yaml` configurati
- [ ] Allow DNS records to be created if not present already
- [ ] Update DNS records concurrently instead of one after the other
- [x] Logging & error handling
- [ ] Allow configuring which DNS record to update manually
- [x] Allow configuring which DNS records to update manually
- [ ] CLI flags
- [ ] Docker deployment
- [ ] Kubernetes Helm Chart deployment
- [ ] Docker Compose deployment
- [x] Kubernetes Helm Chart deployment
- [x] Readiness/liveness probes
- [ ] API key and account email auth option
23 changes: 23 additions & 0 deletions charts/cloudflare-ddns/.helmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Patterns to ignore when building packages.
# This supports shell glob matching, relative path matching, and
# negation (prefixed with !). Only one pattern per line.
.DS_Store
# Common VCS dirs
.git/
.gitignore
.bzr/
.bzrignore
.hg/
.hgignore
.svn/
# Common backup files
*.swp
*.bak
*.tmp
*.orig
*~
# Various IDEs
.project
.idea/
*.tmproj
.vscode/
24 changes: 24 additions & 0 deletions charts/cloudflare-ddns/Chart.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
apiVersion: v2
name: cloudflare-ddns
description: A Dynamic DNS for Cloudflare that allows your zones to be constantly up-to-date with your constantly changing public IP.

# A chart can be either an 'application' or a 'library' chart.
#
# Application charts are a collection of templates that can be packaged into versioned archives
# to be deployed.
#
# Library charts provide useful utilities or functions for the chart developer. They're included as
# a dependency of application charts to inject those utilities and functions into the rendering
# pipeline. Library charts do not define any templates and therefore cannot be deployed.
type: application

# This is the chart version. This version number should be incremented each time you make changes
# to the chart and its templates, including the app version.
# Versions are expected to follow Semantic Versioning (https://semver.org/)
version: 0.1.0

# This is the version number of the application being deployed. This version number should be
# incremented each time you make changes to the application. Versions are not expected to
# follow Semantic Versioning. They should reflect the version the application is using.
# It is recommended to use it with quotes.
appVersion: "0.1.0"
1 change: 1 addition & 0 deletions charts/cloudflare-ddns/templates/NOTES.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Done.
62 changes: 62 additions & 0 deletions charts/cloudflare-ddns/templates/_helpers.tpl
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
{{/*
Expand the name of the chart.
*/}}
{{- define "cloudflare-ddns.name" -}}
{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" }}
{{- end }}

{{/*
Create a default fully qualified app name.
We truncate at 63 chars because some Kubernetes name fields are limited to this (by the DNS naming spec).
If release name contains chart name it will be used as a full name.
*/}}
{{- define "cloudflare-ddns.fullname" -}}
{{- if .Values.fullnameOverride }}
{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" }}
{{- else }}
{{- $name := default .Chart.Name .Values.nameOverride }}
{{- if contains $name .Release.Name }}
{{- .Release.Name | trunc 63 | trimSuffix "-" }}
{{- else }}
{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" }}
{{- end }}
{{- end }}
{{- end }}

{{/*
Create chart name and version as used by the chart label.
*/}}
{{- define "cloudflare-ddns.chart" -}}
{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" }}
{{- end }}

{{/*
Common labels
*/}}
{{- define "cloudflare-ddns.labels" -}}
helm.sh/chart: {{ include "cloudflare-ddns.chart" . }}
{{ include "cloudflare-ddns.selectorLabels" . }}
{{- if .Chart.AppVersion }}
app.kubernetes.io/version: {{ .Chart.AppVersion | quote }}
{{- end }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
{{- end }}

{{/*
Selector labels
*/}}
{{- define "cloudflare-ddns.selectorLabels" -}}
app.kubernetes.io/name: {{ include "cloudflare-ddns.name" . }}
app.kubernetes.io/instance: {{ .Release.Name }}
{{- end }}

{{/*
Create the name of the service account to use
*/}}
{{- define "cloudflare-ddns.serviceAccountName" -}}
{{- if .Values.serviceAccount.create }}
{{- default (include "cloudflare-ddns.fullname" .) .Values.serviceAccount.name }}
{{- else }}
{{- default "default" .Values.serviceAccount.name }}
{{- end }}
{{- end }}
10 changes: 10 additions & 0 deletions charts/cloudflare-ddns/templates/configmap.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
apiVersion: v1
data:
config.yaml: |-
{{ .Values.config | toYaml | indent 4 | trim }}
kind: ConfigMap
metadata:
name: config
namespace: {{ .Release.Namespace }}
labels:
{{- include "cloudflare-ddns.labels" . | nindent 4 }}
67 changes: 67 additions & 0 deletions charts/cloudflare-ddns/templates/deployment.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
apiVersion: apps/v1
kind: Deployment
metadata:
name: {{ include "cloudflare-ddns.fullname" . }}
labels:
{{- include "cloudflare-ddns.labels" . | nindent 4 }}
spec:
replicas: {{ .Values.replicaCount }}
selector:
matchLabels:
{{- include "cloudflare-ddns.selectorLabels" . | nindent 6 }}
template:
metadata:
{{- with .Values.podAnnotations }}
annotations:
{{- toYaml . | nindent 8 }}
{{- end }}
labels:
{{- include "cloudflare-ddns.selectorLabels" . | nindent 8 }}
spec:
{{- with .Values.imagePullSecrets }}
imagePullSecrets:
{{- toYaml . | nindent 8 }}
{{- end }}
serviceAccountName: {{ include "cloudflare-ddns.serviceAccountName" . }}
securityContext:
{{- toYaml .Values.podSecurityContext | nindent 8 }}
containers:
- name: {{ .Chart.Name }}
securityContext:
{{- toYaml .Values.securityContext | nindent 12 }}
image: "{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}"
imagePullPolicy: {{ .Values.image.pullPolicy }}
livenessProbe:
httpGet:
path: /live
port: 8086
initialDelaySeconds: 5
periodSeconds: 5
readinessProbe:
httpGet:
path: /ready
port: 8086
periodSeconds: 5
resources:
{{- toYaml .Values.resources | nindent 12 }}
volumeMounts:
- mountPath: /config.yaml
name: config-volume
subPath: config.yaml
volumes:
- name: config-volume
configMap:
name: config

{{- with .Values.nodeSelector }}
nodeSelector:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with .Values.affinity }}
affinity:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with .Values.tolerations }}
tolerations:
{{- toYaml . | nindent 8 }}
{{- end }}
12 changes: 12 additions & 0 deletions charts/cloudflare-ddns/templates/serviceaccount.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{{- if .Values.serviceAccount.create -}}
apiVersion: v1
kind: ServiceAccount
metadata:
name: {{ include "cloudflare-ddns.serviceAccountName" . }}
labels:
{{- include "cloudflare-ddns.labels" . | nindent 4 }}
{{- with .Values.serviceAccount.annotations }}
annotations:
{{- toYaml . | nindent 4 }}
{{- end }}
{{- end }}
68 changes: 68 additions & 0 deletions charts/cloudflare-ddns/values.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
# Default values for cloudflare-ddns.
# This is a YAML-formatted file.
# Declare variables to be passed into your templates.

replicaCount: 1

image:
repository: criscola/cloudflare-ddns
pullPolicy: IfNotPresent
# Overrides the image tag whose default is the chart appVersion.
tag: ""

imagePullSecrets: []
nameOverride: ""
fullnameOverride: ""

serviceAccount:
# Specifies whether a service account should be created
create: true
# Annotations to add to the service account
annotations: {}
# The name of the service account to use.
# If not set and create is true, a name is generated using the fullname template
name: ""

podAnnotations: {}

podSecurityContext: {}
# fsGroup: 2000

securityContext: {}
# capabilities:
# drop:
# - ALL
# readOnlyRootFilesystem: true
# runAsNonRoot: true
# runAsUser: 1000

resources: {}
# We usually recommend not to specify default resources and to leave this as a conscious
# choice for the user. This also increases chances charts run on environments with little
# resources, such as Minikube. If you do want to specify resources, uncomment the following
# lines, adjust them as necessary, and remove the curly braces after 'resources:'.
# limits:
# cpu: 100m
# memory: 128Mi
# requests:
# cpu: 100m
# memory: 128Mi

nodeSelector: {}

tolerations: []

affinity: {}

config:
api_token: "your api token with Edit DNS enabled"
refresh_interval: 60
zones:
- zone_id: "your zone id"
proxied: true
ipv6: false
- zone_id: "your zone id"
ipv6: false
explicit_records: # pro-tip: use CNAME records if possible
- name: ""
- name: "ssh"
33 changes: 30 additions & 3 deletions cmd/root.go
Original file line number Diff line number Diff line change
@@ -1,16 +1,19 @@
/*
Copyright © 2022 NAME HERE <EMAIL ADDRESS>
Copyright © 2022 Cristiano Colangelo (criscola)
*/
package cmd

import (
"context"
"fmt"
"github.com/cloudflare/cloudflare-go"
"github.com/criscola/cloudflare-ddns/ddns"
"github.com/heptiolabs/healthcheck"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"go.uber.org/zap"
"net/http"
"os"
)

Expand Down Expand Up @@ -41,10 +44,10 @@ func Execute() {
}

func init() {
// init logger
initLogger()
initConfig()
initClient()
initProbes()

// TODO: CLI Flags e.g. debug mode
// rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cloudflare-ddns.yaml)")
Expand All @@ -58,7 +61,7 @@ func initLogger() {
func initConfig() {
viper.SetConfigName("config") // name of config file (without extension)
viper.SetConfigType("yaml") // REQUIRED if the config file does not have the extension in the name
viper.AddConfigPath("/etc/cloudflare-ddns/") // path to look for the config file in
viper.AddConfigPath("/etc/cloudflare-ddns") // path to look for the config file in
viper.AddConfigPath("$HOME/.cloudflare-ddns") // call multiple times to add many search paths
viper.AddConfigPath(".") // optionally look for config in the working directory
// TODO: Error handling, config validation, dependency injection
Expand Down Expand Up @@ -92,3 +95,27 @@ func initClient() {
}
logger.Debug("cfClient initialized successfully")
}

func initProbes() {
health := healthcheck.NewHandler()
// If app cannot reach 1.1.1.1, readiness probe will fail
checkPublicIpResolver := func() error {
resp, err := http.Get(ddns.PublicIpPage)
if err != nil {
return err
}
if resp.StatusCode < 200 || resp.StatusCode > 299 {
return fmt.Errorf("public IP resolver (%s) returned status code %d",
ddns.PublicIpPage, resp.StatusCode)
}
return nil
}
health.AddReadinessCheck("public-ip-resolver-webpage", checkPublicIpResolver)
go func() {
err := http.ListenAndServe("0.0.0.0:8086", health)
if err != nil {
logger.Fatalf("cannot start webserver on port 8086")
}
logger.Debug("probes started successfully")
}()
}
Loading

0 comments on commit 3f8c3ad

Please sign in to comment.