Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

My AWS CLI didn't work with sudo

Tags:

shell

aws-cli

I have shell script that uses aws cli, my script will be executed with sudo (Ex: sudo ./test.sh)

But I got the message: Unable to locate credentials. You can configure credentials by running "aws configure".

Actually, I did config for both sudo aws configure and aws configure

What did I do wrong? Please help. Thanks!

like image 639
Charles PHAM Avatar asked Oct 19 '16 09:10

Charles PHAM


2 Answers

You might have to run sudo with -E to preserve the environment variables set by aws cli.
sudo -E ./test.sh

like image 94
tobyd Avatar answered Nov 15 '22 09:11

tobyd


AWS CLI configured your credentials in $HOME/.aws/credentials. Normally when you use sudo, it doesn't change the value of the $HOME environment variable and so the AWS credentials file will be generated in the same location. You can check this by running aws configure as a normal user, typing in a key, then running sudo aws configure and you will be able to see that the default value would be the key that you just put in.

So at this point, you should be able to run sudo aws <facility> <some-command> and it will work fine - AWS CLI will use your current user's AWS credentials. I just tested it to make sure.

I suspect the problem is that you either invoke your script in a way that forces initialization of the session, such as bash -l - in which case AWS CLI will try to use the credentials of the root user; or you run your script from a user other than the one where you set up the AWS credentials and you expect that because you both use sudo it will get the same credentials (which is not the case as we demonstrated).

You should either:

  1. configure the AWS credentials for the root user by running sudo -i and then aws configure from withing a fully initialized root session, then make sure that all your scripts use a full root session (use #!/bin/bash -l as the shebang).
  2. If your issue is the second one and you don't want to do the complex solution suggested in (1), you should configure the AWS credentials for each of the users.
like image 41
Guss Avatar answered Nov 15 '22 10:11

Guss