Skip to content

Commit 235bc73

Browse files
committed
removed the use of credentials.yaml file
1 parent b9a4070 commit 235bc73

File tree

9 files changed

+29
-113
lines changed

9 files changed

+29
-113
lines changed

README.md

Lines changed: 6 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
# aws_cloudwatch_exporter
22

3-
[![Master branch workflow](https://github.com/slashdevops/aws_cloudwatch_exporter/workflows/Master%20branch%20workflow/badge.svg?branch=master)][github]
3+
![Master branch workflow](https://github.com/slashdevops/aws_cloudwatch_exporter/workflows/Master%20branch%20workflow/badge.svg?branch=master)
44
[![Go Report Card](https://goreportcard.com/badge/github.com/slashdevops/aws_cloudwatch_exporter)](https://goreportcard.com/report/github.com/slashdevops/aws_cloudwatch_exporter)
5-
[![Docker Pulls](https://img.shields.io/docker/pulls/slashdevops/aws_cloudwatch_exporter.svg?maxAge=604800)][hub]
5+
![Docker Pulls](https://img.shields.io/docker/pulls/slashdevops/aws_cloudwatch_exporter.svg?maxAge=604800)
66

77
Prometheus exporter for AWS CloudWatch
88

@@ -13,9 +13,9 @@ This exporter used the AWS CloudWatch GetMetricsData API call, please it is impo
1313

1414
The configuration could be set using 3 ways:
1515

16-
1. Configuration Files (i.e.: ./server.yaml, ./credentials.yaml, ./metrics.yaml)
16+
1. Configuration Files (i.e.: ./server.yaml, ./metrics.yaml)
1717
2. Environment Variables (i.e.: SERVER_PORT, AWS_REGION, AWS_PROFILE, etc)
18-
3. Program Flags (i.e.: --serverPort, --region, --profile)
18+
3. Program Flags (i.e.: --serverPort, --region)
1919

2020
The precedence is in the same order of the list, so, if you define values into `server.yaml` and then
2121
the same configuration key is defined as a `Env Var` this last will replace the file value.
@@ -40,24 +40,16 @@ docker run --rm \
4040
#### Binary
4141

4242
```bash
43-
make
44-
4543
AWS_SDK_LOAD_CONFIG="true" \
4644
AWS_PROFILE="slashdevops" \
47-
./aws_cloudwatch_exporter metrics get --metricsFiles ~/tmp/queries/m1.yaml \
48-
--debug
49-
```
50-
51-
```bash
52-
./aws_cloudwatch_exporter metrics get --metricsFiles ~/tmp/queries/m1.yaml \
53-
--profile slashdevops \
45+
./aws_cloudwatch_exporter metrics get \
46+
--metricsFiles ~/tmp/queries/m1.yaml \
5447
--debug
5548
```
5649

5750
### Configuration Files
5851

5952
* [server.yaml](docs/server.md)
60-
* [credentials.yaml](docs/credentials.md)
6153
* [metrics.yaml](docs/metrics.md)
6254

6355

cmd/metrics.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,7 @@ func getCmd(cmd *cobra.Command, args []string) {
119119

120120
log.Debugf("Metrics queries: %s", mdi.String())
121121

122-
sess := awshelper.NewSession(&conf.AWS)
122+
sess := awshelper.NewSession()
123123
svc := cloudwatch.New(sess)
124124
mdo, err := svc.GetMetricData(mdi)
125125
if err != nil {
@@ -179,7 +179,7 @@ func collectCmd(cmd *cobra.Command, args []string) {
179179
log.Debugf("Available Env Vars: %s", os.Environ())
180180

181181
m := metrics.New(&conf)
182-
sess := awshelper.NewSession(&conf.AWS)
182+
sess := awshelper.NewSession()
183183
cwc := cloudwatch.New(sess)
184184

185185
c := collector.New(&conf, m, cwc)

cmd/root.go

Lines changed: 0 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -80,34 +80,10 @@ func init() {
8080
log.Error(err)
8181
}
8282

83-
rootCmd.PersistentFlags().StringVar(&conf.Application.CredentialsFile, "credentialsFile", "credentials.yaml", "The file with the AWS Credentials configuration")
84-
if err := viper.BindPFlag("application.credentialsFile", rootCmd.PersistentFlags().Lookup("credentialsFile")); err != nil {
85-
log.Error(err)
86-
}
87-
8883
rootCmd.PersistentFlags().StringSliceVar(&conf.Application.MetricsFiles, "metricsFiles", []string{"metrics.yaml"}, "Metrics queries files, the file or files with the metrics queries. example: --metricsFiles ~/tmp/queries/m1.yaml --metricsFiles ~/tmp/queries/m2.yml")
8984
if err := viper.BindPFlag("application.metricsFiles", rootCmd.PersistentFlags().Lookup("metricsFiles")); err != nil {
9085
log.Error(err)
9186
}
92-
93-
// AWS Credentials conf
94-
// Region
95-
rootCmd.PersistentFlags().StringVar(&conf.AWS.Region, "region", "", "The AWS Region, see: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-envvars.html")
96-
if err := viper.BindPFlag("aws.region", rootCmd.PersistentFlags().Lookup("region")); err != nil {
97-
log.Error(err)
98-
}
99-
100-
// Profile
101-
rootCmd.PersistentFlags().StringVar(&conf.AWS.Profile, "profile", "", "The AWS profile name defined in .aws/config or .aws/credential")
102-
if err := viper.BindPFlag("aws.profile", rootCmd.PersistentFlags().Lookup("profile")); err != nil {
103-
log.Error(err)
104-
}
105-
106-
// RoleArn
107-
rootCmd.PersistentFlags().StringVar(&conf.AWS.RoleArn, "role_arn", "", "The AWS RoleArn, see: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-envvars.html")
108-
if err := viper.BindPFlag("aws.role_arn", rootCmd.PersistentFlags().Lookup("role_arn")); err != nil {
109-
log.Error(err)
110-
}
11187
}
11288

11389
func initConfig() {

cmd/server.go

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -115,15 +115,14 @@ func init() {
115115
func startCmd(cmd *cobra.Command, args []string) {
116116

117117
loadFromConfigFiles(conf.Application.ServerFile, &conf)
118-
loadFromConfigFiles(conf.Application.CredentialsFile, &conf)
119118
loadFromMetricsFiles(&conf)
120119
validateMetricsQueries(&conf)
121120

122121
log.Debugf("Available configuration: %s", conf.ToJSON())
123122
log.Debugf("Available Env Vars: %s", os.Environ())
124123

125124
m := metrics.New(&conf)
126-
sess := awshelper.NewSession(&conf.AWS)
125+
sess := awshelper.NewSession()
127126
cwc := cloudwatch.New(sess)
128127

129128
c := collector.New(&conf, m, cwc)

config/config.go

Lines changed: 0 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,6 @@ import (
2525
type All struct {
2626
ServerConf `mapstructure:",squash"`
2727
ApplicationConf `mapstructure:",squash"`
28-
AWSConf `mapstructure:",squash"`
2928
MetricDataQueriesConf `mapstructure:",squash"`
3029
}
3130

@@ -89,32 +88,13 @@ type Application struct {
8988
VersionInfo string `json:"versionInfo" yaml:"versionInfo"`
9089
BuildInfo string `json:"buildInfo" yaml:"buildInfo"`
9190
ServerFile string `mapstructure:"serverFile" json:"serverFile" yaml:"serverFile"`
92-
CredentialsFile string `mapstructure:"credentialsFile" json:"sharedCredentialsFile" yaml:"sharedCredentialsFile"`
9391
HealthPath string `json:"healthPath" yaml:"healthPath"`
9492
MetricsPath string `json:"metricsPath" yaml:"metricsPath"`
9593
MetricsFiles []string `mapstructure:"metricsFiles" json:"metricsFiles" yaml:"metricsFiles"`
9694
MetricStatPeriod string `mapstructure:"metricStatPeriod" json:"metricStatPeriod" yaml:"metricStatPeriod"`
9795
MetricTimeWindow string `mapstructure:"metricTimeWindow" json:"metricTimeWindow" yaml:"metricTimeWindow"`
9896
}
9997

100-
// https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-envvars.html
101-
// This is a convenient structure to allow config files nested (aws.[keys])
102-
// credentials.yaml file
103-
// Nested:
104-
// aws:
105-
// access_key_id: ""
106-
// secret_access_key: ""
107-
// profile: ""
108-
type AWSConf struct {
109-
AWS `mapstructure:"AWS" json:"AWS" yaml:"AWS"`
110-
}
111-
112-
type AWS struct {
113-
Region string `mapstructure:"region" json:"region" yaml:"region"`
114-
Profile string `mapstructure:"profile" json:"profile" yaml:"profile"`
115-
RoleArn string `mapstructure:"role_arn" json:"roleArn" yaml:"roleArn"`
116-
}
117-
11898
// This is a convenient structure to allow config files nested (MetricDataQueries.[keys])
11999
// File conf metrics.yaml
120100
// Will be filled with que Metrics Queries

docs/credentials.md

Lines changed: 0 additions & 14 deletions
This file was deleted.

docs/server.md

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@ server: # This is related to the http service conf
1818
application: # This is related to the application behavior
1919
metricStatPeriod: 5m # Type: time.Duration, Defined the global period of time .see: https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_MetricStat.html
2020
metricTimeWindow: 10m # Type: time.Duration, Defined the time windows between the StartTime and EndTime. see: https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_GetMetricData.html
21-
credentialsFile: credentials.yaml # Type: string, Define the location/path with the file that could contain the different AWS credentials information
2221
metricsFiles: # Type: Array, List of files with the definitions of metrics queries
2322
- metrics.yaml # Type: string, Part of the array list with the location/path of file with the metrics queries in the format defined in metrics.md file
2423
```
@@ -36,12 +35,6 @@ for **metricStatPeriod and metricTimeWindow**
3635
* https://docs.aws.amazon.com/cli/latest/reference/cloudwatch/get-metric-data.html
3736
* https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_GetMetricData.html
3837
39-
for **credentialsFile**
40-
41-
* [credentials.md](credentials.md)
42-
* https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html
43-
* https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-envvars.html
44-
4538
for **metricsFiles**
4639
4740
* [metrics.md](metrics.md)

internal/awshelper/session.go

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -20,34 +20,36 @@ import (
2020

2121
"github.com/aws/aws-sdk-go/aws/session"
2222
log "github.com/sirupsen/logrus"
23-
"github.com/slashdevops/aws_cloudwatch_exporter/config"
2423

2524
"github.com/aws/aws-sdk-go/aws"
2625
"github.com/aws/aws-sdk-go/aws/credentials/stscreds"
2726
)
2827

2928
// https://docs.Credentials.amazon.com/sdk-for-go/v1/developer-guide/configuring-sdk.html
3029
// https://docs.Credentials.amazon.com/sdk-for-go/api/aws/session/
31-
func NewSession(c *config.AWS) *session.Session {
30+
func NewSession() *session.Session {
3231

3332
awsConf := aws.Config{CredentialsChainVerboseErrors: aws.Bool(true)}
3433
awsSessOpts := session.Options{Config: awsConf}
3534

3635
// in case of assume role with MFA
3736
awsSessOpts.AssumeRoleTokenProvider = stscreds.StdinTokenProvider
3837

39-
if len(os.Getenv("AWS_ACCESS_KEY_ID")) == 0 {
38+
if len(os.Getenv("AWS_ACCESS_KEY_ID")) == 0 ||
39+
len(os.Getenv("AWS_SDK_LOAD_CONFIG")) > 1 ||
40+
len(os.Getenv("AWS_SHARED_CREDENTIALS_FILE")) > 1 ||
41+
len(os.Getenv("AWS_CONFIG_FILE")) > 1 {
4042
awsSessOpts.SharedConfigState = session.SharedConfigEnable
4143
}
4244

43-
if len(c.Region) > 0 {
44-
log.Debugf("Using AWS Region: %s", c.Region)
45-
awsConf.Region = aws.String(c.Region)
45+
if len(os.Getenv("AWS_REGION")) > 0 {
46+
log.Debugf("Using AWS Region: %s", os.Getenv("AWS_REGION"))
47+
awsConf.Region = aws.String(os.Getenv("AWS_REGION"))
4648
}
4749

48-
if c.Profile != "" {
49-
awsSessOpts.Profile = c.Profile
50-
log.Debug("Enabling Session SharedConfigState")
50+
if len(os.Getenv("AWS_PROFILE")) > 0 {
51+
log.Debugf("Using AWS Profile: %s", os.Getenv("AWS_PROFILE"))
52+
awsSessOpts.Profile = os.Getenv("AWS_PROFILE")
5153
}
5254

5355
// Try default credential provider chain
@@ -57,10 +59,10 @@ func NewSession(c *config.AWS) *session.Session {
5759
log.Fatalf("Failed to create AWS Session using default chain:%s", err)
5860
}
5961

60-
if len(c.RoleArn) > 0 {
61-
log.Debugf("Create new session assuming role: %s", c.RoleArn)
62+
if len(os.Getenv("AWS_ROLE_ARN")) > 0 {
63+
log.Debugf("Create new session assuming role: %s", os.Getenv("AWS_ROLE_ARN"))
6264
// Override session AWS with the new credentials provided after assume the role
63-
awsConf.Credentials = stscreds.NewCredentials(awsSession, c.RoleArn)
65+
awsConf.Credentials = stscreds.NewCredentials(awsSession, os.Getenv("AWS_ROLE_ARN"))
6466
awsSession = session.Must(session.NewSession(&awsConf))
6567
}
6668

internal/awshelper/session_test.go

Lines changed: 6 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -22,22 +22,19 @@ import (
2222
"testing"
2323

2424
log "github.com/sirupsen/logrus"
25-
"github.com/slashdevops/aws_cloudwatch_exporter/config"
2625
)
2726

2827
func TestNewSessionWithEnvVars(t *testing.T) {
2928

3029
testCases := []struct {
3130
Name string
3231
Description string
33-
Args *config.AWS
3432
EnvVars map[string]string
3533
Expected map[string]string
3634
}{
3735
{
3836
Name: "UsingEnvVarsBasicAndToken",
3937
Description: "Using AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY and AWS_SESSION_TOKEN Env Vars",
40-
Args: &config.AWS{},
4138
EnvVars: map[string]string{
4239
"AWS_SHARED_CREDENTIALS_FILE": "/tmp/nothing", // This is very important to avoid the use of your own credentials file ~.aws/credentials
4340
"AWS_CONFIG_FILE": "/tmp/nothing", // This is very important to avoid the use of your own config file ~.aws/config
@@ -67,7 +64,7 @@ func TestNewSessionWithEnvVars(t *testing.T) {
6764
}
6865

6966
// Create the session with the arguments
70-
s := NewSession(tc.Args)
67+
s := NewSession()
7168

7269
// Get the result credentials and error
7370
c, err := s.Config.Credentials.Get()
@@ -99,33 +96,26 @@ func TestNewSessionWithFiles(t *testing.T) {
9996
testCases := []struct {
10097
Name string
10198
Description string
102-
Args *config.AWS
10399
EnvVars map[string]string
104100
Expected map[string]string
105101
}{
106102
{
107103
Name: "UsingProfileAndConfigStateFile",
108104
Description: "Using ",
109-
Args: &config.AWS{
110-
Profile: "default",
111-
Region: "eu-west-1",
112-
},
113105
EnvVars: map[string]string{
106+
"AWS_SDK_LOAD_CONFIG": "true",
114107
"AWS_SHARED_CREDENTIALS_FILE": "testdata/default/credentials", // This is very important to avoid the use of your own credentials file ~.aws/credentials
115108
},
116109
Expected: map[string]string{
117110
"AWS_ACCESS_KEY_ID": "AKIAIOSFODNN7EXAMPLE",
118111
"AWS_SECRET_ACCESS_KEY": "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
119112
"AWS_REGION": "eu-west-1",
120-
"AWS_SHARED_CREDENTIALS_FILE": "SharedConfigCredentials: testdata/default/credentials",
113+
"AWS_SHARED_CREDENTIALS_FILE": "EnvConfigCredentials",
121114
},
122115
},
123116
{
124117
Name: "UsingProfileAndConfigFile",
125118
Description: "Using ",
126-
Args: &config.AWS{
127-
Profile: "case1",
128-
},
129119
EnvVars: map[string]string{
130120
"AWS_SHARED_CREDENTIALS_FILE": "testdata/case1/credentials", // This is very important to avoid the use of your own credentials file ~.aws/credentials
131121
"AWS_CONFIG_FILE": "testdata/case1/config", // This is very important to avoid the use of your own credentials file ~.aws/credentials
@@ -134,7 +124,7 @@ func TestNewSessionWithFiles(t *testing.T) {
134124
"AWS_ACCESS_KEY_ID": "AKIAIOSFODNN7EXAMPLE",
135125
"AWS_SECRET_ACCESS_KEY": "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
136126
"AWS_REGION": "eu-west-1",
137-
"AWS_SHARED_CREDENTIALS_FILE": "SharedConfigCredentials: testdata/case1/credentials",
127+
"AWS_SHARED_CREDENTIALS_FILE": "EnvConfigCredentials",
138128
},
139129
},
140130
}
@@ -151,7 +141,7 @@ func TestNewSessionWithFiles(t *testing.T) {
151141
}
152142

153143
// Create the session with the arguments
154-
s := NewSession(tc.Args)
144+
s := NewSession()
155145

156146
// Get the result credentials and error
157147
c, err := s.Config.Credentials.Get()
@@ -184,14 +174,12 @@ func TestNewSessionWithConfigAndEnvVars(t *testing.T) {
184174
testCases := []struct {
185175
Name string
186176
Description string
187-
Args *config.AWS
188177
EnvVars map[string]string
189178
Expected map[string]string
190179
}{
191180
{
192181
Name: "UsingConfig",
193182
Description: "Using ",
194-
Args: &config.AWS{},
195183
EnvVars: map[string]string{
196184
"AWS_ACCESS_KEY_ID": "AKIAIOSFODNN7EXAMPLE",
197185
"AWS_SECRET_ACCESS_KEY": "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
@@ -217,7 +205,7 @@ func TestNewSessionWithConfigAndEnvVars(t *testing.T) {
217205
}
218206

219207
// Create the session with the arguments
220-
s := NewSession(tc.Args)
208+
s := NewSession()
221209

222210
// Get the result credentials and error
223211
c, err := s.Config.Credentials.Get()

0 commit comments

Comments
 (0)