Search code examples
amazon-web-servicesubuntuamazon-amipacker

Installing authorized_keys file under custom user for Ubuntu AWS


I'm trying to setup an ubuntu server and login with a non-default user. I've used cloud-config with the user data to setup an initial user, and packer to provision the server:

system_info:
  default_user:
    name: my_user
    shell: /bin/bash
    home: /home/my_user
    sudo: ['ALL=(ALL) NOPASSWD:ALL']

Packer logs in and provisions the server as my_user, but when I launch an instance from the AMI, AWS installs the authorized_keys files under /home/ubuntu/.ssh/

Packer config:

{
    "variables": {
        "aws_profile": ""
    },
    "builders": [{
        "type": "amazon-ebs",
        "profile": "{{user `aws_profile`}}",
        "region": "eu-west-1",
        "instance_type": "c5.large",
        "source_ami_filter": {
            "most_recent": true,
            "owners": ["099720109477"],
            "filters": {
                "name": "*ubuntu-xenial-16.04-amd64-server-*",
                "virtualization-type": "hvm",
                "root-device-type": "ebs"
            }
        },
        "ami_name": "my_ami_{{timestamp}}",
        "ssh_username": "my_user",
        "user_data_file": "cloud-config"
    }],
    "provisioners": [{
        "type": "shell",
        "pause_before": "10s",
        "inline": [
            "echo 'run some commands'"
        ]}
    ]
}

Once the server has launched, both ubuntu and my_user users exist in /etc/passwd:

my_user:1000:1002:Ubuntu:/home/my_user:/bin/bash
ubuntu:x:1001:1003:Ubuntu:/home/ubuntu:/bin/bash

At what point does the ubuntu user get created, and is there a way to install the authorized_keys file under /home/my_user/.ssh at launch instead of ubuntu?


Solution

  • To persist the default user when using the AMI to launch new EC2 instances from it you have to change the value is /etc/cloud/cloud.cfg and update this part:

    system_info:
       default_user:
         # Update this!
         name: ubuntu