Aws key_pair: key_type is null

What’s wrong with this code? aws_key_pair.key_type is always null. How to fix that?

resource “tls_private_key” “rsa-4096-example” {
algorithm = “RSA”
}

resource “local_file” “foo” {
content = tls_private_key.rsa-4096-example.private_key_openssh
filename = “/home/bob/id_rsa.pem”
}

resource “aws_key_pair” “devops-kp” {
key_name = “devops-kp”
public_key = tls_private_key.rsa-4096-example.public_key_openssh
key_type = “rsa”

tags = {
Name = “devops-kp”
}
}

output “algorithm” {
value = tls_private_key.rsa-4096-example.algorithm
}

output “key_type” {
value = aws_key_pair.devops-kp.key_type
}

Hi @sacsachin

Your local_file resource is the issue here. You have mentioned private_key_openssh, which prints it in Authorized key format.

Update it to PEM Encoded as follows:

content = tls_private_key.rsa-4096-example.private_key_pem

https://registry.terraform.io/providers/hashicorp/tls/latest/docs/resources/private_key

Still some issue

resource “tls_private_key” “rsa-4096-example” {
algorithm = “RSA”
}

resource “local_file” “foo” {
content = tls_private_key.rsa-4096-example.private_key_pem
filename = “/home/bob/id_rsa.pem”
}

resource “aws_key_pair” “devops-kp” {
key_name = “devops-kp”
public_key = tls_private_key.rsa-4096-example.public_key_openssh

tags = {
Name = “devops-kp”
}
}

output “algorithm” {
value = tls_private_key.rsa-4096-example.algorithm
}

output “key_type” {
value = aws_key_pair.devops-kp.key_type
}


Error: ‘devops-kp’ doesn’t exist or or its type is not ‘rsa’.

It’s not the same error as you share earlier. It now says ‘devops-kp’ doesn’t exist …:

Try this block:

resource "tls_private_key" "rsa_key"{
    algorithm = "RSA"
    rsa_bits = 4096
}

resource "aws_key_pair" "aws_key" {
  key_name   = "devops-kp"
  public_key = tls_private_key.rsa_key.public_key_openssh
}

resource "local_file" "key_local" {
  content  = tls_private_key.rsa_key.private_key_pem
  filename = "/home/bob/devops-kp.pem"
}

And it worked, thank you!
May be it’s worth mentioning in the exerciser that name the private key file to some exact name.

Hi @sacsachin ,

What is the task name and topic level?

Codeklod Engineer → Terrafrom → Level 1 → Create Key Pair Using Terraform

Thanks, Sachin. BTW, It’s KodeKloud, not CodeKloud. :innocent:

you are right :smile: my bad!

Hi @sacsachin

I just checked, and it’s working fine on my side. I think you might have used the wrong key_name value.

UPDATE:

The team considered this change and updated the task accordingly. Thanks for your feedback.

Regards,