在 Ubuntu AWS 的自定义用户下安装 authorized_keys 文件

Installing authorized_keys file under custom user for Ubuntu AWS

我正在尝试设置 ubuntu 服务器并使用非默认用户登录。我使用 cloud-config 和用户数据来设置初始用户,并使用 packer 来配置服务器:

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

Packer 登录并将服务器配置为 my_user,但是当我从 AMI 启动实例时,AWS 在 /home/ubuntu/.ssh/[= 下安装 authorized_keys 文件15=]

打包机配置:

{
    "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'"
        ]}
    ]
}

服务器启动后,ubuntu 和 my_user 用户都存在于 /etc/passwd:

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

什么时候创建了 ubuntu 用户,有没有办法在启动时在 /home/my_user/.ssh 下安装 authorized_keys 文件而不是 ubuntu?

您可以在使用 cloud-init 创建用户时添加 public 密钥。这是您的操作方法。

users:
  - name: <username>
    groups: [ wheel ]
    sudo: [ "ALL=(ALL) NOPASSWD:ALL" ]
    shell: /bin/bash
    ssh-authorized-keys: 
    - ssh-rsa AAAAB3Nz<your public key>...

Addding additional SSH user account with cloud-init

要在使用 AMI 从中启动新的 EC2 实例时保留默认用户,您必须更改值为 /etc/cloud/cloud.cfg 并更新此部分:

system_info:
   default_user:
     # Update this!
     name: ubuntu