env_provider.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. // * Secret Access Key: AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY
  27. type EnvProvider struct {
  28. retrieved bool
  29. }
  30. // NewEnvCredentials returns a pointer to a new Credentials object
  31. // wrapping the environment variable provider.
  32. func NewEnvCredentials() *Credentials {
  33. return NewCredentials(&EnvProvider{})
  34. }
  35. // Retrieve retrieves the keys from the environment.
  36. func (e *EnvProvider) Retrieve() (Value, error) {
  37. e.retrieved = false
  38. id := os.Getenv("AWS_ACCESS_KEY_ID")
  39. if id == "" {
  40. id = os.Getenv("AWS_ACCESS_KEY")
  41. }
  42. secret := os.Getenv("AWS_SECRET_ACCESS_KEY")
  43. if secret == "" {
  44. secret = os.Getenv("AWS_SECRET_KEY")
  45. }
  46. if id == "" {
  47. return Value{ProviderName: EnvProviderName}, ErrAccessKeyIDNotFound
  48. }
  49. if secret == "" {
  50. return Value{ProviderName: EnvProviderName}, ErrSecretAccessKeyNotFound
  51. }
  52. e.retrieved = true
  53. return Value{
  54. AccessKeyID: id,
  55. SecretAccessKey: secret,
  56. SessionToken: os.Getenv("AWS_SESSION_TOKEN"),
  57. ProviderName: EnvProviderName,
  58. }, nil
  59. }
  60. // IsExpired returns if the credentials have been retrieved.
  61. func (e *EnvProvider) IsExpired() bool {
  62. return !e.retrieved
  63. }