2015-12-12 23:58:19 +01:00
|
|
|
package aws
|
|
|
|
|
|
|
|
import (
|
2016-09-02 19:36:01 +02:00
|
|
|
"errors"
|
2015-12-12 23:58:19 +01:00
|
|
|
"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"
|
2016-08-27 02:46:41 +02:00
|
|
|
"github.com/aws/aws-sdk-go/aws/credentials/stscreds"
|
2015-12-12 23:58:19 +01:00
|
|
|
"github.com/aws/aws-sdk-go/aws/ec2metadata"
|
|
|
|
"github.com/aws/aws-sdk-go/aws/session"
|
|
|
|
"github.com/aws/aws-sdk-go/service/iam"
|
2016-04-28 03:49:42 +02:00
|
|
|
"github.com/aws/aws-sdk-go/service/sts"
|
2016-08-09 00:19:06 +02:00
|
|
|
"github.com/hashicorp/errwrap"
|
2015-12-12 23:58:19 +01:00
|
|
|
"github.com/hashicorp/go-cleanhttp"
|
|
|
|
)
|
|
|
|
|
2016-10-07 05:36:44 +02:00
|
|
|
func GetAccountInfo(iamconn *iam.IAM, stsconn *sts.STS, authProviderName string) (string, string, error) {
|
2015-12-12 23:58:19 +01:00
|
|
|
// 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)
|
2016-08-09 00:19:06 +02:00
|
|
|
sess, err := session.NewSession(cfg)
|
|
|
|
if err != nil {
|
2016-10-07 05:36:44 +02:00
|
|
|
return "", "", errwrap.Wrapf("Error creating AWS session: %s", err)
|
2016-08-09 00:19:06 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
metadataClient := ec2metadata.New(sess)
|
2015-12-12 23:58:19 +01:00
|
|
|
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
|
2016-10-07 05:36:44 +02:00
|
|
|
return "", "", fmt.Errorf("Failed getting EC2 IAM info: %s", err)
|
2015-12-12 23:58:19 +01:00
|
|
|
}
|
|
|
|
|
2016-10-07 05:36:44 +02:00
|
|
|
return parseAccountInfoFromArn(info.InstanceProfileArn)
|
2015-12-12 23:58:19 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// Then try IAM GetUser
|
|
|
|
log.Println("[DEBUG] Trying to get account ID via iam:GetUser")
|
|
|
|
outUser, err := iamconn.GetUser(nil)
|
|
|
|
if err == nil {
|
2016-10-07 05:36:44 +02:00
|
|
|
return parseAccountInfoFromArn(*outUser.User.Arn)
|
2015-12-12 23:58:19 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
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") {
|
2016-10-07 05:36:44 +02:00
|
|
|
return "", "", fmt.Errorf("Failed getting account ID via 'iam:GetUser': %s", err)
|
2015-12-12 23:58:19 +01:00
|
|
|
}
|
|
|
|
log.Printf("[DEBUG] Getting account ID via iam:GetUser failed: %s", err)
|
2016-04-28 03:49:42 +02:00
|
|
|
|
|
|
|
// Then try STS GetCallerIdentity
|
|
|
|
log.Println("[DEBUG] Trying to get account ID via sts:GetCallerIdentity")
|
|
|
|
outCallerIdentity, err := stsconn.GetCallerIdentity(&sts.GetCallerIdentityInput{})
|
|
|
|
if err == nil {
|
2016-10-07 05:36:44 +02:00
|
|
|
return parseAccountInfoFromArn(*outCallerIdentity.Arn)
|
2016-04-28 03:49:42 +02:00
|
|
|
}
|
|
|
|
log.Printf("[DEBUG] Getting account ID via sts:GetCallerIdentity failed: %s", err)
|
|
|
|
|
|
|
|
// Then try IAM ListRoles
|
|
|
|
log.Println("[DEBUG] Trying to get account ID via iam:ListRoles")
|
2015-12-12 23:58:19 +01:00
|
|
|
outRoles, err := iamconn.ListRoles(&iam.ListRolesInput{
|
|
|
|
MaxItems: aws.Int64(int64(1)),
|
|
|
|
})
|
|
|
|
if err != nil {
|
2016-10-07 05:36:44 +02:00
|
|
|
return "", "", fmt.Errorf("Failed getting account ID via 'iam:ListRoles': %s", err)
|
2015-12-12 23:58:19 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
if len(outRoles.Roles) < 1 {
|
2016-10-07 05:36:44 +02:00
|
|
|
return "", "", errors.New("Failed getting account ID via 'iam:ListRoles': No roles available")
|
2015-12-12 23:58:19 +01:00
|
|
|
}
|
|
|
|
|
2016-10-07 05:36:44 +02:00
|
|
|
return parseAccountInfoFromArn(*outRoles.Roles[0].Arn)
|
2015-12-12 23:58:19 +01:00
|
|
|
}
|
|
|
|
|
2016-10-07 05:36:44 +02:00
|
|
|
func parseAccountInfoFromArn(arn string) (string, string, error) {
|
2015-12-12 23:58:19 +01:00
|
|
|
parts := strings.Split(arn, ":")
|
|
|
|
if len(parts) < 5 {
|
2016-10-07 05:36:44 +02:00
|
|
|
return "", "", fmt.Errorf("Unable to parse ID from invalid ARN: %q", arn)
|
2015-12-12 23:58:19 +01:00
|
|
|
}
|
2016-10-07 05:36:44 +02:00
|
|
|
return parts[1], parts[4], nil
|
2015-12-12 23:58:19 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// This function is responsible for reading credentials from the
|
|
|
|
// environment in the case that they're not explicitly specified
|
|
|
|
// in the Terraform configuration.
|
2016-08-27 02:46:41 +02:00
|
|
|
func GetCredentials(c *Config) (*awsCredentials.Credentials, error) {
|
2015-12-12 23:58:19 +01:00
|
|
|
// build a chain provider, lazy-evaulated by aws-sdk
|
|
|
|
providers := []awsCredentials.Provider{
|
|
|
|
&awsCredentials.StaticProvider{Value: awsCredentials.Value{
|
2016-08-10 16:10:34 +02:00
|
|
|
AccessKeyID: c.AccessKey,
|
|
|
|
SecretAccessKey: c.SecretKey,
|
|
|
|
SessionToken: c.Token,
|
2015-12-12 23:58:19 +01:00
|
|
|
}},
|
|
|
|
&awsCredentials.EnvProvider{},
|
|
|
|
&awsCredentials.SharedCredentialsProvider{
|
2016-08-10 16:10:34 +02:00
|
|
|
Filename: c.CredsFilename,
|
|
|
|
Profile: c.Profile,
|
2015-12-12 23:58:19 +01:00
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
// 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)
|
|
|
|
|
2016-08-10 16:25:16 +02:00
|
|
|
if !c.SkipMetadataApiCheck {
|
|
|
|
// 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
|
2016-08-10 16:10:34 +02:00
|
|
|
metadataClient := ec2metadata.New(session.New(cfg))
|
|
|
|
if metadataClient.Available() {
|
|
|
|
providers = append(providers, &ec2rolecreds.EC2RoleProvider{
|
|
|
|
Client: metadataClient,
|
|
|
|
})
|
2016-09-02 19:36:01 +02:00
|
|
|
log.Print("[INFO] AWS EC2 instance detected via default metadata" +
|
2016-08-10 16:10:34 +02:00
|
|
|
" 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)
|
2015-12-12 23:58:19 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-09-02 19:36:01 +02:00
|
|
|
// This is the "normal" flow (i.e. not assuming a role)
|
|
|
|
if c.AssumeRoleARN == "" {
|
|
|
|
return awsCredentials.NewChainCredentials(providers), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Otherwise we need to construct and STS client with the main credentials, and verify
|
|
|
|
// that we can assume the defined role.
|
|
|
|
log.Printf("[INFO] Attempting to AssumeRole %s (SessionName: %q, ExternalId: %q)",
|
|
|
|
c.AssumeRoleARN, c.AssumeRoleSessionName, c.AssumeRoleExternalID)
|
2016-08-27 02:46:41 +02:00
|
|
|
|
2016-09-02 19:36:01 +02:00
|
|
|
creds := awsCredentials.NewChainCredentials(providers)
|
|
|
|
cp, err := creds.Get()
|
|
|
|
if err != nil {
|
|
|
|
if awsErr, ok := err.(awserr.Error); ok && awsErr.Code() == "NoCredentialProviders" {
|
|
|
|
return nil, errors.New(`No valid credential sources found for AWS Provider.
|
2016-08-27 02:46:41 +02:00
|
|
|
Please see https://terraform.io/docs/providers/aws/index.html for more information on
|
2016-09-02 19:36:01 +02:00
|
|
|
providing credentials for the AWS Provider`)
|
2016-08-27 02:46:41 +02:00
|
|
|
}
|
|
|
|
|
2016-09-02 19:36:01 +02:00
|
|
|
return nil, fmt.Errorf("Error loading credentials for AWS Provider: %s", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
log.Printf("[INFO] AWS Auth provider used: %q", cp.ProviderName)
|
2016-08-27 02:46:41 +02:00
|
|
|
|
2016-09-02 19:36:01 +02:00
|
|
|
awsConfig := &aws.Config{
|
|
|
|
Credentials: creds,
|
|
|
|
Region: aws.String(c.Region),
|
|
|
|
MaxRetries: aws.Int(c.MaxRetries),
|
|
|
|
HTTPClient: cleanhttp.DefaultClient(),
|
|
|
|
S3ForcePathStyle: aws.Bool(c.S3ForcePathStyle),
|
|
|
|
}
|
|
|
|
|
|
|
|
stsclient := sts.New(session.New(awsConfig))
|
|
|
|
assumeRoleProvider := &stscreds.AssumeRoleProvider{
|
|
|
|
Client: stsclient,
|
|
|
|
RoleARN: c.AssumeRoleARN,
|
|
|
|
}
|
|
|
|
if c.AssumeRoleSessionName != "" {
|
|
|
|
assumeRoleProvider.RoleSessionName = c.AssumeRoleSessionName
|
|
|
|
}
|
|
|
|
if c.AssumeRoleExternalID != "" {
|
|
|
|
assumeRoleProvider.ExternalID = aws.String(c.AssumeRoleExternalID)
|
|
|
|
}
|
|
|
|
|
|
|
|
providers = []awsCredentials.Provider{assumeRoleProvider}
|
|
|
|
|
|
|
|
assumeRoleCreds := awsCredentials.NewChainCredentials(providers)
|
|
|
|
_, err = assumeRoleCreds.Get()
|
|
|
|
if err != nil {
|
|
|
|
if awsErr, ok := err.(awserr.Error); ok && awsErr.Code() == "NoCredentialProviders" {
|
|
|
|
return nil, fmt.Errorf("The role %q cannot be assumed.\n\n"+
|
|
|
|
" There are a number of possible causes of this - the most common are:\n"+
|
|
|
|
" * The credentials used in order to assume the role are invalid\n"+
|
|
|
|
" * The credentials do not have appropriate permission to assume the role\n"+
|
|
|
|
" * The role ARN is not valid",
|
|
|
|
c.AssumeRoleARN)
|
2016-08-27 02:46:41 +02:00
|
|
|
}
|
|
|
|
|
2016-09-02 19:36:01 +02:00
|
|
|
return nil, fmt.Errorf("Error loading credentials for AWS Provider: %s", err)
|
2016-08-27 02:46:41 +02:00
|
|
|
}
|
|
|
|
|
2016-09-02 19:36:01 +02:00
|
|
|
return assumeRoleCreds, nil
|
2015-12-12 23:58:19 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
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 ""
|
|
|
|
}
|