summaryrefslogtreecommitdiff
path: root/digitalocean/listDroplets.go
blob: a46be29313ca760cf75fa7c62445de5215878278 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package digitalocean

import (
	"context"
	"fmt"

	"golang.org/x/oauth2"

	"github.com/digitalocean/godo"
)

// ListDroplets fetches and prints out the droplets along with their IPv4 and IPv6 addresses.
func ListDroplets(token string) error {
	// OAuth token for authentication.
	tokenSource := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: token})

	// OAuth2 client.
	oauthClient := oauth2.NewClient(context.Background(), tokenSource)

	// DigitalOcean client.
	client := godo.NewClient(oauthClient)

	// Context.
	ctx := context.TODO()

	// List all droplets.
	droplets, _, err := client.Droplets.List(ctx, &godo.ListOptions{})
	if err != nil {
		return err
	}

	// Iterate over droplets and print their details.
	for _, droplet := range droplets {
		fmt.Printf("Droplet: %s\n", droplet.Name)
		for _, network := range droplet.Networks.V4 {
			if network.Type == "public" {
				fmt.Printf("IPv4: %s\n", network.IPAddress)
			}
		}
		for _, network := range droplet.Networks.V6 {
			if network.Type == "public" {
				fmt.Printf("IPv6: %s\n", network.IPAddress)
			}
		}
		fmt.Println("-------------------------")
	}

	return nil
}