3
3
4
4
module AwsRotateKeys
5
5
class CLI
6
+ AWS_ENVIRONMENT_VARIABLES = [ 'AWS_ACCESS_KEY_ID' , 'AWS_SECRET_ACCESS_KEY' ] . freeze
7
+
6
8
def self . call ( *args )
7
9
new ( *args ) . call
8
10
end
@@ -23,11 +25,9 @@ def call
23
25
log "Creating access key..."
24
26
new_key = create_access_key
25
27
26
- create_credentials_directory_if_needed
27
-
28
- if credentials_file_exists?
28
+ if File . exist? ( credentials_path )
29
29
log "Backing up #{ credentials_path } to #{ credentials_backup_path } ..."
30
- backup_aws_credentials_file
30
+ FileUtils . cp ( credentials_path , credentials_backup_path )
31
31
end
32
32
33
33
log "Writing new access key to #{ credentials_path } "
@@ -36,11 +36,9 @@ def call
36
36
log "Deleting your oldest access key..."
37
37
delete_oldest_access_key
38
38
39
- log "You're all set!"
39
+ log aws_environment_variables_warning_message if aws_environment_variables?
40
40
41
- if aws_environment_variables?
42
- log aws_environment_variables_warning_message
43
- end
41
+ log "You're all set!"
44
42
end
45
43
46
44
private
@@ -50,24 +48,14 @@ def create_access_key
50
48
create_access_key_response . access_key
51
49
end
52
50
53
- def create_credentials_directory_if_needed
54
- FileUtils . mkdir_p ( credentials_dir )
55
- end
56
-
57
- def credentials_file_exists?
58
- File . exist? ( credentials_path )
59
- end
60
-
61
51
# ex. ~/aws/credentials.bkp-2017-01-06-16-38-07--0800
62
52
def credentials_backup_path
63
53
credentials_path + ".bkp-#{ Time . now . to_s . gsub ( /[^\d ]/ , '-' ) } "
64
54
end
65
55
66
- def backup_aws_credentials_file
67
- FileUtils . cp ( credentials_path , credentials_backup_path )
68
- end
69
-
70
56
def write_aws_credentials_file ( access_key )
57
+ FileUtils . mkdir_p ( File . dirname ( credentials_path ) ) # ensure credentials directory exists
58
+
71
59
File . open ( credentials_path , "w" ) do |f |
72
60
f . puts "[default]"
73
61
f . puts "aws_access_key_id = #{ access_key . access_key_id } "
@@ -83,20 +71,16 @@ def delete_oldest_access_key
83
71
iam . delete_access_key ( access_key_id : oldest_access_key . access_key_id )
84
72
end
85
73
86
- def credentials_dir
87
- File . dirname ( credentials_path )
88
- end
89
-
90
74
def log ( msg )
91
75
stdout . puts msg
92
76
end
93
77
94
78
def aws_environment_variables?
95
- env [ 'AWS_ACCESS_KEY_ID' ] | | env [ 'AWS_SECRET_ACCESS_KEY' ]
79
+ AWS_ENVIRONMENT_VARIABLES . any? { | v | env . key? ( v ) }
96
80
end
97
81
98
82
def aws_environment_variables_warning_message
99
- "We've noticed that the environment variables AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are set.\n " +
83
+ "We've noticed that the environment variables #{ AWS_ENVIRONMENT_VARIABLES } are set.\n " +
100
84
"Please remove them so that aws cli and libraries use #{ credentials_path } instead."
101
85
end
102
86
end
0 commit comments