keypair.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. // Copyright 2019 Yunion
  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. package baidu
  15. import "net/url"
  16. type SKeypair struct {
  17. Name string
  18. PublicKey string
  19. FingerPrint string
  20. RegionId string
  21. KeypairId string
  22. }
  23. func (self *SRegion) GetKeypairs() ([]SKeypair, error) {
  24. params := url.Values{}
  25. ret := []SKeypair{}
  26. for {
  27. resp, err := self.bccList("v2/keypair", params)
  28. if err != nil {
  29. return nil, err
  30. }
  31. part := struct {
  32. Keypairs []SKeypair
  33. NextMarker string
  34. }{}
  35. err = resp.Unmarshal(&part)
  36. if err != nil {
  37. return nil, err
  38. }
  39. ret = append(ret, part.Keypairs...)
  40. if len(part.NextMarker) == 0 {
  41. break
  42. }
  43. params.Set("marker", part.NextMarker)
  44. }
  45. return ret, nil
  46. }
  47. func (self *SRegion) SyncKeypair(name, publicKey string) (*SKeypair, error) {
  48. keypairs, err := self.GetKeypairs()
  49. if err != nil {
  50. return nil, err
  51. }
  52. for i := range keypairs {
  53. if keypairs[i].PublicKey == publicKey {
  54. return &keypairs[i], nil
  55. }
  56. }
  57. return self.CreateKeypair(name, publicKey)
  58. }
  59. func (self *SRegion) CreateKeypair(name, publicKey string) (*SKeypair, error) {
  60. body := map[string]interface{}{
  61. "name": name,
  62. "publicKey": publicKey,
  63. }
  64. resp, err := self.bccPost("v2/keypair", nil, body)
  65. if err != nil {
  66. return nil, err
  67. }
  68. ret := &SKeypair{}
  69. err = resp.Unmarshal(ret, "keypair")
  70. if err != nil {
  71. return nil, err
  72. }
  73. return ret, nil
  74. }