Ssh_exchange_identification: read: Connection reset by peer

I have written Terraform code that creates an AWS EC2 instance and installs httpd web server in it. SSH keys are created through terraform code. When I do ‘terraform apply’, EC2 instance is created with httpd web server installed on it and I’m able to access contents of index.html using public IP of created EC2 instance. Problem I face is, SSH to created EC2 instance doesn’t work and throws error : ssh_exchange_identification: read: Connection reset by peer
Interesting point is, if I comment out ‘provisioner’ and ‘connection’ sections of code, I am able to SSH into the created EC2 instance. But, I want to be able to install software as well as SSH into instances. Please help.

Below is the code.

provider “aws” {
region = “us-east-1”
profile = “default”
}

variable “sgports” {
type = list(number)
description = “Enter ports to be allowed in Security Group”
}

variable “kname” {
description = “Enter Key name”
}

resource “tls_private_key” “keys” {
algorithm = “RSA”
}

resource “aws_key_pair” “ec2key” {
key_name = var.kname
public_key = tls_private_key.keys.public_key_openssh

}
resource “aws_security_group” “sgiac” {
name = “sgiacdynamic”

dynamic “ingress” {
for_each = var.sgports
content {
from_port = ingress.value
to_port = ingress.value
protocol = “tcp”
cidr_blocks = [“0.0.0.0/0”]
}

}

egress {
from_port = 0
to_port = 65535
protocol = “tcp”
cidr_blocks = [“0.0.0.0/0”]
}

}

resource “aws_instance” “ec2” {
instance_type = “t2.micro”
ami = “ami-09d95fab7fff3776c”
associate_public_ip_address = “true”
key_name = aws_key_pair.ec2key.key_name
vpc_security_group_ids = [aws_security_group.sgiac.id]

provisioner “remote-exec” {
inline = [
“sudo yum install -y httpd”,
“sudo systemctl start httpd”,
“sudo chmod 777 -R /var/”,
“echo $HOSTNAME >> /var/www/html/index.html”
]

connection {
type = “ssh”
user = “ec2-user”
private_key = tls_private_key.keys.private_key_pem
host = self.public_ip
}

}

}

output “sg” {
value = aws_security_group.sgiac.id
}

output “ec2” {
value = aws_instance.ec2.public_ip
}

output “ec2ENI” {
value = aws_instance.ec2.primary_network_interface_id
}

output “key” {
value = tls_private_key.keys.private_key_pem
}

output “public” {
value = tls_private_key.keys.public_key_openssh
}