Fixing an AWS EC2 Instance Boot Up Issue

Background

We recently had a problem with one of our AWS EC2 Instances after shutting it down, making some configuration changes and starting it back up. We were unable to SSH onto the machines despite the fact that the machine came up OK (we would keep getting a Connection Refused error). We reviewed the Security Group settings, Network Settings, reverted our configuration changes, made sure we were pointing to the correct IP address and much more, but we still couldn’t SSH onto the machine.

Upon viewing the system logs, we noticed that one of the disk volumes failed to be mounted onto the machine. It was an Instance Store drive that apparently was remounted onto the machine after restarting it under a different device name. This prevented the boot up from completing, which as a result prevented the sshd daemon from being started up to allow us to SSH onto the machine. With us not being able to SSH onto the machine to effect repairs we were left dead in the water. But we eventually figured a way to allow us to view the file system and make the necessary changes to fix the issue, which is described in this blog post.

In our case it was an issue with the /etc/fstab that caused us to have to follow these steps, but there are other cases where these steps can also benefit you. For example, if you mistakingly configured sshd not to start on startup of the machine or if something else failed to run during boot up which prevented the sshd daemon from starting up.

High Level Process

To resolve this, we’re going to basically unmount the bad machines root file system, mount it to a healthy machine so we can explore the file system and fix the issue, and then remount it back to the original instance.

Step by Step Process

Setup

Suppose we have our EC2 instance (call it prod-instance) which has booted up ok, but we’re unable to SSH onto.

Setup

Steps

  1. Loin to the AWS Web Console
  2. Stop the prod-instance instance
  3. Detach the root EBS volume from the prod-instance
    1. Select the prod-instance EC2 instance in the AWS console and view the content in the “Description” tab in the window bellow the instance list
    2. Search for the “Root device” field
    3. Click on the link next to it
      • It should look something like this: /dev/xvda
      • A dialog box will pop up
        Block Device Modal
    4. Take a note of the EBS ID
      • For the bellow the steps bellow, assume the EBS ID is vol-0c7bf2325c6ab485b
    5. Click on the EBS ID link
      • This will take you to a new list with information on that EBS Volume
        Available Volumes
    6. Make sure the EBS Volume vol-0c7bf2325c6ab485b is selected and click Actions -> Detach Volume
      Attached Volume Actions
    7. If you would like to abort this and reattach the volume, Jump to step #15
  4. Create a brand new micro instance that you’re able to SSH into and let it startup. We’ll call it maintenance-instance.
    • Make sure that its in the same Region and Availability Zone of the machine you detached the root volume from. Volumes cannot switch between availability zones.
    • Note: Be sure you can SSH onto the machine before proceeding forward
      ssh -i {pem_file} {username}@{ec2_host_or_ip}
       Prod Instance Stopped
  5. Mount the prod-instance‘s old root EBS volume to the maintenance-instance as an additional drive
    1. Click on the “Volumes” link on the left side of the AWS EC2 Web Console under ELASTIC BLOCK STORE
    2. Search for the EBS Volume you detached (vol-0c7bf2325c6ab485b). It will also be listed as having the State “available” (as opposed to “in-use”).
      Volume available
    3. Select the volume and click Actions -> Attach Volume
      Detached Volume Actions
    4. This will open a modal
      Attach Volume
    5. Search for your the maintenance-instance and click on the entry
      Instance Added to Attach Volume
      • By clicking on the entry it will put in a default value into the Device field. If it doesn’t, you can put in the value /dev/sdf.
    6. Click Attach
    7. Note: You do not need to stop or restart maintenance-instance before or after attaching the instance. 
  6. SSH onto the maintenance-instance
  7. Login as root
    sudo su
  8. Check the disk to ensure that the prod-instance‘s old root EBS volume is available and get the device name
    1. Run the following command to get information about what volumes are currently mounted (which should only be the default root volume at this point)
      df -h
      • This will produce a result like this:
        Filesystem Size Used Avail Use% Mounted on
        devtmpfs 488M 64K 488M 1% /dev
        tmpfs 498M 0 498M 0% /dev/shm
        /dev/xvda1 7.8G 981M 6.7G 13% /
      • What this tells you is that there is one main drive called /dev/xvda1 which is the root volume of the maintenance-instance. Thus we can ignore this device name.
    2. Run the following command to find out what the device name is of the volume we want to effect repairs on
      lsblk
      • This will produce a result like this:
        NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT
        xvda 202:0 0 8G 0 disk
        └─xvda1 202:1 0 8G 0 part /
        xvdf 202:80 0 8G 0 disk
        └─xvdf1 202:81 0 8G 0 part
      • What this tells you, is that there are 2 main disks attached, each with one partition. We’ve already found out that the xvda device is the original root volume of the maintenance-instance, so by process of elimination xvdf is the disk we mounted onto the machine and want to effect repairs on.
    3. Get the device name of the volume you mounted onto the machine
      1. In our case, based off the output above, the device name is: /dev/xvdf1 (which is the partition of that disk)
      2. Note: you may have noticed the device name also available in the AWS console under the Description of the machine and under the Block devices section. However, the value provided in the AWS console isn’t always the same as the one you will see when using the fdisk or lsblk command, so therefore you shouldn’t use this value. Use the one provided in the fdisk or lsblk command.
  9. Create the directory that you want to mount the volume to (this can be named and placed wherever you would like)
    mkdir /badvolume
  10. Mount the drives partition to the directory
    mount /dev/xvdf1 /badvolume
  11. Explore the file system and make the necessary change you would like to it
    • Change directory to the newly mounted file system
      cd /badvolume
    • Note: In our case, since we were dealing with a mounting issue, we had to modify the /etc/fstab file to prevent the machine from trying to mount the volume that was failing. Since theprod-instance‘s root volume was mounted onto the /badvolume directory, the fstab file that we need to fix is at /badvolume/etc/fstab.
      • We simply commented out the bad entry and then moved on
    • When you have completed your repairs, move onto the next step
  12. Unmount the drive from the machine
    umount /badvolume
  13. Switch back to the AWS Web Console
  14. Detach the vol-0c7bf2325c6ab485b volume from the maintenance-instance
    1. Click on the “Volumes” link on the left side of the AWS Web Console under ELASTIC BLOCK STORE
    2. Search for the EBS Volume you detached (vol-0c7bf2325c6ab485b). It will also be listed as having the State “in-use”.
    3. Select the volume and click Actions -> Detach Volume
      Attached Volume Actions
  15. Re-Attach the vol-0c7bf2325c6ab485b volume to the prod-instance as the root volume
    1. Click on the “Volumes” link on the left side of the AWS Web Console under ELASTIC BLOCK STORE
    2. Search for the EBS Volume you detached (vol-0c7bf2325c6ab485b). It will also be listed as having the State “available”.
    3. Select the volume and click Actions -> Attach Volume
      Detached Volume Actions
    4. This will open a modal
      Attach Volume
    5. Search for your the prod-instance
    6. Set the Device as the root volume with the value: /dev/xvda
      Instance Added to Attach Volume
    7. Click Attach
  16. Restart the prod-instance
  17. Test SSH’ing onto the prod-instance
  18. If you’re still having issues connecting to the prod-instance then check the system logs of the machine to debug the problem and, if necessary, repeat these steps to fix the issue with the drive.
  19. When you’re all done you can terminate the maintenance-instance

Encrypting Amazon EC2 boot volumes via Packer

In order to layer on some easy data-at-rest security, I want to encrypt the boot volumes of my Amazon EC2 instances.  I also want to use the centos.org CentOS images but those are not encrypted.  How can I end up with an encrypted copy of those AMIs in the fewest steps?

In the past, I have used shell scripts and the AWS CLI to perform the boot volume encryption dance. The steps are basically:

  1. Deploy an instance running the source AMI.
  2. Create an image from that instance.
  3. Copy the image and encrypt the copy.
  4. Delete the unencrypted image.
  5. Terminate the instance.
  6. Add tags to new AMI.

The script has a need for a lot of VPC/subnet/security group preparation (which I guess could have been added to the script), and if there were errors during the execution then cleanup was very manual (more possible script work). The script is very flexible and meets my needs, but it is a codebase that needs expertise in order to maintain. And I have better things to do with my time.

A simpler solution is Packer.

I had looked at Packer around July of 2016 and it was very promising, but it was missing one key feature: it could not actually encrypt the boot volume. Dave Konopka wrote a post describing the problem and his solution of using Ansible in Encrypted Amazon EC2 boot volumes with Packer and Ansible.

Luckily, there was an outstanding pull request and as of version 0.11.0, Packer now has support for boot volume encryption whilst copying Marketplace AMIs.

The nice thing about a Packer template is that it takes care of dynamic generation of most objects. Temporary SSH keys and security groups are created just for the build and are then destroyed. The above steps for the boot volume encryption dance are followed with built-in error checking and recovery in case something goes wrong.

This template assumes automatic lookup of your AWS credentials. Read the docs (Specifying Amazon Credentials section) for more details.

Code can be downloaded from GitHub.

$ cat encrypt-centos.org-7-ami.json
{
    "description": "Copy the centos.org CentOS 7 AMI into our account so that we can add boot volume encryption.",
    "min_packer_version": "0.11.0",
    "variables": {
        "aws_region": "us-east-1",
        "aws_vpc": null,
        "aws_subnet": null,
        "ssh_username": "centos"
    },
    "builders": [
        {
            "type": "amazon-ebs",
            "ami_name": "CentOS Linux 7 x86_64 HVM EBS (encrypted) {{isotime \"20060102\"}}",
            "ami_description": "CentOS Linux 7 x86_64 HVM EBS (encrypted) {{isotime \"20060102\"}}",
            "instance_type": "t2.nano",
            "region": "{{user `aws_region`}}",
            "vpc_id": "{{user `aws_vpc`}}",
            "subnet_id": "{{user `aws_subnet`}}",
            "source_ami_filter": {
                "filters": {
                    "owner-alias": "aws-marketplace",
                    "product-code": "aw0evgkw8e5c1q413zgy5pjce",
                    "virtualization-type": "hvm"
                },
                "most_recent": true
            },
            "ami_virtualization_type": "hvm",
            "ssh_username": "{{user `ssh_username`}}",
            "associate_public_ip_address": true,
            "tags": {
                "Name": "CentOS 7",
                "OS": "CentOS",
                "OSVER": "7"
            },
            "encrypt_boot": true,
            "ami_block_device_mappings": [
                {
                    "device_name": "/dev/sda1",
                    "volume_type": "gp2",
                    "volume_size": 8,
                    "encrypted": true,
                    "delete_on_termination": true
                }
            ],
            "communicator": "ssh",
            "ssh_pty": true
        }
    ],
    "provisioners": [
        {
            "type": "shell",
            "execute_command": "sudo -S sh '{{.Path}}'",
            "inline_shebang": "/bin/sh -e -x",
            "inline": [
                "echo '** Shreding sensitive data ...'",
                "shred -u /etc/ssh/*_key /etc/ssh/*_key.pub",
                "shred -u /root/.*history /home/{{user `ssh_username`}}/.*history",
                "shred -u /root/.ssh/authorized_keys /home/{{user `ssh_username`}}/.ssh/authorized_keys",
                "sync; sleep 1; sync"
            ]
        }
    ]
}

To copy the CentoS 6 AMI, change any references of CentOS “7” to “6” and the product-code from “aw0evgkw8e5c1q413zgy5pjce” to “6x5jmcajty9edm3f211pqjfn2”.

When you build with this Packer template, you will have to pass in the variables aws_vpc and aws_subnet. The AWS region defaults to us-east-1, but can be overridden by setting aws_region. The newest centos.org CentOS AMI in that region will be automatically discovered.

$ packer build -var 'aws_vpc=vpc-12345678' -var 'aws_subnet=subnet-23456789' \
encrypt-centos.org-7-ami.json
amazon-ebs output will be in this color.

==> amazon-ebs: Prevalidating AMI Name...
    amazon-ebs: Found Image ID: ami-6d1c2007
==> amazon-ebs: Creating temporary keypair: packer_583c7438-d1d8-f33d-8517-1bdbbd84d2c9
==> amazon-ebs: Creating temporary security group for this instance...
==> amazon-ebs: Authorizing access to port 22 the temporary security group...
==> amazon-ebs: Launching a source AWS instance...
    amazon-ebs: Instance ID: i-5b68a2c4
==> amazon-ebs: Waiting for instance (i-5b68a2c4) to become ready...
==> amazon-ebs: Waiting for SSH to become available...
==> amazon-ebs: Connected to SSH!
==> amazon-ebs: Provisioning with shell script: /var/folders/42/drnmdknj7zz7bf03d91v8nkr0000gq/T/packer-shell797958164
    amazon-ebs: ** Shreding sensitive data ...
    amazon-ebs: shred: /root/.*history: failed to open for writing: No such file or directory
    amazon-ebs: shred: /home/centos/.*history: failed to open for writing: No such file or directory
==> amazon-ebs: Stopping the source instance...
==> amazon-ebs: Waiting for the instance to stop...
==> amazon-ebs: Creating the AMI: CentOS Linux 7 x86_64 HVM EBS (encrypted) 1480356920
    amazon-ebs: AMI: ami-33506f25
==> amazon-ebs: Waiting for AMI to become ready...
==> amazon-ebs: Creating Encrypted AMI Copy
==> amazon-ebs: Copying AMI: us-east-1(ami-33506f25)
==> amazon-ebs: Waiting for AMI copy to become ready...
==> amazon-ebs: Deregistering unencrypted AMI
==> amazon-ebs: Deleting unencrypted snapshots
    amazon-ebs: Snapshot ID: snap-5c87d7eb
==> amazon-ebs: Modifying attributes on AMI (ami-9d4b748b)...
    amazon-ebs: Modifying: description
==> amazon-ebs: Adding tags to AMI (ami-9d4b748b)...
    amazon-ebs: Adding tag: "OS": "CentOS"
    amazon-ebs: Adding tag: "OSVER": "7"
    amazon-ebs: Adding tag: "Name": "CentOS 7"
==> amazon-ebs: Tagging snapshot: snap-1eb5dc01
==> amazon-ebs: Terminating the source AWS instance...
==> amazon-ebs: Cleaning up any extra volumes...
==> amazon-ebs: Destroying volume (vol-aa727a37)...
==> amazon-ebs: Deleting temporary security group...
==> amazon-ebs: Deleting temporary keypair...
Build 'amazon-ebs' finished.

==> Builds finished. The artifacts of successful builds are:
--> amazon-ebs: AMIs were created:

us-east-1: ami-9d4b748b