terraform:使用给定的公钥添加OS用户

时间:2018-06-20 11:45:42

标签: amazon-web-services amazon-ec2 terraform

我已使用Terraform在AWS上创建了EC2实例;

我想要在操作系统级别添加一个用户,并提供要添加到其~/.ssh/authorized_keys文件中的特定密钥。

aws_instance文档似乎没有列出此功能。

有办法解决吗?

编辑:我认为一种实现方法是通过remote-exec预配器,但是由于我已经创建了ec2资源,因此我需要一种强制运行该方法的方法。

2 个答案:

答案 0 :(得分:3)

在评论和编辑之后,您正在寻找的内容可能像这样:

resource "aws_instance" "default" {
  ...
  provisioner "remote-exec" {
    inline = [
      "sudo useradd someuser"
    ]

    connection {
      type        = "ssh"
      user        = "ubuntu"
      private_key = "${file("yourkey.pem")}"
    }
  }

  provisioner "file" {
    source      = "authorized_keys"
    destination = "/home/someuser/.ssh/authorized_keys"

    connection {
      type        = "ssh"
      user        = "ubuntu"
      private_key = "${file("yourkey.pem")}"
    }
  }

  provisioner "remote-exec" {
    inline = [
      "sudo chown someuser:someuser /home/someuser/.ssh/authorized_keys",
      "sudo chmod 0600 /home/someuser/.ssh/authorized_keys"
    ]

    connection {
      type        = "ssh"
      user        = "ubuntu"
      private_key = "${file("yourkey.pem")}"
    }
  }
  ...
}
  • 创建用户
  • 上传您的授权密钥文件
  • 在文件上为用户设置适当的权限

您也可以一次remote-exec一次完成所有操作,具体取决于您要如何处理authorized_keys文件的设置

答案 1 :(得分:2)

@布兰登·米勒(Brandon Miller)给出的答案似乎很好,我最后给出了以下内容(我必须承认,这不是很优雅):

  provisioner "remote-exec" {
    inline = [
        "sudo adduser --disabled-password --gecos '' myuser",
        "sudo mkdir -p /home/myuser/.ssh",
        "sudo touch /home/myuser/.ssh/authorized_keys",
        "sudo echo '${var.MY_USER_PUBLIC_KEY}' > authorized_keys",
        "sudo mv authorized_keys /home/myuser/.ssh",
        "sudo chown -R myuser:myuser /home/myuser/.ssh",
        "sudo chmod 700 /home/myuser/.ssh",
        "sudo chmod 600 /home/myuser/.ssh/authorized_keys",
        "sudo usermod -aG sudo myuser"
   ]

    connection {
     user     = "ubuntu"
    }

  }