GitOps Commit Bot
Clones a repo, creates a feature branch, writes a generated config file, commits it, and pushes. This is the foundational pattern for GitOps config automation where infrastructure changes are driven by Git commits.
Input: A GitHub token and repository URL. Output: A new branch pushed with an automated config commit.
package main
import (
"fmt"
"os"
"time"
git "github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing"
"github.com/go-git/go-git/v5/plumbing/object"
"github.com/go-git/go-git/v5/plumbing/transport/http"
)
func main() {
token := os.Getenv("GITHUB_TOKEN")
repoURL := "https://github.com/org/infra-config.git"
dir, _ := os.MkdirTemp("", "gitops-*")
defer os.RemoveAll(dir)
auth := &http.BasicAuth{Username: "x-access-token", Password: token}
// Clone
repo, err := git.PlainClone(dir, false, &git.CloneOptions{
URL: repoURL,
Auth: auth,
})
if err != nil {
panic(err)
}
// Create branch
wt, _ := repo.Worktree()
branchName := fmt.Sprintf("auto/update-config-%d", time.Now().Unix())
err = wt.Checkout(&git.CheckoutOptions{
Branch: plumbing.NewBranchReferenceName(branchName),
Create: true,
})
if err != nil {
panic(err)
}
// Write a generated file
configContent := []byte(`replicas: 3
image: app:v2.1.0
env: production
`)
configPath := dir + "/k8s/deployment.yaml"
os.MkdirAll(dir+"/k8s", 0o755)
os.WriteFile(configPath, configContent, 0o644)
// Stage and commit
wt.Add("k8s/deployment.yaml")
hash, _ := wt.Commit("chore: update deployment config", &git.CommitOptions{
Author: &object.Signature{
Name: "GitOps Bot",
Email: "[email protected]",
When: time.Now(),
},
})
// Push
err = repo.Push(&git.PushOptions{Auth: auth})
if err != nil {
panic(err)
}
fmt.Printf("Pushed commit %s on branch %s\n", hash.String()[:8], branchName)
}