Skip to content

Instantly share code, notes, and snippets.

@jeanlouisferey
Last active September 1, 2023 12:34
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save jeanlouisferey/15be1f421eb9f9a66f1c74d410de2675 to your computer and use it in GitHub Desktop.
Save jeanlouisferey/15be1f421eb9f9a66f1c74d410de2675 to your computer and use it in GitHub Desktop.
How to create a LXD Container with your ssh key in it (and with ssh server in the container)

How to create a LXD Container with your ssh key in it (and with ssh server in the container)

Create a brand new ed25519 key pair

ssh-keygen -o -a 100 -t ed25519

Get the pub key and put the result in your lxd default profile

cat ~/.ssh/ed25519.pub
lxc profile edit default
config:
user.user-data: |
  #cloud-config
  ssh_authorized_keys:
    - ssh-ed25519 AAAAC......

Create a new container from ubuntu

lxc launch Ubuntu.16.04 MyContainer

Get into the container and install ssh server

lxc exec MyContainer /bin/bash
apt update
apt upgrade
apt install ssh

Verify ssh connexion with key is ok

ssh root@Container -i .ssh/ed25519

Stop the Container and create a new image from this container

lxc stop MyContainer
lxc publish MyContainer --alias=MyImage description="My base image (with ssh and key)"
lxc delete MyContainer

Start a new container and verify everything is ok

lxc launch MyImage TestContainer
lxc list (to get TestContainer Ip)
sh root@TestContainer -i .ssh/ed25519
@thepenguinthatwants
Copy link

Hi!

I've tried your steps but I only get

Permission denied (publickey)

When I try to ssh to the image. Is there some steps undocumented or something?

@thepenguinthatwants
Copy link

no-port-forwarding,no-agent-forwarding,no-X11-forwarding,command="echo 'Please login as the user "ubuntu" rather than the user "root".';echo;sleep 10"

@zarinfam
Copy link

Thanks, It was very helpful for me. You can install openssh-server using cloud-init by adding this to your profile:

    packages:
      - openssh-server

@talDoFlemis
Copy link

If someone is trying to setup a user to make this connection and it's not working try this :

config:
  cloud-init.user-data: |
    #cloud-config
    packages:
      - openssh-server
      - vim
    ssh_pwauth: false
    users:
      - name: ansible
        gecos: Ansible User
        groups: users,admin,wheel
        sudo: ALL=(ALL) NOPASSWD:ALL
        shell: /bin/bash
        ssh_authorized_keys:
          - "ssh-pub-key here" 

It should be users instead of user that was written on documentation of LXD.
And for more examples see the cloud-init examples

@jeanlouisferey
Copy link
Author

Thank you @zarinfam and @talDoFlemis

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment