Beispiel #1
0
// Config returns a valid aws.Config object for access to AWS services, or
// an error if the authentication and region couldn't be resolved
func (c *AccessConfig) Config() (*aws.Config, error) {
	var creds *credentials.Credentials

	region, err := c.Region()
	if err != nil {
		return nil, err
	}
	config := aws.NewConfig().WithRegion(region).WithMaxRetries(11)
	if c.ProfileName != "" {
		profile, err := NewFromProfile(c.ProfileName)
		if err != nil {
			return nil, err
		}
		creds, err = profile.CredentialsFromProfile(config)
		if err != nil {
			return nil, err
		}
	} else {
		sess := session.New(config)
		creds = credentials.NewChainCredentials([]credentials.Provider{
			&credentials.StaticProvider{Value: credentials.Value{
				AccessKeyID:     c.AccessKey,
				SecretAccessKey: c.SecretKey,
				SessionToken:    c.Token,
			}},
			&credentials.EnvProvider{},
			&credentials.SharedCredentialsProvider{Filename: "", Profile: ""},
			&ec2rolecreds.EC2RoleProvider{
				Client: ec2metadata.New(sess),
			},
		})
	}
	return config.WithCredentials(creds), nil
}
Beispiel #2
0
func (c *CloudWatch) Connect() error {
	Config := &aws.Config{
		Region: aws.String(c.Region),
		Credentials: credentials.NewChainCredentials(
			[]credentials.Provider{
				&ec2rolecreds.EC2RoleProvider{Client: ec2metadata.New(session.New())},
				&credentials.EnvProvider{},
				&credentials.SharedCredentialsProvider{},
			}),
	}

	svc := cloudwatch.New(session.New(Config))

	params := &cloudwatch.ListMetricsInput{
		Namespace: aws.String(c.Namespace),
	}

	_, err := svc.ListMetrics(params) // Try a read-only call to test connection.

	if err != nil {
		log.Printf("cloudwatch: Error in ListMetrics API call : %+v \n", err.Error())
	}

	c.svc = svc

	return err
}
Beispiel #3
0
func handleListMetrics(req *cwRequest, c *middleware.Context) {
	creds := credentials.NewChainCredentials(
		[]credentials.Provider{
			&credentials.EnvProvider{},
			&credentials.SharedCredentialsProvider{Filename: "", Profile: req.DataSource.Database},
			&ec2rolecreds.EC2RoleProvider{ExpiryWindow: 5 * time.Minute},
		})
	svc := cloudwatch.New(&aws.Config{
		Region:      aws.String(req.Region),
		Credentials: creds,
	})

	reqParam := &struct {
		Parameters struct {
			Namespace  string                        `json:"namespace"`
			MetricName string                        `json:"metricName"`
			Dimensions []*cloudwatch.DimensionFilter `json:"dimensions"`
		} `json:"parameters"`
	}{}
	json.Unmarshal(req.Body, reqParam)

	params := &cloudwatch.ListMetricsInput{
		Namespace:  aws.String(reqParam.Parameters.Namespace),
		MetricName: aws.String(reqParam.Parameters.MetricName),
		Dimensions: reqParam.Parameters.Dimensions,
	}

	resp, err := svc.ListMetrics(params)
	if err != nil {
		c.JsonApiErr(500, "Unable to call AWS API", err)
		return
	}

	c.JSON(200, resp)
}
Beispiel #4
0
// ToServiceConfig creates an aws Config object from the CliConfig object.
func (cfg *CliConfig) ToServiceConfig() (*aws.Config, error) {
	region := cfg.getRegion()
	if region == "" {
		return nil, fmt.Errorf("Set a region with the --%s flag or %s environment variable", cli.RegionFlag, cli.AwsRegionEnvVar)
	}

	awsDefaults := defaults.Get()
	credentialProviders := cfg.getCredentialProviders(cfg.getEC2MetadataClient(&awsDefaults))
	chainCredentials := credentials.NewChainCredentials(credentialProviders)
	creds, err := chainCredentials.Get()
	if err != nil {
		return nil, err
	}

	// This is just a fail-fast check to ensure that valid credentials are available before returning to the caller.
	if creds.AccessKeyID == "" {
		return nil, fmt.Errorf("Error getting valid credentials")
	}

	svcConfig := awsDefaults.Config
	svcConfig.Region = aws.String(region)
	svcConfig.Credentials = chainCredentials

	return svcConfig, nil
}
Beispiel #5
0
func (g *S3Getter) getAWSConfig(region string, creds *credentials.Credentials) *aws.Config {
	conf := &aws.Config{}
	if creds == nil {
		// Grab the metadata URL
		metadataURL := os.Getenv("AWS_METADATA_URL")
		if metadataURL == "" {
			metadataURL = "http://169.254.169.254:80/latest"
		}

		creds = credentials.NewChainCredentials(
			[]credentials.Provider{
				&credentials.EnvProvider{},
				&credentials.SharedCredentialsProvider{Filename: "", Profile: ""},
				&ec2rolecreds.EC2RoleProvider{
					Client: ec2metadata.New(session.New(&aws.Config{
						Endpoint: aws.String(metadataURL),
					})),
				},
			})
	}

	conf.Credentials = creds
	if region != "" {
		conf.Region = aws.String(region)
	}

	return conf
}
Beispiel #6
0
// newS3Backend constructs a S3 backend using a pre-existing
// bucket. Credentials can be provided to the backend, sourced
// from the environment, AWS credential files or by IAM role.
func newS3Backend(conf map[string]string) (Backend, error) {

	bucket, ok := conf["bucket"]
	if !ok {
		return nil, fmt.Errorf("'bucket' must be set")
	}

	access_key, ok := conf["access_key"]
	if !ok {
		access_key = ""
	}
	secret_key, ok := conf["secret_key"]
	if !ok {
		secret_key = ""
	}
	session_token, ok := conf["session_token"]
	if !ok {
		session_token = ""
	}
	endpoint, ok := conf["endpoint"]
	if !ok {
		endpoint = os.Getenv("AWS_S3_ENDPOINT")
	}
	region, ok := conf["region"]
	if !ok {
		region = os.Getenv("AWS_DEFAULT_REGION")
		if region == "" {
			region = "us-east-1"
		}
	}

	creds := credentials.NewChainCredentials([]credentials.Provider{
		&credentials.StaticProvider{Value: credentials.Value{
			AccessKeyID:     access_key,
			SecretAccessKey: secret_key,
			SessionToken:    session_token,
		}},
		&credentials.EnvProvider{},
		&credentials.SharedCredentialsProvider{Filename: "", Profile: ""},
		&ec2rolecreds.EC2RoleProvider{},
	})

	s3conn := s3.New(session.New(&aws.Config{
		Credentials: creds,
		Endpoint:    aws.String(endpoint),
		Region:      aws.String(region),
	}))

	_, err := s3conn.HeadBucket(&s3.HeadBucketInput{Bucket: &bucket})
	if err != nil {
		return nil, fmt.Errorf("unable to access bucket '%s': %v", bucket, err)
	}

	s := &S3Backend{
		client: s3conn,
		bucket: bucket,
	}
	return s, nil
}
Beispiel #7
0
func getCred(providers []credentials.Provider) *credentials.Credentials {
	cred := credentials.NewChainCredentials(providers)
	_, credErr := cred.Get()
	if credErr != nil {
		panic(credErr)
	}
	return cred
}
Beispiel #8
0
// discoverEc2Hosts searches an AWS region, returning a list of instance ips
// where EC2TagKey = EC2TagValue
func (c *Config) discoverEc2Hosts(logger *log.Logger) ([]string, error) {
	config := c.RetryJoinEC2

	ec2meta := ec2metadata.New(session.New())
	if config.Region == "" {
		logger.Printf("[INFO] agent: No EC2 region provided, querying instance metadata endpoint...")
		identity, err := ec2meta.GetInstanceIdentityDocument()
		if err != nil {
			return nil, err
		}
		config.Region = identity.Region
	}

	awsConfig := &aws.Config{
		Region: &config.Region,
		Credentials: credentials.NewChainCredentials(
			[]credentials.Provider{
				&credentials.StaticProvider{
					Value: credentials.Value{
						AccessKeyID:     config.AccessKeyID,
						SecretAccessKey: config.SecretAccessKey,
					},
				},
				&credentials.EnvProvider{},
				&credentials.SharedCredentialsProvider{},
				defaults.RemoteCredProvider(*(defaults.Config()), defaults.Handlers()),
			}),
	}

	svc := ec2.New(session.New(), awsConfig)

	resp, err := svc.DescribeInstances(&ec2.DescribeInstancesInput{
		Filters: []*ec2.Filter{
			{
				Name: aws.String("tag:" + config.TagKey),
				Values: []*string{
					aws.String(config.TagValue),
				},
			},
		},
	})

	if err != nil {
		return nil, err
	}

	var servers []string
	for i := range resp.Reservations {
		for _, instance := range resp.Reservations[i].Instances {
			// Terminated instances don't have the PrivateIpAddress field
			if instance.PrivateIpAddress != nil {
				servers = append(servers, *instance.PrivateIpAddress)
			}
		}
	}

	return servers, nil
}
Beispiel #9
0
func getAWSConfig(c *cli.Context) *aws.Config {
	creds := credentials.NewChainCredentials(
		[]credentials.Provider{
			&credentials.EnvProvider{},
			&ec2rolecreds.EC2RoleProvider{Client: ec2metadata.New(session.New(&aws.Config{})), ExpiryWindow: 5 * time.Minute},
		})
	region := c.GlobalString("region")
	return &aws.Config{Credentials: creds, Region: aws.String(region)}
}
Beispiel #10
0
func (p *VaultProvider) getMasterCreds() (credentials.Value, error) {
	source := p.profiles.sourceProfile(p.profile)

	provider := credentials.NewChainCredentials([]credentials.Provider{
		&credentials.EnvProvider{},
		&credentials.SharedCredentialsProvider{Filename: "", Profile: p.profile},
		&KeyringProvider{Keyring: p.keyring, Profile: source},
	})

	return provider.Get()
}
Beispiel #11
0
Datei: s3.go Projekt: TV4/s3
func awsConfig(id, secret, region string) *aws.Config {
	return &aws.Config{
		Credentials: credentials.NewChainCredentials([]credentials.Provider{
			&credentials.StaticProvider{
				Value: credentials.Value{AccessKeyID: id, SecretAccessKey: secret},
			},
		}),
		Logger: aws.NewDefaultLogger(),
		Region: &region,
	}
}
Beispiel #12
0
func (a *awsCredentials) credentialChain() *credentials.Credentials {
	return credentials.NewChainCredentials([]credentials.Provider{
		&credentials.StaticProvider{Value: credentials.Value{
			AccessKeyID:     a.AWSAccessKeyID,
			SecretAccessKey: a.AWSAccessKeyID,
			SessionToken:    a.AWSSessionToken}},
		&credentials.EnvProvider{},
		&credentials.SharedCredentialsProvider{},
		&ec2rolecreds.EC2RoleProvider{Client: ec2metadata.New(session.New())},
	})
}
Beispiel #13
0
func s3Factory(conf map[string]string) (Client, error) {
	bucketName, ok := conf["bucket"]
	if !ok {
		return nil, fmt.Errorf("missing 'bucket' configuration")
	}

	keyName, ok := conf["key"]
	if !ok {
		return nil, fmt.Errorf("missing 'key' configuration")
	}

	regionName, ok := conf["region"]
	if !ok {
		regionName = os.Getenv("AWS_DEFAULT_REGION")
		if regionName == "" {
			return nil, fmt.Errorf(
				"missing 'region' configuration or AWS_DEFAULT_REGION environment variable")
		}
	}

	accessKeyId := conf["access_key"]
	secretAccessKey := conf["secret_key"]

	credentialsProvider := credentials.NewChainCredentials([]credentials.Provider{
		&credentials.StaticProvider{Value: credentials.Value{
			AccessKeyID:     accessKeyId,
			SecretAccessKey: secretAccessKey,
			SessionToken:    "",
		}},
		&credentials.EnvProvider{},
		&credentials.SharedCredentialsProvider{Filename: "", Profile: ""},
		&credentials.EC2RoleProvider{},
	})

	// Make sure we got some sort of working credentials.
	_, err := credentialsProvider.Get()
	if err != nil {
		return nil, fmt.Errorf("Unable to determine AWS credentials. Set the AWS_ACCESS_KEY_ID and "+
			"AWS_SECRET_ACCESS_KEY environment variables.\n(error was: %s)", err)
	}

	awsConfig := &aws.Config{
		Credentials: credentialsProvider,
		Region:      regionName,
	}
	nativeClient := s3.New(awsConfig)

	return &S3Client{
		nativeClient: nativeClient,
		bucketName:   bucketName,
		keyName:      keyName,
	}, nil
}
Beispiel #14
0
func (c *defaultAWSCredentials) Credentials() *credentials.Credentials {
	providers := []credentials.Provider{}
	if c.AccessKey != "" && c.SecretKey != "" {
		providers = append(providers, c.providerFactory.NewStaticProvider(c.AccessKey, c.SecretKey, c.SessionToken))
	}
	if c.fallbackProvider != nil {
		fallbackCreds, err := c.fallbackProvider.Credentials().Get()
		if err == nil {
			providers = append(providers, &credentials.StaticProvider{Value: fallbackCreds})
		}
	}
	return credentials.NewChainCredentials(providers)
}
Beispiel #15
0
// CredChain returns the default credential chain.
//
// Generally you shouldn't need to use this method directly, but
// is available if you need to reset the credentials of an
// existing service client or session's Config.
func CredChain(cfg *aws.Config, handlers request.Handlers) *credentials.Credentials {
	endpoint, signingRegion := endpoints.EndpointForRegion(ec2metadata.ServiceName, *cfg.Region, true)

	return credentials.NewChainCredentials(
		[]credentials.Provider{
			&credentials.EnvProvider{},
			&credentials.SharedCredentialsProvider{Filename: "", Profile: ""},
			&ec2rolecreds.EC2RoleProvider{
				Client:       ec2metadata.NewClient(*cfg, handlers, endpoint, signingRegion),
				ExpiryWindow: 5 * time.Minute,
			},
		})
}
Beispiel #16
0
// CreateImageRepo create a repository for the image on amazon's ECR(EC2 Container Repository)
// if it doesn't exist as repository needs to be present before pushing and image into it.
func CreateImageRepo(reponame string, params map[string]string) error {
	var (
		accessKey  string
		secretKey  string
		regionName string
		ok         bool
	)

	accessKey, ok = params["accesskey"]
	if !ok {
		accessKey = ""
	}
	secretKey, ok = params["secretkey"]
	if !ok {
		secretKey = ""
	}
	regionName, ok = params["region"]
	if !ok || fmt.Sprint(regionName) == "" {
		return fmt.Errorf("No region parameter provided")
	}
	region := fmt.Sprint(regionName)
	creds := credentials.NewChainCredentials([]credentials.Provider{
		&credentials.StaticProvider{
			Value: credentials.Value{
				AccessKeyID:     accessKey,
				SecretAccessKey: secretKey,
			},
		},
		&credentials.EnvProvider{},
		&credentials.SharedCredentialsProvider{},
		&ec2rolecreds.EC2RoleProvider{Client: ec2metadata.New(session.New())},
	})
	awsConfig := aws.NewConfig()
	awsConfig.WithCredentials(creds)
	awsConfig.WithRegion(region)
	svc := ecr.New(session.New(awsConfig))

	repoInput := &ecr.CreateRepositoryInput{
		RepositoryName: aws.String(reponame),
	}

	_, err := svc.CreateRepository(repoInput)
	if err != nil {
		if s3Err, ok := err.(awserr.Error); ok && s3Err.Code() == "RepositoryAlreadyExistsException" {
			return nil
		}
		return err
	}
	return nil
}
Beispiel #17
0
// This function is responsible for reading credentials from the
// environment in the case that they're not explicitly specified
// in the Terraform configuration.
func getCreds(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,
		},
	}

	// We only look in the EC2 metadata API if we can connect
	// to the metadata service within a reasonable amount of time
	metadataURL := os.Getenv("AWS_METADATA_URL")
	if metadataURL == "" {
		metadataURL = "http://169.254.169.254:80/latest"
	}
	c := http.Client{
		Timeout: 100 * time.Millisecond,
	}

	r, err := c.Get(metadataURL)
	// Flag to determine if we should add the EC2Meta data provider. Default false
	var useIAM bool
	if err == nil {
		// AWS will add a "Server: EC2ws" header value for the metadata request. We
		// check the headers for this value to ensure something else didn't just
		// happent to be listening on that IP:Port
		if r.Header["Server"] != nil && strings.Contains(r.Header["Server"][0], "EC2") {
			useIAM = true
		}
	}

	if useIAM {
		log.Printf("[DEBUG] EC2 Metadata service found, adding EC2 Role Credential Provider")
		providers = append(providers, &ec2rolecreds.EC2RoleProvider{
			Client: ec2metadata.New(session.New(&aws.Config{
				Endpoint: aws.String(metadataURL),
			})),
		})
	} else {
		log.Printf("[DEBUG] EC2 Metadata service not found, not adding EC2 Role Credential Provider")
	}
	return awsCredentials.NewChainCredentials(providers)
}
func TestGetCredentialProvidersWhenEC2MetadataServiceReturnsFailure(t *testing.T) {
	server := initTestServer("2016-06-19T00:00:00Z", true)
	defer server.Close()

	metadataClient := ec2metadata.New(session.New(), &aws.Config{Endpoint: aws.String(server.URL + "/latest")})

	ecsConfig := NewCliConfig(clusterName)
	ecsConfig.Region = region
	credentialProviders := ecsConfig.getCredentialProviders(metadataClient)
	chainCredentials := credentials.NewChainCredentials(credentialProviders)
	_, err := chainCredentials.Get()
	if err == nil {
		t.Error("Expected an error while retrieving credentials from EC2 metadata service")
	}
}
Beispiel #19
0
func handleDescribeInstances(req *cwRequest, c *middleware.Context) {
	sess := session.New()
	creds := credentials.NewChainCredentials(
		[]credentials.Provider{
			&credentials.EnvProvider{},
			&credentials.SharedCredentialsProvider{Filename: "", Profile: req.DataSource.Database},
			&ec2rolecreds.EC2RoleProvider{Client: ec2metadata.New(sess), ExpiryWindow: 5 * time.Minute},
		})

	cfg := &aws.Config{
		Region:      aws.String(req.Region),
		Credentials: creds,
	}

	svc := ec2.New(session.New(cfg), cfg)

	reqParam := &struct {
		Parameters struct {
			Filters     []*ec2.Filter `json:"filters"`
			InstanceIds []*string     `json:"instanceIds"`
		} `json:"parameters"`
	}{}
	json.Unmarshal(req.Body, reqParam)

	params := &ec2.DescribeInstancesInput{}
	if len(reqParam.Parameters.Filters) > 0 {
		params.Filters = reqParam.Parameters.Filters
	}
	if len(reqParam.Parameters.InstanceIds) > 0 {
		params.InstanceIds = reqParam.Parameters.InstanceIds
	}

	var resp ec2.DescribeInstancesOutput
	err := svc.DescribeInstancesPages(params,
		func(page *ec2.DescribeInstancesOutput, lastPage bool) bool {
			reservations, _ := awsutil.ValuesAtPath(page, "Reservations")
			for _, reservation := range reservations {
				resp.Reservations = append(resp.Reservations, reservation.(*ec2.Reservation))
			}
			return !lastPage
		})
	if err != nil {
		c.JsonApiErr(500, "Unable to call AWS API", err)
		return
	}

	c.JSON(200, resp)
}
Beispiel #20
0
func getCredentials(profile string) *credentials.Credentials {
	if _, ok := awsCredentials[profile]; ok {
		return awsCredentials[profile]
	}

	sess := session.New()
	creds := credentials.NewChainCredentials(
		[]credentials.Provider{
			&credentials.EnvProvider{},
			&credentials.SharedCredentialsProvider{Filename: "", Profile: profile},
			&ec2rolecreds.EC2RoleProvider{Client: ec2metadata.New(sess), ExpiryWindow: 5 * time.Minute},
		})
	awsCredentials[profile] = creds

	return creds
}
Beispiel #21
0
func config() *aws.Config {
	log := aws.LogLevel(aws.LogOff)
	cfg := app.NewConfig()
	if cfg.AwsLog {
		log = aws.LogLevel(aws.LogDebug)
	}
	return &aws.Config{
		Credentials: credentials.NewChainCredentials(
			[]credentials.Provider{
				&credentials.EnvProvider{},
				&ec2rolecreds.EC2RoleProvider{ExpiryWindow: cfg.AwsRoleExpiry * time.Minute},
			}),
		Region:   aws.String(os.Getenv("AWS_REGION")),
		LogLevel: log,
	}
}
func s3Upload(k *string, bucket *string, rd io.ReadSeeker, ct *string) error {
	var err error

	// Will eventually rewrite the program so I can write this as a struct and use s3upload() to receive it
	creds := credentials.NewChainCredentials(
		[]credentials.Provider{
			&credentials.SharedCredentialsProvider{
				Filename: conf,
				Profile:  "suchgop",
			},
		},
	)

	cl := s3.New(&aws.Config{
		Credentials: creds,
		Region:      "us-east-1",
	})

	params := &s3.PutObjectInput{
		Bucket:      bucket,
		Key:         k,
		Body:        rd,
		ContentType: ct,
	}

	resp, err := cl.PutObject(params)
	// This is basically straight from the AWS Go SDK Documentation.
	if err != nil {
		if awsErr, ok := err.(awserr.Error); ok {
			// Generic AWS error with Code, Message, and original error (if any)
			fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
			if reqErr, ok := err.(awserr.RequestFailure); ok {
				// A service error occurred
				fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
			}
		} else {
			// This case should never be hit, the SDK should always return an
			// error which satisfies the awserr.Error interface.
			fmt.Println(err.Error())
		}
	}

	fmt.Println(awsutil.StringValue(resp))

	return err

}
Beispiel #23
0
func handleListMetrics(req *cwRequest, c *middleware.Context) {
	sess := session.New()
	creds := credentials.NewChainCredentials(
		[]credentials.Provider{
			&credentials.EnvProvider{},
			&credentials.SharedCredentialsProvider{Filename: "", Profile: req.DataSource.Database},
			&ec2rolecreds.EC2RoleProvider{Client: ec2metadata.New(sess), ExpiryWindow: 5 * time.Minute},
		})

	cfg := &aws.Config{
		Region:      aws.String(req.Region),
		Credentials: creds,
	}

	svc := cloudwatch.New(session.New(cfg), cfg)

	reqParam := &struct {
		Parameters struct {
			Namespace  string                        `json:"namespace"`
			MetricName string                        `json:"metricName"`
			Dimensions []*cloudwatch.DimensionFilter `json:"dimensions"`
		} `json:"parameters"`
	}{}
	json.Unmarshal(req.Body, reqParam)

	params := &cloudwatch.ListMetricsInput{
		Namespace:  aws.String(reqParam.Parameters.Namespace),
		MetricName: aws.String(reqParam.Parameters.MetricName),
		Dimensions: reqParam.Parameters.Dimensions,
	}

	var resp cloudwatch.ListMetricsOutput
	err := svc.ListMetricsPages(params,
		func(page *cloudwatch.ListMetricsOutput, lastPage bool) bool {
			metrics, _ := awsutil.ValuesAtPath(page, "Metrics")
			for _, metric := range metrics {
				resp.Metrics = append(resp.Metrics, metric.(*cloudwatch.Metric))
			}
			return !lastPage
		})
	if err != nil {
		c.JsonApiErr(500, "Unable to call AWS API", err)
		return
	}

	c.JSON(200, resp)
}
Beispiel #24
0
func handleGetMetricStatistics(req *cwRequest, c *middleware.Context) {
	sess := session.New()
	creds := credentials.NewChainCredentials(
		[]credentials.Provider{
			&credentials.EnvProvider{},
			&credentials.SharedCredentialsProvider{Filename: "", Profile: req.DataSource.Database},
			&ec2rolecreds.EC2RoleProvider{Client: ec2metadata.New(sess), ExpiryWindow: 5 * time.Minute},
		})

	cfg := &aws.Config{
		Region:      aws.String(req.Region),
		Credentials: creds,
	}

	svc := cloudwatch.New(session.New(cfg), cfg)

	reqParam := &struct {
		Parameters struct {
			Namespace  string                  `json:"namespace"`
			MetricName string                  `json:"metricName"`
			Dimensions []*cloudwatch.Dimension `json:"dimensions"`
			Statistics []*string               `json:"statistics"`
			StartTime  int64                   `json:"startTime"`
			EndTime    int64                   `json:"endTime"`
			Period     int64                   `json:"period"`
		} `json:"parameters"`
	}{}
	json.Unmarshal(req.Body, reqParam)

	params := &cloudwatch.GetMetricStatisticsInput{
		Namespace:  aws.String(reqParam.Parameters.Namespace),
		MetricName: aws.String(reqParam.Parameters.MetricName),
		Dimensions: reqParam.Parameters.Dimensions,
		Statistics: reqParam.Parameters.Statistics,
		StartTime:  aws.Time(time.Unix(reqParam.Parameters.StartTime, 0)),
		EndTime:    aws.Time(time.Unix(reqParam.Parameters.EndTime, 0)),
		Period:     aws.Int64(reqParam.Parameters.Period),
	}

	resp, err := svc.GetMetricStatistics(params)
	if err != nil {
		c.JsonApiErr(500, "Unable to call AWS API", err)
		return
	}

	c.JSON(200, resp)
}
Beispiel #25
0
// 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(c *Config) *awsCredentials.Credentials {
	// build a chain provider, lazy-evaulated by aws-sdk
	providers := []awsCredentials.Provider{
		&awsCredentials.StaticProvider{Value: awsCredentials.Value{
			AccessKeyID:     c.AccessKey,
			SecretAccessKey: c.SecretKey,
			SessionToken:    c.Token,
		}},
		&awsCredentials.EnvProvider{},
		&awsCredentials.SharedCredentialsProvider{
			Filename: c.CredsFilename,
			Profile:  c.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)

	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
		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 main() {

	credentialsProvider := credentials.NewChainCredentials(
		[]credentials.Provider{
			&credentials.EnvProvider{},
			&credentials.SharedCredentialsProvider{Filename: "", Profile: "default"},
		})

	svc := s3.New(&aws.Config{Credentials: credentialsProvider, Region: aws.String(os.Getenv("AWS_REGION"))})
	var params *s3.ListBucketsInput
	result, err := svc.ListBuckets(params)
	if err != nil {
		log.Println(err.Error())
		return
	}
	log.Println(result)
}
func (c *CredentialsConfig) GenerateCredentialChain() (*credentials.Credentials, error) {
	var providers []credentials.Provider

	switch {
	case c.AccessKey != "" && c.SecretKey != "":
		// Add the static credential provider
		providers = append(providers, &credentials.StaticProvider{
			Value: credentials.Value{
				AccessKeyID:     c.AccessKey,
				SecretAccessKey: c.SecretKey,
				SessionToken:    c.SessionToken,
			}})
	case c.AccessKey == "" && c.AccessKey == "":
		// Attempt to get credentials from the IAM instance role below

	default: // Have one or the other but not both and not neither
		return nil, fmt.Errorf(
			"static AWS client credentials haven't been properly configured (the access key or secret key were provided but not both)")
	}

	// Add the environment credential provider
	providers = append(providers, &credentials.EnvProvider{})

	// Add the shared credentials provider
	providers = append(providers, &credentials.SharedCredentialsProvider{
		Filename: c.Filename,
		Profile:  c.Profile,
	})

	// Add the instance metadata role provider
	providers = append(providers, &ec2rolecreds.EC2RoleProvider{
		Client: ec2metadata.New(session.New(&aws.Config{
			Region:     aws.String(c.Region),
			HTTPClient: c.HTTPClient,
		})),
		ExpiryWindow: 15,
	})

	// Create the credentials required to access the API.
	creds := credentials.NewChainCredentials(providers)
	if creds == nil {
		return nil, fmt.Errorf("could not compile valid credential providers from static config, environemnt, shared, or instance metadata")
	}

	return creds, nil
}
Beispiel #28
0
// NewAsgClient returns EC2 and ASG clients with a connection to the region
// configured via the AWS SDK configuration
// It returns an error if the connection cannot be made and exits if the
// AutoScalingGroup does not exist.
func NewAsgClient(asg string, region *string) (*Client, error) {
	providers := []credentials.Provider{
		&credentials.SharedCredentialsProvider{},
		&credentials.EnvProvider{},
	}
	ec2RoleConn, ec2RoleErr := net.DialTimeout("tcp", "169.254.169.254:80", 100*time.Millisecond)
	if ec2RoleErr == nil {
		ec2RoleConn.Close()
		providers = append(providers, &ec2rolecreds.EC2RoleProvider{})
	}

	creds := credentials.NewChainCredentials(providers)
	_, credErr := creds.Get()
	if credErr != nil {
		log.Fatal("Can't find AWS credentials")
		return nil, credErr
	}

	// Use region if provided, otherwise rely on the AWS_REGION
	// environment variable.
	var c *aws.Config
	if region != nil && *region != "" {
		c = &aws.Config{
			Region: aws.String(*region),
		}
	}
	a := autoscaling.New(c)
	e := ec2.New(c)
	describeAsgReq, describeAsgErr := a.DescribeAutoScalingGroups(
		&autoscaling.DescribeAutoScalingGroupsInput{
			AutoScalingGroupNames: []*string{&asg},
		},
	)
	if describeAsgErr != nil {
		return nil, describeAsgErr
	}
	if len(describeAsgReq.AutoScalingGroups) == 0 {
		log.Fatal("Can't find Auto Scaling Group with name '" + asg + "'")
	}
	return &Client{
		a,
		e,
		asg,
	}, nil
}
Beispiel #29
0
func (g *S3Getter) getAWSConfig(region string, creds *credentials.Credentials) *aws.Config {
	conf := &aws.Config{}
	if creds == nil {
		creds = credentials.NewChainCredentials(
			[]credentials.Provider{
				&credentials.EnvProvider{},
				&credentials.SharedCredentialsProvider{Filename: "", Profile: ""},
				&ec2rolecreds.EC2RoleProvider{ExpiryWindow: 5 * time.Minute},
			})
	}

	conf.Credentials = creds
	if region != "" {
		conf.Region = aws.String(region)
	}

	return conf
}
func main() {

	credentialsProvider := credentials.NewChainCredentials(
		[]credentials.Provider{
			&credentials.EnvProvider{},
			&credentials.SharedCredentialsProvider{Filename: "", Profile: "default"},
		})

	containerStream := &logStream{
		logStreamName: "bar",
		logGroupName:  "docker-log",
		client:        cloudwatchlogs.New(&aws.Config{Credentials: credentialsProvider, Region: aws.String(os.Getenv("AWS_REGION"))}),
	}
	err := containerStream.create()
	if err != nil {
		log.Println(err)
	}
}