Skip to content

Instantly share code, notes, and snippets.

@oprietop
Created July 8, 2021 12:41
Show Gist options
  • Save oprietop/0421ee9a1f9652d9ce979de316bac98e to your computer and use it in GitHub Desktop.
Save oprietop/0421ee9a1f9652d9ce979de316bac98e to your computer and use it in GitHub Desktop.
Copy CI variables between projects on the same gitlab instance
package main
import (
"net/http"
"net/url"
"fmt"
"os"
"log"
"time"
"encoding/json"
"strings"
"strconv"
)
// Main struct
type RunTasks struct {
gitHost string
gitSrcProjId string
gitDstProjId string
gitToken string
client *http.Client
}
// Helper for handling errors without bailing out
func errChk(err error) {
if err != nil {
log.Printf("Error: %v", err)
}
}
// Perform a Gitlab API call
func (rt *RunTasks) apiCall(uri string, token string, method string, form map[string]string) (result []interface{}) {
log.Printf("Connecting to: %s", uri)
data := url.Values{}
for k, v := range form {
data.Set(k, v)
}
req, _ := http.NewRequest(method, uri, strings.NewReader(data.Encode()))
req.Header.Set("PRIVATE-TOKEN", token)
res, err := rt.client.Do(req)
errChk(err)
if res.Body != nil {
defer res.Body.Close()
}
log.Printf("Status: %s", res.Status)
_ = json.NewDecoder(res.Body).Decode(&result)
return result
}
// Initinalize a new Runtasks struct
func NewRunTasks() *RunTasks {
// Parse Args
args := os.Args[1:]
if len(args) != 4 {
log.Fatal(os.Args[0], " <gitlab host> <gitlab token> <Src Project ID> <Dst Project ID>")
}
// Create a http client for connection reuse
client := &http.Client {
Timeout: 10 * time.Second,
}
return &RunTasks{
gitHost: args[0],
gitToken: args[1],
gitSrcProjId: args[2],
gitDstProjId: args[3],
client: client,
}
}
func main() {
// Initialize a RunTasks struct for this execution
rt := NewRunTasks()
log.Printf("%+v\n", rt)
url := "https://" + rt.gitHost + "/api/v4/projects/" + rt.gitSrcProjId + "/variables"
result := rt.apiCall(url, rt.gitToken, "GET", nil)
log.Printf("Found %d variables:", len(result))
for _, r := range result {
firstMap := r.(map[string]interface{})
fmt.Println(firstMap["key"], firstMap["value"], firstMap["masked"])
m := map[string]string{
"key": firstMap["key"].(string),
"value": firstMap["value"].(string),
"masked": strconv.FormatBool(firstMap["masked"].(bool)),
"protected": strconv.FormatBool(firstMap["protected"].(bool)),
}
log.Printf("Adding: %v", m)
url := "https://" + rt.gitHost + "/api/v4/projects/" + rt.gitDstProjId + "/variables"
_ = rt.apiCall(url, rt.gitToken, "POST", m)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment