'My AWS CLI didn't work with sudo

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!



Solution 1:[1]

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

Solution 2:[2]

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.

Solution 3:[3]

You can do the following:

sudo cp -r /home/<username>/.aws /home/root

Now you can use the same user credentials for root.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 tobyd
Solution 2 Guss
Solution 3 Misael Abanto