portainer

This commit is contained in:
qiaofeng1227 2023-10-19 17:10:16 +08:00
parent 4bdf16affa
commit 9dda38be08
2 changed files with 83 additions and 58 deletions

View File

@ -1,4 +1,4 @@
# modify time: 202310182230, you can modify here to trigger Docker Build action # modify time: 202310191713, you can modify here to trigger Docker Build action
# step1: Build entrypoint execute program init_portainer by golang # step1: Build entrypoint execute program init_portainer by golang
FROM golang:latest AS builder FROM golang:latest AS builder

View File

@ -6,6 +6,8 @@ import (
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"net/http" "net/http"
"net/url"
"strings"
"os" "os"
"time" "time"
) )
@ -18,8 +20,13 @@ const (
) )
type Endpoint struct { type Endpoint struct {
Name string `json:"Name"` Name string `json:"name"`
URL string `json:"URL"` URL string `json:"url"`
}
type EndpointCreation struct {
Name string `json:"name"`
EndpointCreationType int `json:"EndpointCreationType"`
} }
type AuthResponse struct { type AuthResponse struct {
@ -27,13 +34,45 @@ type AuthResponse struct {
} }
type Credentials struct { type Credentials struct {
Username string `json:"Username"` Username string `json:"username"`
Password string `json:"Password"` Password string `json:"password"`
} }
func main() { func main() {
var password string client := &http.Client{}
password, err := getPassword()
if err != nil {
fmt.Println("Failed to get password:", err)
return
}
token, err := authenticate(client, AdminUser, password)
if err != nil {
fmt.Println("Failed to authenticate:", err)
return
}
endpoints, err := queryEndpoints(client, token)
if err != nil {
fmt.Println("Failed to query endpoints:", err)
return
}
for _, endpoint := range endpoints {
if endpoint.Name == "local" && endpoint.URL == "unix:///var/run/docker.sock" {
fmt.Println("Endpoint exists, exiting...")
return
}
}
fmt.Println("Endpoint does not exist, creating...")
createEndpoint(client, token)
fmt.Println("Endpoint created successfully")
}
func getPassword() (string, error) {
for { for {
if _, err := os.Stat(CredentialLoc); os.IsNotExist(err) { if _, err := os.Stat(CredentialLoc); os.IsNotExist(err) {
fmt.Printf("%s does not exist, waiting for 3 seconds...\n", CredentialLoc) fmt.Printf("%s does not exist, waiting for 3 seconds...\n", CredentialLoc)
@ -42,99 +81,85 @@ func main() {
fmt.Printf("%s exists, proceeding...\n", CredentialLoc) fmt.Printf("%s exists, proceeding...\n", CredentialLoc)
data, err := ioutil.ReadFile(CredentialLoc) data, err := ioutil.ReadFile(CredentialLoc)
if err != nil { if err != nil {
fmt.Println("Failed to read file:", err) return "", err
return
} }
password = string(data) return string(data), nil
break
} }
} }
}
client := &http.Client{} func authenticate(client *http.Client, username, password string) (string, error) {
credentials := Credentials{Username: AdminUser, Password: password} credentials := Credentials{Username: username, Password: password}
credentialsJson, err := json.Marshal(credentials) credentialsJson, err := json.Marshal(credentials)
if err != nil { if err != nil {
fmt.Println("Failed to encode JSON:", err) return "", err
return
} }
req, err := http.NewRequest("POST", AuthURL, bytes.NewBuffer(credentialsJson)) req, err := http.NewRequest("POST", AuthURL, bytes.NewBuffer(credentialsJson))
req.Header.Set("Content-Type", "application/json") req.Header.Set("Content-Type", "application/json")
resp, err := client.Do(req) resp, err := client.Do(req)
if err != nil { if err != nil {
fmt.Println("Failed to make request:", err) return "", err
return
} }
defer resp.Body.Close() defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body) body, err := ioutil.ReadAll(resp.Body)
if err != nil { if err != nil {
fmt.Println("Failed to read response:", err) return "", err
return
} }
fmt.Printf("Received body: %s\n", string(body))
var authResponse AuthResponse var authResponse AuthResponse
err = json.Unmarshal(body, &authResponse) err = json.Unmarshal(body, &authResponse)
if err != nil { if err != nil {
fmt.Println("Failed to parse JSON:", err) return "", err
return
} }
fmt.Printf("Received JWT: %s\n", authResponse.Jwt) return authResponse.Jwt, nil
}
req, err = http.NewRequest("GET", EndpointURL, nil) func queryEndpoints(client *http.Client, token string) ([]Endpoint, error) {
req.Header.Set("Authorization", "Bearer "+authResponse.Jwt) req, err := http.NewRequest("GET", EndpointURL, nil)
resp, err = client.Do(req) req.Header.Set("Authorization", "Bearer "+token)
resp, err := client.Do(req)
if err != nil { if err != nil {
fmt.Println("Failed to make request:", err) return nil, err
return
} }
defer resp.Body.Close() defer resp.Body.Close()
body, err = ioutil.ReadAll(resp.Body) body, err := ioutil.ReadAll(resp.Body)
if err != nil { if err != nil {
fmt.Println("Failed to read response:", err) return nil, err
return
} }
var endpoints []Endpoint var endpoints []Endpoint
err = json.Unmarshal(body, &endpoints) err = json.Unmarshal(body, &endpoints)
if err != nil { if err != nil {
fmt.Println("Failed to parse JSON:", err) return nil, err
return
} }
for _, endpoint := range endpoints { return endpoints, nil
if endpoint.Name == "local" { }
fmt.Println("Endpoint exists, exiting...")
return func createEndpoint(client *http.Client, token string) error {
} data := url.Values{
"Name": {"local"},
"EndpointCreationType": {"1"},
} }
fmt.Println("Endpoint does not exist, creating...") req, err := http.NewRequest("POST", EndpointURL, strings.NewReader(data.Encode()))
endpoint := Endpoint{
Name: "local",
URL: "/var/run/docker.sock",
}
data, err := json.Marshal(endpoint)
if err != nil { if err != nil {
fmt.Println("Failed to encode JSON:", err) return err
return
} }
req, err = http.NewRequest("POST", EndpointURL, bytes.NewBuffer(data)) req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Authorization", "Bearer "+authResponse.Jwt) req.Header.Set("Authorization", "Bearer "+token)
resp, err = client.Do(req)
if err != nil { resp, err := client.Do(req)
fmt.Println("Failed to make request:", err)
return
}
if resp.StatusCode != http.StatusCreated { if resp.StatusCode != http.StatusCreated {
fmt.Println("Failed to create endpoint:", resp.Status) body, _ := ioutil.ReadAll(resp.Body)
} else { return fmt.Errorf("Failed to create endpoint: %s, Response body: %s", resp.Status, string(body))
fmt.Println("Endpoint created successfully")
} }
}
return nil
}