2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

TerraformでEC2のauthorized_keysをUserDataとcloud-initで設定する

Posted at

TerraformにてUserDataにcloud-initを設定する方法でSSH公開鍵を authorized_keys に設定する方法を記載します。

variables に公開鍵を list(string) で受けるように設定し、tfvars にもリスト形式で設定しておきます。

variable.tf
variable "ssh_authorized_keys" {
  type = list(string)
}
ssh_authorized_keys = [
  "ssh-rsa xxxxx",
  "ssh-rsa yyyyy",
]

後はyamlencode関数で受ければOKです。

ec2.tf
resource "aws_instance" "instance" {
# 省略

  user_data = <<EOF
Content-Type: multipart/mixed; boundary="==BOUNDARY=="
MIME-Version:  1.0

--==BOUNDARY==
Content-Type: text/cloud-config; charset="us-ascii"
MIME-Version:  1.0
#cloud-config
${yamlencode({ "ssh_authorized_keys" : var.ssh_authorized_keys })}

EOF
}

参考

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?