Promting for Sudo Password in Travis


"Lucy, why would you want to do this? ARE YOU OK?" It's true: making Travis print the sudo prompt and enter it's password is not a common use case. We were testing a new feature in Bolt which opens a subprocess on the local machine and runs a command as a different user (code, docs). We like to have as many tests in Travis so that our users and contributors see if their own code breaks tests (as opposed to our acceptance tests which run nightly in Jenkins). So, to test this properly in Travis, I needed to make the travis user be prompted for sudo.

I initially tried creating a different user and running the test as that user, so that I didn't have to mess with the sudo configuration of travis. This turned out to be more difficult than expected, since switching the user opens a new login which stops the tests from running.

So, we were stuck with travis. Here's the magic lines I added to the 'before_script' section of .travis.yml:

- echo 'travis:travis' | sudo chpasswd
- sudo sh -c "echo 'Defaults authenticate' >> /etc/sudoers"
- sudo sh -c "echo 'travis  ALL=(ALL) PASSWD:ALL' >> /etc/sudoers"

By default Travis sets Defaults !authenticate and travis ALL=(ALL) NOPASSWD:ALL in /etc/sudoers.d/travis. The first thing we needed to do was give travis a password so that we could still authenticate, then undo this sudo config. Also worth noting: you must set the NOPASSWD line last, otherwise you won't be able to use sudo to modify the sudo config!

Et voila! We can test prompting for a sudo password in Travis.