refactor(gitea)!: switch init job to structured config as code

This commit is contained in:
Khue Doan 2022-03-24 09:54:26 +07:00
parent 86807062b2
commit 134c0b4902
4 changed files with 37 additions and 98 deletions

View File

@ -1,6 +1,9 @@
users: # TODO create user and access token
- name: renovate # users:
tokenSecretRef: renovate-secret # ??? # - name: renovate
# fullName: Renovate
# email: bot@renovateapp.com
# tokenSecretRef: renovate-secret # ???
organizations: organizations:
- name: ops - name: ops
description: Operations description: Operations
@ -15,19 +18,16 @@ repositories:
migrate: migrate:
source: https://github.com/khuedoan/homelab source: https://github.com/khuedoan/homelab
mirror: false mirror: false
webhooks: # TODO create webhook (use a global one?)
- http://gitea-webhook.tekton-pipelines:3000 # webhooks:
# - http://gitea-webhook.tekton-pipelines:3000
- name: blog - name: blog
owner: khuedoan owner: khuedoan
migrate: migrate:
source: https://github.com/khuedoan/blog source: https://github.com/khuedoan/blog
mirror: true mirror: true
webhooks:
- http://gitea-webhook.tekton-pipelines:3000
- name: backstage - name: backstage
owner: khuedoan owner: khuedoan
migrate: migrate:
source: https://github.com/khuedoan/backstage source: https://github.com/khuedoan/backstage
mirror: true mirror: true
webhooks:
- http://gitea-webhook.tekton-pipelines:3000

View File

@ -1,7 +1,8 @@
package main package main
// TODO WIP clean this up
import ( import (
"fmt"
"log" "log"
"os" "os"
@ -9,11 +10,6 @@ import (
"gopkg.in/yaml.v2" "gopkg.in/yaml.v2"
) )
type User struct {
Name string
TokenSecretRef string
}
type Organization struct { type Organization struct {
Name string Name string
Description string Description string
@ -27,11 +23,9 @@ type Repository struct {
Source string Source string
Mirror bool Mirror bool
} }
Webhooks []string
} }
type Config struct { type Config struct {
Users []User
Organizations []Organization Organizations []Organization
Repositories []Repository Repositories []Repository
} }
@ -40,7 +34,7 @@ func main() {
data, err := os.ReadFile("./config.yaml") data, err := os.ReadFile("./config.yaml")
if err != nil { if err != nil {
log.Fatalf("unable to read config file: %v", err) log.Fatalf("Unable to read config file: %v", err)
} }
config := Config{} config := Config{}
@ -51,15 +45,12 @@ func main() {
log.Fatalf("error: %v", err) log.Fatalf("error: %v", err)
} }
fmt.Println(config) gitea_host := os.Getenv("GITEA_HOST")
gitea_user := os.Getenv("GITEA_USER")
gitea_password := os.Getenv("GITEA_PASSWORD")
// TODO options := (gitea.SetBasicAuth(gitea_user, gitea_password))
url := "https://git.khuedoan.com" client, err := gitea.NewClient(gitea_host, options)
// url := "http://gitea-http:3000"
password := "thisisjustfortestingdude"
options := (gitea.SetBasicAuth("gitea_admin", password))
client, err := gitea.NewClient(url, options)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
@ -72,7 +63,7 @@ func main() {
}) })
if err != nil { if err != nil {
log.Printf("Create organization %s: %s", "testing", err) log.Printf("Create organization %s: %v", org.Name, err)
} }
} }
@ -89,11 +80,12 @@ func main() {
}) })
if err != nil { if err != nil {
log.Printf("Migrate %s/%s: %s", repo.Owner, repo.Name, err) log.Printf("Migrate %s/%s: %v", repo.Owner, repo.Name, err)
} }
} else { } else {
_, _, err = client.AdminCreateRepo(repo.Owner, gitea.CreateRepoOption{ _, _, err = client.AdminCreateRepo(repo.Owner, gitea.CreateRepoOption{
Name: repo.Name, Name: repo.Name,
// Description: "TODO",
Private: repo.Private, Private: repo.Private,
}) })
} }

View File

@ -1,64 +0,0 @@
#!/usr/bin/python
import json
import os
import subprocess
import sys
subprocess.check_call([sys.executable, "-m", "pip", "install", "requests"])
import requests
gitea_host = os.getenv('GITEA_HOST', "gitea-http:3000")
gitea_user = os.environ['GITEA_USER']
gitea_pass = os.environ['GITEA_PASSWORD']
seed_repo = "https://github.com/khuedoan/homelab"
org = "ops"
repo = "homelab"
gitea_url = f"http://{gitea_user}:{gitea_pass}@{gitea_host}"
headers = {
'Content-Type': 'application/json'
}
data_org = json.dumps({
'username': org
})
data_repo = json.dumps({
'clone_addr': seed_repo,
'uid': 1,
'repo_owner': org,
'repo_name': repo,
'mirror': True
})
resp = requests.post(
url=f"{gitea_url}/api/v1/admin/users/{gitea_user}/orgs",
headers=headers,
data=data_org
)
if resp.status_code == 201:
print(f"Created organization {org}")
elif resp.status_code == 422:
print(f"Organization already exists")
else:
print(f"Error creating organization {org} ({resp.status_code})")
print(resp.content)
sys.exit(1)
resp = requests.post(
url=f"{gitea_url}/api/v1/repos/migrate",
headers=headers,
data=data_repo
)
if resp.status_code == 201:
print(f"Created repository {json.loads(str(resp.content, 'utf8'))['html_url']}")
elif resp.status_code == 409:
print(f"Repository already exists")
else:
print(f"Error creating git repository ({resp.status_code})")
print(resp.content)
sys.exit(1)

View File

@ -1,7 +1,7 @@
apiVersion: batch/v1 apiVersion: batch/v1
kind: Job kind: Job # TODO switch to CronJob
metadata: metadata:
name: init-gitops-repo name: gitea-config
namespace: {{ .Release.Namespace }} namespace: {{ .Release.Namespace }}
annotations: annotations:
argocd.argoproj.io/sync-wave: "1" argocd.argoproj.io/sync-wave: "1"
@ -11,9 +11,11 @@ spec:
spec: spec:
restartPolicy: Never restartPolicy: Never
containers: containers:
- name: script - name: apply
image: python image: golang:1.17-alpine
env: env:
- name: GITEA_HOST
value: http://gitea-http:3000
- name: GITEA_USER - name: GITEA_USER
valueFrom: valueFrom:
secretKeyRef: secretKeyRef:
@ -24,9 +26,18 @@ spec:
secretKeyRef: secretKeyRef:
name: gitea-admin-secret name: gitea-admin-secret
key: password key: password
workingDir: /go/src/gitea-config
command: command:
- python - sh
- -c - -c
args: args:
- | - |
{{ .Files.Get "files/init_gitops_repo.py" | indent 14 }} go get .
go run .
volumeMounts:
- name: source
mountPath: /go/src/gitea-config
volumes:
- name: source
configMap:
name: gitea-config-source