Bare Metal Cloud - 如何为计算实例设置授权的 ssh 密钥?

Bare Metal Cloud - How to set authorized ssh keys for compute instances?

我已经使用以下代码成功配置了裸机云计算实例:

public static Instance createInstance(
        ComputeClient computeClient,
        String compartmentId,
        AvailabilityDomain availabilityDomain,
        String instanceName,
        Image image,
        Shape shape,
        Subnet subnet
    ) {

    LaunchInstanceResponse response = computeClient.launchInstance(
        LaunchInstanceRequest.builder()
            .launchInstanceDetails(
                LaunchInstanceDetails.builder()
                    .availabilityDomain(availabilityDomain.getName())
                    .compartmentId(compartmentId)
                    .displayName(instanceName)
                    .imageId(image.getId())
                    .shape(shape.getShape())
                    .subnetId(subnet.getId())
                    .build())
            .build());  

    return response.getInstance();
}

但是,我无法通过 SSH 连接到我通过上面的代码创建的任何实例,因为 launchInstance 上没有参数来传递我的 SSH 密钥对的 public 密钥。

如何告诉实例允许使用什么 SSH public 密钥?我知道这一定是可行的,因为控制台 UI 允许我提供 SSH public 密钥作为实例创建的一部分。

根据 launch instance API documentation,您需要通过 metadata 参数的 ssh_authorized_keys 字段传递 SSH public 密钥:

Providing Cloud-Init Metadata

You can use the following metadata key names to provide information to Cloud-Init:

"ssh_authorized_keys" - Provide one or more public SSH keys to be included in the ~/.ssh/authorized_keys file for the default user on the instance. Use a newline character to separate multiple keys. The SSH keys must be in the format necessary for the authorized_keys file

Java SDK 中的代码如下所示:

public static Instance createInstance(
        ComputeClient computeClient,
        String compartmentId,
        AvailabilityDomain availabilityDomain,
        String instanceName,
        Image image,
        Shape shape,
        Subnet subnet
    ) {

    String sshPublicKey = "ssh-rsa AAAAB3NzaC1y...key shortened for example...fdK/ABqxgH7sy3AWgBjfj some description";

    Map<String, String> metadata = new HashMap<>();
    metadata.put("ssh_authorized_keys", sshPublicKey);

    LaunchInstanceResponse response = computeClient.launchInstance(
        LaunchInstanceRequest.builder()
            .launchInstanceDetails(
                LaunchInstanceDetails.builder()
                    .availabilityDomain(availabilityDomain.getName())
                    .compartmentId(compartmentId)
                    .displayName(instanceName)
                    .imageId(image.getId())
                    .metadata(metadata)
                    .shape(shape.getShape())
                    .subnetId(subnet.getId())
                    .build())
            .build());  

    return response.getInstance();
}

然后该实例将允许您使用该 public 密钥的 SSH 密钥对通过 SSH 连接到它。