github.com/GoogleCloudPlatform/terraformer@v0.8.18/providers/alicloud/key_pair.go (about)

     1  // Copyright 2018 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 alicloud
    16  
    17  import (
    18  	"github.com/GoogleCloudPlatform/terraformer/terraformutils"
    19  	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
    20  	"github.com/aliyun/alibaba-cloud-sdk-go/services/ecs"
    21  )
    22  
    23  // KeyPairGenerator Struct for generating AliCloud Key pair
    24  type KeyPairGenerator struct {
    25  	AliCloudService
    26  }
    27  
    28  func resourceFromKeyPair(keyPair ecs.KeyPair) terraformutils.Resource {
    29  	return terraformutils.NewResource(
    30  		keyPair.KeyPairName, // nolint
    31  		keyPair.KeyPairName+"__"+keyPair.KeyPairName, // nolint
    32  		"alicloud_key_pair",
    33  		"alicloud",
    34  		map[string]string{},
    35  		[]string{},
    36  		map[string]interface{}{},
    37  	)
    38  }
    39  
    40  // InitResources Gets the list of all key pair ids and generates resources
    41  func (g *KeyPairGenerator) InitResources() error {
    42  	client, err := g.LoadClientFromProfile()
    43  	if err != nil {
    44  		return err
    45  	}
    46  	remaining := 1
    47  	pageNumber := 1
    48  	pageSize := 10
    49  
    50  	allKeyPairs := make([]ecs.KeyPair, 0)
    51  
    52  	for remaining > 0 {
    53  		raw, err := client.WithEcsClient(func(ecsClient *ecs.Client) (interface{}, error) {
    54  			request := ecs.CreateDescribeKeyPairsRequest()
    55  			request.RegionId = client.RegionID
    56  			request.PageSize = requests.NewInteger(pageSize)
    57  			request.PageNumber = requests.NewInteger(pageNumber)
    58  			return ecsClient.DescribeKeyPairs(request)
    59  		})
    60  		if err != nil {
    61  			return err
    62  		}
    63  
    64  		response := raw.(*ecs.DescribeKeyPairsResponse)
    65  		allKeyPairs = append(allKeyPairs, response.KeyPairs.KeyPair...)
    66  		remaining = response.TotalCount - pageNumber*pageSize
    67  		pageNumber++
    68  	}
    69  
    70  	for _, keypair := range allKeyPairs {
    71  		resource := resourceFromKeyPair(keypair)
    72  		g.Resources = append(g.Resources, resource)
    73  	}
    74  
    75  	return nil
    76  }