it runs but a part of actual execution fails as user2 's environment is NOT set.
Hence tried below -
sudo -i -u user2 /usr/local/bin/script.sh
But it asks for password, if I type in the password then the script runs just fine but the problem is that it prompts for password which is a problem for automation. So my query is how could I run sudo -i without password prompt.
I think one way is to set user2's environment into the script itself but not sure which environment variables I need to set and also anything else that might be needed.
You are correct that the issue is that the environment variables for user2 are not set when running the script with sudo -u user2. To run the script as user2 with their environment variables set, you can use the sudo -i -u user2 command, but this prompts for a password.
One solution would be to use the sudo -n option, which allows you to run a command with elevated privileges without being prompted for a password. So you can use the command sudo -n -i -u user2 /usr/local/bin/script.sh to run the script as user2 with their environment variables set, without being prompted for a password.
Another solution would be to set the needed environment variables in the script itself, by using the export command. You can use the printenv command to see all the environment variables for user2, and then set them in the script using the export command.
You also need to make sure that user1 has the permissions to run the script in the first place.
If you want to avoid using the sudo command altogether, you could also give user1 the necessary permissions to run the script as user2 without using sudo. This can be done by adding user1 to the same group as user2 or by changing the ownership and permissions of the script to allow user1 to execute it.
sudo -n -i -u is not a solution as it throws sudo: a password is required error and exits silently.
From sudo man page -
-n, --non-interactive
Avoid prompting the user for input of any kind. If a
password is required for the command to run, sudo will
display an error message and exit.
Looks like setting environment variables in the script itself is the only option but updating script is my last option, looking for a better/alt solution.
when using -i, the target user's login shell is invoked (so potential .bashrc, .profile etc. are sourced) in order to execute the given command. So you have to allow the full command line in the sudoers file:
, /path/to/command must be appended to make it also work without -i (maybe wildcards can be used in order to eliminate this redundancy).
Normally, the login shell is one of /bin/{bash,ksh,dash,sh}. You can find it via getent passwd user2 | cut -d: -f7.
For debugging sudo, you can comment out the last 2 entries in /etc/sudo.conf:
Not necessarily. Shorter files in /etc/<whatever>.d/ get things way better organized and easier to mantain, automate, and so on. But are not mandatory.