blob: b676dd97787d5560039e5b189d5e10a531a430ed [file] [log] [blame]
Ash Wilson0482daf2014-10-22 11:24:40 -04001package keypairs
Ash Wilsonad612f62014-10-22 14:04:37 -04002
3import (
Ash Wilson10fede72014-10-22 14:58:52 -04004 "errors"
5
Ash Wilson4aaaa1e2014-10-22 14:38:02 -04006 "github.com/racker/perigee"
Ash Wilsonad612f62014-10-22 14:04:37 -04007 "github.com/rackspace/gophercloud"
8 "github.com/rackspace/gophercloud/pagination"
9)
10
11// List returns a Pager that allows you to iterate over a collection of KeyPairs.
12func List(client *gophercloud.ServiceClient) pagination.Pager {
13 return pagination.NewPager(client, listURL(client), func(r pagination.PageResult) pagination.Page {
14 return KeyPairPage{pagination.SinglePageBase(r)}
15 })
16}
Ash Wilson4aaaa1e2014-10-22 14:38:02 -040017
Ash Wilson10fede72014-10-22 14:58:52 -040018// CreateOptsBuilder describes struct types that can be accepted by the Create call. Notable, the
19// CreateOpts struct in this package does.
20type CreateOptsBuilder interface {
21 ToKeyPairCreateMap() (map[string]interface{}, error)
22}
23
24// CreateOpts species keypair creation or import parameters.
25type CreateOpts struct {
26 // Name [required] is a friendly name to refer to this KeyPair in other services.
27 Name string
28
29 // PublicKey [optional] is a pregenerated OpenSSH-formatted public key. If provided, this key
30 // will be imported and no new key will be created.
31 PublicKey string
32}
33
34// ToKeyPairCreateMap constructs a request body from CreateOpts.
35func (opts CreateOpts) ToKeyPairCreateMap() (map[string]interface{}, error) {
36 if opts.Name == "" {
37 return nil, errors.New("Missing field required for keypair creation: Name")
38 }
39
40 keypair := make(map[string]interface{})
41 keypair["name"] = opts.Name
42 if opts.PublicKey != "" {
43 keypair["public_key"] = opts.PublicKey
44 }
45
46 return map[string]interface{}{"keypair": keypair}, nil
47}
48
49// Create requests the creation of a new keypair on the server, or to import a pre-existing
50// keypair.
51func Create(client *gophercloud.ServiceClient, opts CreateOptsBuilder) CreateResult {
52 var res CreateResult
53
54 reqBody, err := opts.ToKeyPairCreateMap()
55 if err != nil {
56 res.Err = err
57 return res
58 }
59
60 _, res.Err = perigee.Request("POST", createURL(client), perigee.Options{
61 MoreHeaders: client.AuthenticatedHeaders(),
62 ReqBody: reqBody,
63 Results: &res.Body,
64 OkCodes: []int{200},
65 })
66 return res
67}
68
Ash Wilson4aaaa1e2014-10-22 14:38:02 -040069// Get returns public data about a previously uploaded KeyPair.
70func Get(client *gophercloud.ServiceClient, name string) GetResult {
71 var res GetResult
72 _, res.Err = perigee.Request("GET", getURL(client, name), perigee.Options{
73 MoreHeaders: client.AuthenticatedHeaders(),
74 Results: &res.Body,
75 OkCodes: []int{200},
76 })
77 return res
78}