init.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. /*
  2. Copyright 2020 Docker, Inc.
  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 secrets
  14. import (
  15. "encoding/json"
  16. "fmt"
  17. "io/ioutil"
  18. "os"
  19. "path/filepath"
  20. )
  21. type Secret struct {
  22. Name string
  23. Keys []string
  24. }
  25. func CreateSecretFiles(secret Secret, path string) error {
  26. value, ok := os.LookupEnv(secret.Name)
  27. if !ok {
  28. return fmt.Errorf("%q variable not set", secret.Name)
  29. }
  30. secrets := filepath.Join(path, secret.Name)
  31. if len(secret.Keys) == 0 {
  32. // raw Secret
  33. fmt.Printf("inject Secret %q info %s\n", secret.Name, secrets)
  34. return ioutil.WriteFile(secrets, []byte(value), 0444)
  35. }
  36. var unmarshalled interface{}
  37. err := json.Unmarshal([]byte(value), &unmarshalled)
  38. if err != nil {
  39. return fmt.Errorf("%q Secret is not a valid JSON document: %w", secret.Name, err)
  40. }
  41. dict, ok := unmarshalled.(map[string]interface{})
  42. if !ok {
  43. return fmt.Errorf("%q Secret is not a JSON dictionary: %w", secret.Name, err)
  44. }
  45. err = os.MkdirAll(secrets, 0755)
  46. if err != nil {
  47. return err
  48. }
  49. if contains(secret.Keys, "*") {
  50. var keys []string
  51. for k := range dict {
  52. keys = append(keys, k)
  53. }
  54. secret.Keys = keys
  55. }
  56. for _, k := range secret.Keys {
  57. path := filepath.Join(secrets, k)
  58. fmt.Printf("inject Secret %q info %s\n", k, path)
  59. v, ok := dict[k]
  60. if !ok {
  61. return fmt.Errorf("%q Secret has no %q key", secret.Name, k)
  62. }
  63. var raw []byte
  64. if s, ok := v.(string); ok {
  65. raw = []byte(s)
  66. } else {
  67. raw, err = json.Marshal(v)
  68. if err != nil {
  69. return err
  70. }
  71. }
  72. err = ioutil.WriteFile(path, raw, 0444)
  73. if err != nil {
  74. return err
  75. }
  76. }
  77. return nil
  78. }
  79. func contains(keys []string, s string) bool {
  80. for _, k := range keys {
  81. if k == s {
  82. return true
  83. }
  84. }
  85. return false
  86. }