|
1 | 1 | package ipam |
2 | 2 |
|
3 | 3 | import ( |
| 4 | + "context" |
| 5 | + "fmt" |
4 | 6 | "net" |
5 | 7 | "time" |
6 | 8 |
|
@@ -65,3 +67,58 @@ func diffSuppressFuncStandaloneIPandCIDR(_, oldValue, newValue string, _ *schema |
65 | 67 |
|
66 | 68 | return false |
67 | 69 | } |
| 70 | + |
| 71 | +type GetResourcePrivateIPsOptions struct { |
| 72 | + ResourceType *ipam.ResourceType |
| 73 | + ResourceID *string |
| 74 | + ResourceName *string |
| 75 | + PrivateNetworkID *string |
| 76 | +} |
| 77 | + |
| 78 | +// GetResourcePrivateIPs fetches the private IP addresses of a resource in a private network. |
| 79 | +func GetResourcePrivateIPs(ctx context.Context, m interface{}, region scw.Region, opts *GetResourcePrivateIPsOptions) ([]map[string]interface{}, error) { |
| 80 | + ipamAPI := ipam.NewAPI(meta.ExtractScwClient(m)) |
| 81 | + |
| 82 | + req := &ipam.ListIPsRequest{ |
| 83 | + Region: region, |
| 84 | + } |
| 85 | + |
| 86 | + if opts != nil { |
| 87 | + if opts.PrivateNetworkID != nil { |
| 88 | + req.PrivateNetworkID = opts.PrivateNetworkID |
| 89 | + } |
| 90 | + if opts.ResourceID != nil { |
| 91 | + req.ResourceID = opts.ResourceID |
| 92 | + } |
| 93 | + if opts.ResourceName != nil { |
| 94 | + req.ResourceName = opts.ResourceName |
| 95 | + } |
| 96 | + if opts.ResourceType != nil { |
| 97 | + req.ResourceType = *opts.ResourceType |
| 98 | + } |
| 99 | + } |
| 100 | + |
| 101 | + resp, err := ipamAPI.ListIPs(req, scw.WithContext(ctx)) |
| 102 | + if err != nil { |
| 103 | + return nil, fmt.Errorf("error fetching IPs from IPAM: %w", err) |
| 104 | + } |
| 105 | + |
| 106 | + if len(resp.IPs) == 0 { |
| 107 | + return nil, nil |
| 108 | + } |
| 109 | + |
| 110 | + ipList := make([]map[string]interface{}, 0, len(resp.IPs)) |
| 111 | + for _, ip := range resp.IPs { |
| 112 | + ipNet := ip.Address |
| 113 | + if ipNet.IP == nil { |
| 114 | + continue |
| 115 | + } |
| 116 | + ipMap := map[string]interface{}{ |
| 117 | + "id": regional.NewIDString(region, ip.ID), |
| 118 | + "address": ipNet.IP.String(), |
| 119 | + } |
| 120 | + ipList = append(ipList, ipMap) |
| 121 | + } |
| 122 | + |
| 123 | + return ipList, nil |
| 124 | +} |
0 commit comments