secret.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. /*
  2. Copyright 2015 The Kubernetes Authors.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package kubectl
  14. import (
  15. "fmt"
  16. "io/ioutil"
  17. "os"
  18. "path"
  19. "strings"
  20. "k8s.io/kubernetes/pkg/api"
  21. "k8s.io/kubernetes/pkg/runtime"
  22. "k8s.io/kubernetes/pkg/util/validation"
  23. )
  24. // SecretGeneratorV1 supports stable generation of an opaque secret
  25. type SecretGeneratorV1 struct {
  26. // Name of secret (required)
  27. Name string
  28. // Type of secret (optional)
  29. Type string
  30. // FileSources to derive the secret from (optional)
  31. FileSources []string
  32. // LiteralSources to derive the secret from (optional)
  33. LiteralSources []string
  34. }
  35. // Ensure it supports the generator pattern that uses parameter injection
  36. var _ Generator = &SecretGeneratorV1{}
  37. // Ensure it supports the generator pattern that uses parameters specified during construction
  38. var _ StructuredGenerator = &SecretGeneratorV1{}
  39. // Generate returns a secret using the specified parameters
  40. func (s SecretGeneratorV1) Generate(genericParams map[string]interface{}) (runtime.Object, error) {
  41. err := ValidateParams(s.ParamNames(), genericParams)
  42. if err != nil {
  43. return nil, err
  44. }
  45. delegate := &SecretGeneratorV1{}
  46. fromFileStrings, found := genericParams["from-file"]
  47. if found {
  48. fromFileArray, isArray := fromFileStrings.([]string)
  49. if !isArray {
  50. return nil, fmt.Errorf("expected []string, found :%v", fromFileStrings)
  51. }
  52. delegate.FileSources = fromFileArray
  53. delete(genericParams, "from-file")
  54. }
  55. fromLiteralStrings, found := genericParams["from-literal"]
  56. if found {
  57. fromLiteralArray, isArray := fromLiteralStrings.([]string)
  58. if !isArray {
  59. return nil, fmt.Errorf("expected []string, found :%v", fromFileStrings)
  60. }
  61. delegate.LiteralSources = fromLiteralArray
  62. delete(genericParams, "from-literal")
  63. }
  64. params := map[string]string{}
  65. for key, value := range genericParams {
  66. strVal, isString := value.(string)
  67. if !isString {
  68. return nil, fmt.Errorf("expected string, saw %v for '%s'", value, key)
  69. }
  70. params[key] = strVal
  71. }
  72. delegate.Name = params["name"]
  73. delegate.Type = params["type"]
  74. return delegate.StructuredGenerate()
  75. }
  76. // ParamNames returns the set of supported input parameters when using the parameter injection generator pattern
  77. func (s SecretGeneratorV1) ParamNames() []GeneratorParam {
  78. return []GeneratorParam{
  79. {"name", true},
  80. {"type", false},
  81. {"from-file", false},
  82. {"from-literal", false},
  83. {"force", false},
  84. }
  85. }
  86. // StructuredGenerate outputs a secret object using the configured fields
  87. func (s SecretGeneratorV1) StructuredGenerate() (runtime.Object, error) {
  88. if err := s.validate(); err != nil {
  89. return nil, err
  90. }
  91. secret := &api.Secret{}
  92. secret.Name = s.Name
  93. secret.Data = map[string][]byte{}
  94. if len(s.Type) > 0 {
  95. secret.Type = api.SecretType(s.Type)
  96. }
  97. if len(s.FileSources) > 0 {
  98. if err := handleFromFileSources(secret, s.FileSources); err != nil {
  99. return nil, err
  100. }
  101. }
  102. if len(s.LiteralSources) > 0 {
  103. if err := handleFromLiteralSources(secret, s.LiteralSources); err != nil {
  104. return nil, err
  105. }
  106. }
  107. return secret, nil
  108. }
  109. // validate validates required fields are set to support structured generation
  110. func (s SecretGeneratorV1) validate() error {
  111. if len(s.Name) == 0 {
  112. return fmt.Errorf("name must be specified")
  113. }
  114. return nil
  115. }
  116. // handleFromLiteralSources adds the specified literal source information into the provided secret
  117. func handleFromLiteralSources(secret *api.Secret, literalSources []string) error {
  118. for _, literalSource := range literalSources {
  119. keyName, value, err := parseLiteralSource(literalSource)
  120. if err != nil {
  121. return err
  122. }
  123. err = addKeyFromLiteralToSecret(secret, keyName, []byte(value))
  124. if err != nil {
  125. return err
  126. }
  127. }
  128. return nil
  129. }
  130. // handleFromFileSources adds the specified file source information into the provided secret
  131. func handleFromFileSources(secret *api.Secret, fileSources []string) error {
  132. for _, fileSource := range fileSources {
  133. keyName, filePath, err := parseFileSource(fileSource)
  134. if err != nil {
  135. return err
  136. }
  137. info, err := os.Stat(filePath)
  138. if err != nil {
  139. switch err := err.(type) {
  140. case *os.PathError:
  141. return fmt.Errorf("error reading %s: %v", filePath, err.Err)
  142. default:
  143. return fmt.Errorf("error reading %s: %v", filePath, err)
  144. }
  145. }
  146. if info.IsDir() {
  147. if strings.Contains(fileSource, "=") {
  148. return fmt.Errorf("cannot give a key name for a directory path.")
  149. }
  150. fileList, err := ioutil.ReadDir(filePath)
  151. if err != nil {
  152. return fmt.Errorf("error listing files in %s: %v", filePath, err)
  153. }
  154. for _, item := range fileList {
  155. itemPath := path.Join(filePath, item.Name())
  156. if item.Mode().IsRegular() {
  157. keyName = item.Name()
  158. err = addKeyFromFileToSecret(secret, keyName, itemPath)
  159. if err != nil {
  160. return err
  161. }
  162. }
  163. }
  164. } else {
  165. err = addKeyFromFileToSecret(secret, keyName, filePath)
  166. if err != nil {
  167. return err
  168. }
  169. }
  170. }
  171. return nil
  172. }
  173. func addKeyFromFileToSecret(secret *api.Secret, keyName, filePath string) error {
  174. data, err := ioutil.ReadFile(filePath)
  175. if err != nil {
  176. return err
  177. }
  178. return addKeyFromLiteralToSecret(secret, keyName, data)
  179. }
  180. func addKeyFromLiteralToSecret(secret *api.Secret, keyName string, data []byte) error {
  181. if errs := validation.IsConfigMapKey(keyName); len(errs) != 0 {
  182. return fmt.Errorf("%q is not a valid key name for a Secret: %s", keyName, strings.Join(errs, ";"))
  183. }
  184. if _, entryExists := secret.Data[keyName]; entryExists {
  185. return fmt.Errorf("cannot add key %s, another key by that name already exists: %v.", keyName, secret.Data)
  186. }
  187. secret.Data[keyName] = data
  188. return nil
  189. }