-
Notifications
You must be signed in to change notification settings - Fork 9.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
provider/aws: Allow account ID checks on EC2 instances & w/ federated accounts #5030
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,134 @@ | ||
package aws | ||
|
||
import ( | ||
"fmt" | ||
"log" | ||
"os" | ||
"strings" | ||
"time" | ||
|
||
"github.com/aws/aws-sdk-go/aws" | ||
"github.com/aws/aws-sdk-go/aws/awserr" | ||
awsCredentials "github.com/aws/aws-sdk-go/aws/credentials" | ||
"github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds" | ||
"github.com/aws/aws-sdk-go/aws/ec2metadata" | ||
"github.com/aws/aws-sdk-go/aws/session" | ||
"github.com/aws/aws-sdk-go/service/iam" | ||
"github.com/hashicorp/go-cleanhttp" | ||
) | ||
|
||
func GetAccountId(iamconn *iam.IAM, authProviderName string) (string, error) { | ||
// If we have creds from instance profile, we can use metadata API | ||
if authProviderName == ec2rolecreds.ProviderName { | ||
log.Println("[DEBUG] Trying to get account ID via AWS Metadata API") | ||
|
||
cfg := &aws.Config{} | ||
setOptionalEndpoint(cfg) | ||
metadataClient := ec2metadata.New(session.New(cfg)) | ||
info, err := metadataClient.IAMInfo() | ||
if err != nil { | ||
// This can be triggered when no IAM Role is assigned | ||
// or AWS just happens to return invalid response | ||
return "", fmt.Errorf("Failed getting EC2 IAM info: %s", err) | ||
} | ||
|
||
return parseAccountIdFromArn(info.InstanceProfileArn) | ||
} | ||
|
||
// Then try IAM GetUser | ||
log.Println("[DEBUG] Trying to get account ID via iam:GetUser") | ||
outUser, err := iamconn.GetUser(nil) | ||
if err == nil { | ||
return parseAccountIdFromArn(*outUser.User.Arn) | ||
} | ||
|
||
// Then try IAM ListRoles | ||
awsErr, ok := err.(awserr.Error) | ||
// AccessDenied and ValidationError can be raised | ||
// if credentials belong to federated profile, so we ignore these | ||
if !ok || (awsErr.Code() != "AccessDenied" && awsErr.Code() != "ValidationError") { | ||
return "", fmt.Errorf("Failed getting account ID via 'iam:GetUser': %s", err) | ||
} | ||
|
||
log.Printf("[DEBUG] Getting account ID via iam:GetUser failed: %s", err) | ||
log.Println("[DEBUG] Trying to get account ID via iam:ListRoles instead") | ||
outRoles, err := iamconn.ListRoles(&iam.ListRolesInput{ | ||
MaxItems: aws.Int64(int64(1)), | ||
}) | ||
if err != nil { | ||
return "", fmt.Errorf("Failed getting account ID via 'iam:ListRoles': %s", err) | ||
} | ||
|
||
if len(outRoles.Roles) < 1 { | ||
return "", fmt.Errorf("Failed getting account ID via 'iam:ListRoles': No roles available") | ||
} | ||
|
||
return parseAccountIdFromArn(*outRoles.Roles[0].Arn) | ||
} | ||
|
||
func parseAccountIdFromArn(arn string) (string, error) { | ||
parts := strings.Split(arn, ":") | ||
if len(parts) < 5 { | ||
return "", fmt.Errorf("Unable to parse ID from invalid ARN: %q", arn) | ||
} | ||
return parts[4], nil | ||
} | ||
|
||
// This function is responsible for reading credentials from the | ||
// environment in the case that they're not explicitly specified | ||
// in the Terraform configuration. | ||
func GetCredentials(key, secret, token, profile, credsfile string) *awsCredentials.Credentials { | ||
// build a chain provider, lazy-evaulated by aws-sdk | ||
providers := []awsCredentials.Provider{ | ||
&awsCredentials.StaticProvider{Value: awsCredentials.Value{ | ||
AccessKeyID: key, | ||
SecretAccessKey: secret, | ||
SessionToken: token, | ||
}}, | ||
&awsCredentials.EnvProvider{}, | ||
&awsCredentials.SharedCredentialsProvider{ | ||
Filename: credsfile, | ||
Profile: profile, | ||
}, | ||
} | ||
|
||
// Build isolated HTTP client to avoid issues with globally-shared settings | ||
client := cleanhttp.DefaultClient() | ||
|
||
// Keep the timeout low as we don't want to wait in non-EC2 environments | ||
client.Timeout = 100 * time.Millisecond | ||
cfg := &aws.Config{ | ||
HTTPClient: client, | ||
} | ||
usedEndpoint := setOptionalEndpoint(cfg) | ||
|
||
// Real AWS should reply to a simple metadata request. | ||
// We check it actually does to ensure something else didn't just | ||
// happen to be listening on the same IP:Port | ||
metadataClient := ec2metadata.New(session.New(cfg)) | ||
if metadataClient.Available() { | ||
providers = append(providers, &ec2rolecreds.EC2RoleProvider{ | ||
Client: metadataClient, | ||
}) | ||
log.Printf("[INFO] AWS EC2 instance detected via default metadata" + | ||
" API endpoint, EC2RoleProvider added to the auth chain") | ||
} else { | ||
if usedEndpoint == "" { | ||
usedEndpoint = "default location" | ||
} | ||
log.Printf("[WARN] Ignoring AWS metadata API endpoint at %s "+ | ||
"as it doesn't return any instance-id", usedEndpoint) | ||
} | ||
|
||
return awsCredentials.NewChainCredentials(providers) | ||
} | ||
|
||
func setOptionalEndpoint(cfg *aws.Config) string { | ||
endpoint := os.Getenv("AWS_METADATA_URL") | ||
if endpoint != "" { | ||
log.Printf("[INFO] Setting custom metadata endpoint: %q", endpoint) | ||
cfg.Endpoint = aws.String(endpoint) | ||
return endpoint | ||
} | ||
return "" | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
can we if/elseif on the other provider names? This should remove the need to poke the AWS API if we're not using User credentials
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can you be more specific? I'm not sure I follow. What would be in those if/elseif and what API calls in which specific cases would we save?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ah nevermind, I was thinking we can exclude
AssumeRoleProvider
from theGetUser
path, but it's more cumbersome than helpful