14

I'm trying to build a user data script for an EC2 instance that builds node and npm from github, and then starts a service. To grease these wheels, I need to add:

:/usr/local/bin

to the end of the line in /etc/sudoers which starts:

Defaults        secure_path="

https://superuser.com/questions/927512/how-to-set-path-for-sudo-commands talks about using visudo to achieve this, but I want to do it programatically within the EC2 user data.

https://stackoverflow.com/questions/16282789/adding-sudo-permissions-to-sudoers-for-user-via-shell-script talks about editing the sudoers file, but it seems awfully over baked for what I'm trying to achieve.

I thought it'd be easy to grep the line and replace it, but I'm stumped. Not only because of that annoying closing inverted comma!

3 Answers 3

13

If you can live with replacing the secure_path value instead of appending it, you can use a much easier solution. Usually sudo has a config directory like /etc/sudoers.d where you can drop additional configuration files.

Just create a file there with your complete secure_path value:

Defaults secure_path="<default value>:/usr/local/bin"

This overwrites the value from the main config. If the path value is the same for all your machines this can easily be deployed with scripts or a package.

This has the additional advantage that you don't have to check and possibly merge config files when the sudo package is updated in the future.

4

assuming you know the line with secure_path exists, a simple sed command to do this

sed -i -e '/secure_path/ s[=.*[&:/usr/local/bin[' /etc/sudoers

or a bit more sophisticated (more syntax check on input) :

sed -i -r -e '/^\s*Defaults\s+secure_path/ s[=(.*)[=\1:/usr/local/bin[' /etc/sudoers
1
  • Thank you! The second line was a really clean way of doing it. Jan 23, 2023 at 20:02
0

Lately, (perhaps since ever) you could've just added a line like this:

Defaults secure_path += ":/usr/local/bin"
1
  • 2
    This doesn't work with secure_path
    – Angelo
    Aug 3, 2021 at 22:38

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .