Recreate GitHub deploy key during bootstrap

pull/40/head
stefanprodan 5 years ago
parent 2a61befbfd
commit dca7b0ba91

@ -186,7 +186,7 @@ func bootstrapGitHubCmdRun(cmd *cobra.Command, args []string) error {
return fmt.Errorf("generating deploy key failed: %w", err) return fmt.Errorf("generating deploy key failed: %w", err)
} }
if err := createGitHubDeployKey(ctx, key, ghHostname, ghOwner, ghRepository, ghToken); err != nil { if err := createGitHubDeployKey(ctx, key, ghHostname, ghOwner, ghRepository, ghPath, ghToken); err != nil {
return err return err
} }
logSuccess("deploy key configured") logSuccess("deploy key configured")
@ -521,14 +521,54 @@ func generateGitHubDeployKey(ctx context.Context, kubeClient client.Client, url
return string(pair.PublicKey), nil return string(pair.PublicKey), nil
} }
func createGitHubDeployKey(ctx context.Context, key, hostname, owner, name, token string) error { func createGitHubDeployKey(ctx context.Context, key, hostname, owner, repository, targetPath, token string) error {
gh, err := makeGitHubClient(hostname, token) gh, err := makeGitHubClient(hostname, token)
if err != nil { if err != nil {
return err return err
} }
keyName := fmt.Sprintf("tk-%s", namespace) keyName := "tk"
if targetPath != "" {
keyName = fmt.Sprintf("tk-%s", targetPath)
}
// list deploy keys
keys, resp, err := gh.Repositories.ListKeys(ctx, owner, repository, nil)
if err != nil {
return fmt.Errorf("github list deploy keys error: %w", err)
}
if resp.StatusCode >= 300 {
return fmt.Errorf("github list deploy keys failed with status code: %s", resp.Status)
}
// check if the key exists
shouldCreateKey := true
var existingKey *github.Key
for _, k := range keys {
if k.Title != nil && k.Key != nil && *k.Title == keyName {
if *k.Key != key {
existingKey = k
} else {
shouldCreateKey = false
}
break
}
}
// delete existing key if the value differs
if existingKey != nil {
resp, err := gh.Repositories.DeleteKey(ctx, owner, repository, *existingKey.ID)
if err != nil {
return fmt.Errorf("github delete deploy key error: %w", err)
}
if resp.StatusCode >= 300 {
return fmt.Errorf("github delete deploy key failed with status code: %s", resp.Status)
}
}
// create key
if shouldCreateKey {
isReadOnly := true isReadOnly := true
_, _, err = gh.Repositories.CreateKey(ctx, owner, name, &github.Key{ _, _, err = gh.Repositories.CreateKey(ctx, owner, repository, &github.Key{
Title: &keyName, Title: &keyName,
Key: &key, Key: &key,
ReadOnly: &isReadOnly, ReadOnly: &isReadOnly,
@ -536,5 +576,7 @@ func createGitHubDeployKey(ctx context.Context, key, hostname, owner, name, toke
if err != nil { if err != nil {
return fmt.Errorf("github create deploy key error: %w", err) return fmt.Errorf("github create deploy key error: %w", err)
} }
}
return nil return nil
} }

Loading…
Cancel
Save