如何使用 Terraform 在 Openstack 实例上添加非 root ssh 密钥?

问题描述 投票:0回答:2

我正在尝试使用 Terraform 创建一个 Openstack 实例,之后,我想使用我的 ssh 密钥配置用户“ubuntu”。

到目前为止我正在做:

terraform-instances.tf

resource "openstack_compute_keypair_v2" "tf-keypair" {
  name       = "${var.openstack_keypair}"
  public_key = "${file("~/.ssh/id_rsa.pub")}"
}

resource "openstack_compute_instance_v2" "k8s-master" {
  name      = "k8s-master"
  region    = "${var.openstack_region}"
  image_id  = "${var.openstack_image_id}"
  flavor_id = "${var.openstack_flavor_id}"
  key_pair  = "${var.openstack_keypair}"
  depends_on = ["openstack_compute_keypair_v2.tf-keypair"]

  network {
    uuid = "00000000-0000-0000-0000-000000000000"
    name = "public"
  }
  network {
    uuid = "11111111-1111-1111-1111-111111111111"
    name = "private"
  }
}

resource "null_resource" "authkeys" {
  depends_on = ["openstack_compute_instance_v2.k8s-master"]
  provisioner "file" {
    source      = "authorized_keys"
    destination = "/home/ubuntu/.ssh/authorized_keys"
    }

  connection {
    host        = "${openstack_compute_instance_v2.k8s-master.network.0.fixed_ip_v4}"
    type        = "ssh"
    user        = "root"
    private_key = "${file("~/.ssh/id_rsa")}"
    timeout     = "45s"
    }
}

所以运行后:

terraform apply 

实例已创建,使用 root 用户的 ssh 密钥,但不使用 ubuntu 用户。

如何为 ubuntu 用户部署 ssh 密钥?

openstack terraform ssh-keys terraform-provider-openstack
2个回答
0
投票

这可能不是最优雅的解决方案,但它有效。我基本上正在运行一个通过

user_data
传递的脚本。这允许我上传多个公钥,并将其保存为变量列表。

resource "openstack_compute_instance_v2" "my_instance" {
  name         = "my_instance_name"
  flavor_id    = var.flavor_id_compute
  image_id     = var.image_id
  ...
  security_groups = [var.security_group_name]
  user_data = <<-EOF
    #!/bin/bash
    echo "${join("\n", var.ssh_public_keys)}" > /tmp/authorized_keys
    sudo mv /tmp/authorized_keys /home/ubuntu/.ssh/authorized_keys
    sudo chown ubuntu:ubuntu /home/ubuntu/.ssh/authorized_keys
    sudo chmod 600 /home/ubuntu/.ssh/authorized_keys
    echo "###" > /tmp/authorized_keys
  EOF
}

然后在我的

variables.tf
文件中我有:

variable "ssh_public_keys" {
  description = "List of SSH public keys"
  type        = list(string)
  default     = [
    "ssh-rsa xxxxxxxxxxxxx user1”,
    "ssh-rsa xxxxxxxxxxxxx user2”,
    # Add more keys as needed
  ]
}

-1
投票

我建议使用 cloud-init,因为 openstack 中没有内置任何内容(它实际上使用 cloud-init 本身来预先播种密钥)。

© www.soinside.com 2019 - 2024. All rights reserved.