Gaining access to inherited AWS EC2 instances
You could also use the user data to install the SSM agent and connect using System Manager, avoiding the hassle of SSH altogether.
This is the easy case; I hoped this article would cover the more challenging scenarios, like when:
-
the OS on the inherited instance does not execute user-data (it often does, but it is not a requirement) - in which case you can attach the root EBS disk to a different instance as its secondary volume to alter its files as you need
-
you cannot afford downtime, that is, the inherited instance has to keep running and cannot be stopped
-
the target instance does not currently run an SSH server
etc.
The only reasonable solution to zero downtime i can think of is to clone the target machine, give yourself access to the clone, and then redirect traffic to the clone.
Which is not ideal in some cases.
Any other ways?
I thought UserData only ran on instance creation (RunInstance) not subsequent starts (StartInstance) unless you prep the instance in advance to do this every Start?
the OS on the inherited instance does not execute user-data
If you can remount the root volume on an instance of your own you control and simply run passwd on an existing account. Its annoying but not difficult.
you cannot afford downtime, that is, the inherited instance has to keep running and cannot be stopped
This one is easy. If it cannot have downtime it is woefully behind on security patches. Exploit one of the dozens of vulnerabilities to gain root access. /s
the target instance does not currently run an SSH server
How about serial console?
AFAIK that’s true for Windows. Not for Linux.
user data is ran only once though.
By default, user data scripts and cloud-init directives run only during the boot cycle when you first launch an instance.
It depends on the cloud-init directive, but the key point is that you can use it to regain access to a Linux EC2 instance because it’ll re-evaluate the user data when it reboots. For example, “bootcmd” runs on every boot.
If you open this page and do a Ctrl+F for “always”, you’ll see a lot of the modules have a frequency of “always” (runs every boot):
https://cloudinit.readthedocs.io/en/latest/reference/modules.html
You’ll also see in the OP article it’s doing this:
cloud_final_modules:
- [scripts-user, always]
That’s configuring “scripts-user” to run on every boot, and it’s doing it via userdata.
This is different from the behavior on Windows, where by default, there is nothing you can change or configure via userdata after it has first booted (without otherwise configuring it manually to do so), which makes it not suitable for regaining administrative access to the box. Or at least that’s my understanding.