33
44module AwsRotateKeys
55 class CLI
6+ AWS_ENVIRONMENT_VARIABLES = [ 'AWS_ACCESS_KEY_ID' , 'AWS_SECRET_ACCESS_KEY' ] . freeze
7+
68 def self . call ( *args )
79 new ( *args ) . call
810 end
@@ -23,11 +25,9 @@ def call
2325 log "Creating access key..."
2426 new_key = create_access_key
2527
26- create_credentials_directory_if_needed
27-
28- if credentials_file_exists?
28+ if File . exist? ( credentials_path )
2929 log "Backing up #{ credentials_path } to #{ credentials_backup_path } ..."
30- backup_aws_credentials_file
30+ FileUtils . cp ( credentials_path , credentials_backup_path )
3131 end
3232
3333 log "Writing new access key to #{ credentials_path } "
@@ -36,11 +36,9 @@ def call
3636 log "Deleting your oldest access key..."
3737 delete_oldest_access_key
3838
39- log "You're all set!"
39+ log aws_environment_variables_warning_message if aws_environment_variables?
4040
41- if aws_environment_variables?
42- log aws_environment_variables_warning_message
43- end
41+ log "You're all set!"
4442 end
4543
4644 private
@@ -50,24 +48,14 @@ def create_access_key
5048 create_access_key_response . access_key
5149 end
5250
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-
6151 # ex. ~/aws/credentials.bkp-2017-01-06-16-38-07--0800
6252 def credentials_backup_path
6353 credentials_path + ".bkp-#{ Time . now . to_s . gsub ( /[^\d ]/ , '-' ) } "
6454 end
6555
66- def backup_aws_credentials_file
67- FileUtils . cp ( credentials_path , credentials_backup_path )
68- end
69-
7056 def write_aws_credentials_file ( access_key )
57+ FileUtils . mkdir_p ( File . dirname ( credentials_path ) ) # ensure credentials directory exists
58+
7159 File . open ( credentials_path , "w" ) do |f |
7260 f . puts "[default]"
7361 f . puts "aws_access_key_id = #{ access_key . access_key_id } "
@@ -83,20 +71,16 @@ def delete_oldest_access_key
8371 iam . delete_access_key ( access_key_id : oldest_access_key . access_key_id )
8472 end
8573
86- def credentials_dir
87- File . dirname ( credentials_path )
88- end
89-
9074 def log ( msg )
9175 stdout . puts msg
9276 end
9377
9478 def aws_environment_variables?
95- env [ 'AWS_ACCESS_KEY_ID' ] | | env [ 'AWS_SECRET_ACCESS_KEY' ]
79+ AWS_ENVIRONMENT_VARIABLES . any? { | v | env . key? ( v ) }
9680 end
9781
9882 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 " +
10084 "Please remove them so that aws cli and libraries use #{ credentials_path } instead."
10185 end
10286 end
0 commit comments