You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置Packer通过SSH连接GCP VM构建镜像及解决认证错误

问题:Packer构建GCP镜像时SSH认证失败

我使用Packer构建GCP镜像,已创建拥有「Compute Instance Admin v1」和「Service Account User」权限的服务账号。该账号可成功创建VM,但无法通过SSH连接实例以继续自定义镜像的构建。

报错信息

Build 'googlecompute.custom-image' errored after 2 minutes 20 seconds: Packer experienced an authentication error when trying to connect via SSH. This can happen if your username/password are wrong. You may want to double-check your credentials as part of your debugging process. original error: ssh: handshake failed: ssh: unable to authenticate, attempted methods [none publickey], no supported methods remain

构建文件源码(packer.pkr.hcl)

locals {
  project_id              = "project-id"  
  source_image_family     = "rocky-linux-8"           
  source_image_project_id = ["rocky-linux-cloud"]     
  ssh_username            = "packer"                   
  machine_type            = "e2-medium"               
  zone                    = "us-central1-a"  
}

source "googlecompute" "custom-image" {

  image_name = "custom-image"  # Name of image to be created
  image_description       = "Custom Image 1"    # Description for image to be created
  project_id              = "${local.project_id}"
  source_image_family     = "${local.source_image_family}"
  source_image_project_id = "${local.source_image_project_id}"
  ssh_username            = "${local.ssh_username}"
  machine_type            = "${local.machine_type}"
  zone                    = "${local.zone}"
}

build {
  sources = ["source.googlecompute.custom-image"]

  #
  # Run arbitrary shell script file
  #
  provisioner "shell" {
    execute_command = "sudo su - root -c \"sh {{ .Path }} \""
    script          = "foo.sh"
  }

}

解决方案

1. 修正SSH用户名

Rocky Linux 8官方镜像的默认管理员用户是rocky,而非配置中的packer,修改locals里的用户名:

locals {
  # 保留其他配置
  ssh_username = "rocky"
}

2. 开启Packer自动生成SSH密钥

在googlecompute源配置中添加ssh_generate_key_pair = true,让Packer自动生成密钥并注入实例,无需手动管理密钥:

source "googlecompute" "custom-image" {
  # 保留其他配置
  ssh_generate_key_pair = true
}

3. 验证网络防火墙规则

确认实例所在VPC的防火墙允许22端口(SSH)的入站流量,默认VPC通常自带allow-ssh规则,自定义VPC需手动添加该规则。

4. 简化Shell Provisioner执行命令

rocky用户默认拥有sudo权限,无需先切换到root再执行脚本,简化命令避免冗余操作:

provisioner "shell" {
  execute_command = "sudo sh {{ .Path }}"
  script          = "foo.sh"
}

内容的提问来源于stack exchange,提问作者kristen_1024

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 21:41:11