首先,您需要一个计算实例:
resource "google_compute_instance" "website_server" {
name = "webserver"
description = "Web Server"
machine_type = "f1-micro"
allow_stopping_for_update = true
deletion_protection = false
tags = ["webserver-instance"]
shielded_instance_config {
enable_secure_boot = true
enable_vtpm = true
enable_integrity_monitoring = true
}
scheduling {
provisioning_model = "STANDARD"
on_host_maintenance = "TERMINATE"
automatic_restart = true
}
boot_disk {
mode = "READ_WRITE"
auto_delete = true
initialize_params {
image = "ubuntu-minimal-2204-jammy-v20220816"
type = "pd-balanced"
}
}
network_interface {
network = "default"
access_config {
network_tier = "PREMIUM"
}
}
metadata = {
ssh-keys = "${var.ssh_user}:${local_file.public_key.content}"
block-project-ssh-keys = true
}
labels = {
terraform = "true"
purpose = "host-static-files"
}
service_account {
# Custom service account with restricted permissions
email = data.google_service_account.myaccount.email
scopes = ["compute-rw"]
}
}
请注意,元数据中的“ssh-keys”字段需要以“授权密钥”格式提供公钥数据,即开放式SSH公钥。这类似于执行“pbcopy <~/.ssh/id_ed25519.pub”的操作。
您需要一个防火墙规则来允许默认端口22上的SSH连接:
resource "google_compute_firewall" "webserver_ssh" {
name = "webserver-firewall"
network = "default"
allow {
protocol = "tcp"
ports = ["22"]
}
target_tags = ["webserver-instance"]
source_ranges = ["0.0.0.0/0"]
}
您的公钥和私钥可以是短暂的,以使事情更加无缝:
resource "tls_private_key" "webserver_access" {
algorithm = "ED25519"
}
resource "local_file" "public_key" {
filename = "server_public_openssh"
content = trimspace(tls_private_key.webserver_access.public_key_openssh)
file_permission = "0400"
}
resource "local_sensitive_file" "private_key" {
filename = "server_private_openssh"
content = tls_private_key.webserver_access.private_key_openssh
file_permission = "0400"
}
最后,要登录您需要基于以下内容的连接字符串:
output "instance_connection_string" {
description = "Command to connect to the compute instance"
value = "ssh -i ${local_sensitive_file.private_key.filename} ${var.ssh_user}@${google_compute_instance.website_server.network_interface.0.access_config.0.nat_ip} ${var.host_check} ${var.ignore_known_hosts}"
sensitive = false
}
变量file可能看起来像:
variable "ssh_user" {
type = string
description = "SSH user for compute instance"
default = "myusername"
sensitive = false
}
variable "host_check" {
type = string
description = "Dont add private key to known_hosts"
default = "-o StrictHostKeyChecking=no"
sensitive = false
}
variable "ignore_known_hosts" {
type = string
description = "Ignore (many) keys stored in the ssh-agent; use explicitly declared keys"
default = "-o IdentitiesOnly=yes"
sensitive = false
}
can_ip_forward = true
:https://github.com/iostat/mesos-fun/blob/bb08bc4866a1ba4e535cbff4eba6611f1d3838b4/terraform/3-slaves.tf 和 https://www.terraform.io/docs/providers/google/r/compute_instance.html - mblakelessh-keys
而不是ssh_keys
,虽然两者都被接受,但它们执行不同的操作。您最有可能需要的是ssh-keys
而不是ssh_keys
。ssh_keys
安装了您的云帐户密钥,而ssh-keys
则安装了指定文件中的密钥。 - Christian Hujer