Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terraform fails remote-exec (aws/ec2)

When trying to execute a shell script throw provisioner "remote-exec" in terraform connection not establish

I'm using ami for ubuntu-xenial-16.04 so the user is ubuntu

This is the last code that I use to execute the shell script:

resource "aws_instance" "secondary_zone" {
  count = 1
  instance_type = "${var.ec2_instance_type}"
  ami           = "${data.aws_ami.latest-ubuntu.id}"
  key_name = "${aws_key_pair.deployer.key_name}"
  subnet_id = "${aws_subnet.secondary.id}"
  vpc_security_group_ids =  ["${aws_security_group.server.id}"]
  associate_public_ip_address = true

  provisioner "remote-exec" {
    inline = ["${template_file.script.rendered}"]
  }

  connection {
    type        = "ssh"
    user        = "ubuntu"
    private_key = "${file("~/.ssh/id_rsa")}"
  }
}

This is what get in console:

aws_instance.secondary_zone (remote-exec): Connecting to remote host via SSH...
aws_instance.secondary_zone (remote-exec):   Host: x.x.x.x
aws_instance.secondary_zone (remote-exec):   User: ubuntu
aws_instance.secondary_zone (remote-exec):   Password: false
aws_instance.secondary_zone (remote-exec):   Private key: true
aws_instance.secondary_zone (remote-exec):   SSH Agent: false
aws_instance.secondary_zone (remote-exec):   Checking Host Key: false

Thank you for your help...

like image 688
AvZi Avatar asked Apr 27 '19 08:04

AvZi


1 Answers

I had the same issue. In your connection block try specifying the host.

  connection {
    type        = "ssh"
    user        = "ubuntu"
    private_key = "${file("~/.ssh/id_rsa")}"
    host        = self.public_ip
  }

I also had to create a route & gateway and associate them to my vpc. I'm still learning terraform, but this worked for me.

resource "aws_internet_gateway" "test-env-gw" {
  vpc_id = aws_vpc.test-env.id
}

resource "aws_route_table" "route-table-test-env" {
  vpc_id = aws_vpc.test-env.id
  route {
    cidr_block = "0.0.0.0/0"
    gateway_id = aws_internet_gateway.test-env-gw.id
  }
}

resource "aws_route_table_association" "subnet-association" {
  subnet_id      = aws_subnet.us-east-2a-public.id
  route_table_id = aws_route_table.route-table-test-env.id
}
like image 97
Charlie Avatar answered Nov 06 '22 02:11

Charlie