Skip to content

Instantly share code, notes, and snippets.

@mootpt
Last active May 17, 2022 16:41
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save mootpt/1ea7aac43e90d27ab890d45bc3b1d3d5 to your computer and use it in GitHub Desktop.
Save mootpt/1ea7aac43e90d27ab890d45bc3b1d3d5 to your computer and use it in GitHub Desktop.
Example using rsadecrypt interpolation function with windows.
# WARNING. DO NOT USE tls_private_key resource like I have done in this example
# Doing so will result in the private key being stored in state. You do not want that
# Instead use an existing key pair and use the file interpolation function to source
# the private key from disk for use in the rsadecrypt interpolation function
resource "tls_private_key" "key" {
algorithm = "RSA"
}
resource "aws_key_pair" "key_pair" {
key_name = "test-key"
public_key = "${tls_private_key.key.public_key_openssh}"
}
resource "aws_security_group" "allow_all" {
ingress {
from_port = 0
to_port = 65535
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
}
data "aws_ami" "windows_ami" {
most_recent = true
owners = ["amazon"]
filter {
name = "name"
values = ["Windows_Server-2012-R2_RTM-English-64Bit-Base-*"]
}
}
resource "aws_instance" "ec2" {
ami = "${data.aws_ami.windows_ami.image_id}"
instance_type = "t2.micro"
key_name = "${aws_key_pair.key_pair.key_name}"
security_groups = ["${aws_security_group.allow_all.name}"]
get_password_data = "true"
provisioner "remote-exec" {
inline = ["echo hello world"]
connection {
type = "winrm"
password = "${rsadecrypt(aws_instance.ec2.password_data,tls_private_key.key.private_key_pem)}"
}
}
}
output "instance_id" {
value = "${aws_instance.ec2.id}"
}
#This sources a pregenerated key from disk.
resource "aws_key_pair" "key_pair" {
key_name = "test-key"
public_key = "${file("test_key.pub")}"
}
resource "aws_security_group" "allow_all" {
ingress {
from_port = 0
to_port = 65535
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
}
data "aws_ami" "windows_ami" {
most_recent = true
owners = ["amazon"]
filter {
name = "name"
values = ["Windows_Server-2012-R2_RTM-English-64Bit-Base-*"]
}
}
resource "aws_instance" "ec2" {
ami = "${data.aws_ami.windows_ami.image_id}"
instance_type = "t2.micro"
key_name = "${aws_key_pair.key_pair.key_name}"
security_groups = ["${aws_security_group.allow_all.name}"]
get_password_data = "true"
provisioner "remote-exec" {
inline = ["echo hello world"]
connection {
type = "winrm"
password = "${rsadecrypt(aws_instance.ec2.password_data,file("test_key"))}"
}
}
}
output "instance_id" {
value = "${aws_instance.ec2.id}"
}
@chris1248
Copy link

Awesome. Thanks so much for this. It's what I've been looking for all day.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment