AWS (aws_key_pair): unable to connect to VM using created key pair

Hello,
I’m using the following code to create a keypair and then use the private key to connect to the EC2.
Attempts to connect with the private key fail with an authentication failed message. At the same time, when I use a previously (manually) created key pair in aws, I can connect to ec2.

What am I missing?
code :

resource "aws_key_pair" "Test_key" {

  provider = aws.destination
  key_name   = "Test_Key"
  public_key = file("Test_Key.pub")
}

module "vm" {
  providers = {
    aws.destination = aws.destination
  }
  source        = "../modules/AWS/comp/ec2"
  key_name   = aws_key_pair.Test_key.key_name
...

in the module:

resource "aws_instance" "this" {
  provider               = aws.destination
  key_name               = var.key_name
 ....
}

this code works:


data "aws_key_pair" "ExistingKey" {
  key_name           = "XXXX"
  include_public_key = true
}

module "vm" {
  providers = {
    aws.destination = aws.destination
  }
  source        = "../modules/AWS/comp/ec2"
 
  key_name   = data.aws_key_pair.ExistingKey.key_name
#  key_name   = aws_key_pair.vm_key.key_name
...
}

Thank you.