env_provider.go 2.0 KB

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