I am trying to create an ec2 instance and I want use ssh-key from AWS secrets manager Here is my terraform code , which is giving an error
A data resource "aws_secretsmanager_secret_version" "ssh_key" has not been declared in the root module.
I am not sure where it wants me to add secrets code and if this code is write or not
resource "aws_security_group" "wordpress_sg" {
name = "wordpress-sg"
description = "Security group for the WordPress instance"
ingress {
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"] // Allow SSH access from anywhere
}
ingress {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"] // Allow HTTP access from anywhere
}
ingress {
from_port = 443
to_port = 443
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"] // Allow HTTPS access from anywhere
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
}
resource "aws_instance" "example" {
ami = var.ami_id
instance_type = var.instance_type
key_name = data.aws_secretsmanager_secret_version.ssh_key
security_groups = [aws_security_group.wordpress_sg.name]
}
output "instance_public_ip" {
value = aws_instance.example.public_ip
}
data "aws_secretsmanager_secret" "secrets" {
arn = "arn:aws:secretsmanager:us-east-1:xxxx:secret:mysecret-xxxx"
}
data "aws_secretsmanager_secret_version" "current" {
secret_id = data.aws_secretsmanager_secret.secrets.id
}
My secret name is mysecret and ssh key is saved as key value pair named ssh-key
If you secret is already created, you dont need to recreate the same thing in terraform, (or any other IAC for that matter), its already there. I presume you already populated the secret in the console.
one way you could do it, is to make sure your box has an instance role, and profile, attach a policy that gives it access to the secret, and you can then use the awscli app to bring it in with your userdata.
in your userdata, you can then give the command
https://docs.aws.amazon.com/cli/latest/reference/secretsmanager/get-secret-value.html
and then send it into your .ssh/authorized_keys file.
KEY=aws secretsmanager get-secret-value --secret-id my-ssh-key-name
echo $KEY >>test.txt