github.com/GoogleCloudPlatform/terraformer@v0.8.18/providers/digitalocean/ssh_key.go (about)

     1  // Copyright 2019 The Terraformer Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package digitalocean
    16  
    17  import (
    18  	"context"
    19  	"strconv"
    20  
    21  	"github.com/GoogleCloudPlatform/terraformer/terraformutils"
    22  	"github.com/digitalocean/godo"
    23  )
    24  
    25  type SSHKeyGenerator struct {
    26  	DigitalOceanService
    27  }
    28  
    29  func (g SSHKeyGenerator) listKeys(ctx context.Context, client *godo.Client) ([]godo.Key, error) {
    30  	list := []godo.Key{}
    31  
    32  	// create options. initially, these will be blank
    33  	opt := &godo.ListOptions{}
    34  	for {
    35  		keys, resp, err := client.Keys.List(ctx, opt)
    36  		if err != nil {
    37  			return nil, err
    38  		}
    39  
    40  		list = append(list, keys...)
    41  
    42  		// if we are at the last page, break out the for loop
    43  		if resp.Links == nil || resp.Links.IsLastPage() {
    44  			break
    45  		}
    46  
    47  		page, err := resp.Links.CurrentPage()
    48  		if err != nil {
    49  			return nil, err
    50  		}
    51  
    52  		// set the page we want for the next request
    53  		opt.Page = page + 1
    54  	}
    55  
    56  	return list, nil
    57  }
    58  
    59  func (g SSHKeyGenerator) createResources(keyList []godo.Key) []terraformutils.Resource {
    60  	var resources []terraformutils.Resource
    61  	for _, key := range keyList {
    62  		resources = append(resources, terraformutils.NewSimpleResource(
    63  			strconv.Itoa(key.ID),
    64  			key.Name,
    65  			"digitalocean_ssh_key",
    66  			"digitalocean",
    67  			[]string{}))
    68  	}
    69  	return resources
    70  }
    71  
    72  func (g *SSHKeyGenerator) InitResources() error {
    73  	client := g.generateClient()
    74  	output, err := g.listKeys(context.TODO(), client)
    75  	if err != nil {
    76  		return err
    77  	}
    78  	g.Resources = g.createResources(output)
    79  	return nil
    80  }