So you’ve made a typo in your sudoers file on your Linux VM in Azure. Now sudo is broken and you don’t have the root password. You now have a VM with no ability to get escalated privileges which is a bit awkward as you’re delivering the VM to a client with a series of packages installed which require root permission. This is all a hypothetical situation of course.
You’ve got a few options to get root privileges back:
- Redeploy the VM
This is a bit of an extreme measure to fix a 1 line typo. If the VM is a fresh deploy and you’re using some automated deployment then it’s a viable option.
- Mount the OS drive of this broken VM to another VM in Azure
You can then fix the typo in the file and the OS drive should be peachy. The issue here is Azure doesn’t allow you to just remove the OS drive from a VM. You need to delete the VM and then OS disk will be available. You will then need to re-create the VM and attach this disk as the OS drive. There is a good guide over here that goes through that process with powershell. The guide is a bit older so the powershell commands might need to be updated.
- Set or reset the root password
Lucky for us Azure allows you to reset or set a user’s password on a VM using the console or shell commands. Sadly for us Azure doesn’t allow you to reset the root user’s password. It seems Azure did allow this at one point as this Microsoft article from 2016 shows. Though after much frustration at the command line this doesn’t seem to be the case. This updated article seems to show that.
- Fix the typo in the file somehow
It’s only a one line typo in the sudoers file, surely there is way to just delete the line or file that is causing sudo to break. This doesn’t seem to be an option from the OS as this error is a consistent reminder of this.
$ sudo su /etc/sudoers.d/99-admin: syntax error near line 1 <<< sudo: parse error in /etc/sudoers.d/99-admin near line 1 sudo: no valid sudoers sources found, quitting sudo: unable to initialize policy plugin
Maybe Azure has some script or module to run that will allow running OS commands on the VM. Bingo! The
az vm run-command does this and it seems to run with root creds. So we can use this module to run a command, in this case to delete the bad sudo file. I’m sure you can get creative with this command as it’s running as root.
[email protected]:~/.azure$ az vm run-command invoke -g resourcegroup01 -n vm01 --command-id RunShellScript --scripts "rm -rf /etc/sudoers.d/99-admin"
And just like that sudo is working again on our VM and we can continue with our work!
I’m sure there are a few methods to remedy this situation. This is the one I came up with after my brown trousers situation and panic googling didn’t come up with any firm answers. Give a shout in the comments if you’ve got another solution to this.