|
1 | 1 | // Package ec2metadata provides the client for making API calls to the |
2 | 2 | // EC2 Metadata service. |
| 3 | +// |
| 4 | +// This package's client can be disabled completely by setting the environment |
| 5 | +// variable "AWS_EC2_METADATA_DISABLED=true". This environment variable set to |
| 6 | +// true instructs the SDK to disable the EC2 Metadata client. The client cannot |
| 7 | +// be used while the environemnt variable is set to true, (case insensitive). |
3 | 8 | package ec2metadata |
4 | 9 |
|
5 | 10 | import ( |
6 | 11 | "bytes" |
7 | 12 | "errors" |
8 | 13 | "io" |
9 | 14 | "net/http" |
| 15 | + "os" |
| 16 | + "strings" |
10 | 17 |
|
11 | 18 | "github.com/aws/aws-sdk-go-v2/aws" |
12 | 19 | "github.com/aws/aws-sdk-go-v2/aws/awserr" |
| 20 | + "github.com/aws/aws-sdk-go-v2/aws/defaults" |
13 | 21 | ) |
14 | 22 |
|
15 | 23 | // ServiceName is the name of the service. |
16 | 24 | const ServiceName = "ec2metadata" |
| 25 | +const disableServiceEnvVar = "AWS_EC2_METADATA_DISABLED" |
17 | 26 |
|
18 | 27 | // A EC2Metadata is an EC2 Metadata service Client. |
19 | 28 | type EC2Metadata struct { |
@@ -42,6 +51,21 @@ func New(config aws.Config) *EC2Metadata { |
42 | 51 | svc.Handlers.Validate.Clear() |
43 | 52 | svc.Handlers.Validate.PushBack(validateEndpointHandler) |
44 | 53 |
|
| 54 | + // Disable the EC2 Metadata service if the environment variable is set. |
| 55 | + // This shortcirctes the service's functionality to always fail to send |
| 56 | + // requests. |
| 57 | + if strings.ToLower(os.Getenv(disableServiceEnvVar)) == "true" { |
| 58 | + svc.Handlers.Send.SwapNamed(aws.NamedHandler{ |
| 59 | + Name: defaults.SendHandler.Name, |
| 60 | + Fn: func(r *aws.Request) { |
| 61 | + r.Error = awserr.New( |
| 62 | + aws.CanceledErrorCode, |
| 63 | + "EC2 IMDS access disabled via "+disableServiceEnvVar+" env var", |
| 64 | + nil) |
| 65 | + }, |
| 66 | + }) |
| 67 | + } |
| 68 | + |
45 | 69 | return svc |
46 | 70 | } |
47 | 71 |
|
|
0 commit comments