env_provider.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package credentials
  2. import (
  3. "os"
  4. "github.com/aws/aws-sdk-go/aws/awserr"
  5. )
  6. // EnvProviderName provides a name of Env provider
  7. const EnvProviderName = "EnvProvider"
  8. var (
  9. // ErrAccessKeyIDNotFound is returned when the AWS Access Key ID can't be
  10. // found in the process's environment.
  11. //
  12. // @readonly
  13. ErrAccessKeyIDNotFound = awserr.New("EnvAccessKeyNotFound", "AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY not found in environment", nil)
  14. // ErrSecretAccessKeyNotFound is returned when the AWS Secret Access Key
  15. // can't be found in the process's environment.
  16. //
  17. // @readonly
  18. ErrSecretAccessKeyNotFound = awserr.New("EnvSecretNotFound", "AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY not found in environment", nil)
  19. )
  20. // A EnvProvider retrieves credentials from the environment variables of the
  21. // running process. Environment credentials never expire.
  22. //
  23. // Environment variables used:
  24. //
  25. // * Access Key ID: AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY
  26. //
  27. // * Secret Access Key: AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY
  28. type EnvProvider struct {
  29. retrieved bool
  30. }
  31. // NewEnvCredentials returns a pointer to a new Credentials object
  32. // wrapping the environment variable provider.
  33. func NewEnvCredentials() *Credentials {
  34. return NewCredentials(&EnvProvider{})
  35. }
  36. // Retrieve retrieves the keys from the environment.
  37. func (e *EnvProvider) Retrieve() (Value, error) {
  38. e.retrieved = false
  39. id := os.Getenv("AWS_ACCESS_KEY_ID")
  40. if id == "" {
  41. id = os.Getenv("AWS_ACCESS_KEY")
  42. }
  43. secret := os.Getenv("AWS_SECRET_ACCESS_KEY")
  44. if secret == "" {
  45. secret = os.Getenv("AWS_SECRET_KEY")
  46. }
  47. if id == "" {
  48. return Value{ProviderName: EnvProviderName}, ErrAccessKeyIDNotFound
  49. }
  50. if secret == "" {
  51. return Value{ProviderName: EnvProviderName}, ErrSecretAccessKeyNotFound
  52. }
  53. e.retrieved = true
  54. return Value{
  55. AccessKeyID: id,
  56. SecretAccessKey: secret,
  57. SessionToken: os.Getenv("AWS_SESSION_TOKEN"),
  58. ProviderName: EnvProviderName,
  59. }, nil
  60. }
  61. // IsExpired returns if the credentials have been retrieved.
  62. func (e *EnvProvider) IsExpired() bool {
  63. return !e.retrieved
  64. }