Home > database >  Terraform: EC2 instance is still creating after running shell script using provisioner
Terraform: EC2 instance is still creating after running shell script using provisioner

Time:01-14

I need some help from Terraform export. I'm going to create EC2 instance and install some packages on it using terraform. To install packages, I used the provisiner of terraform. This is a EC2 instance part.

resource "aws_instance" "lms_server" {
  ami = var.AMI
  instance_type = var.instance_type
  key_name = var.private_key
  iam_instance_profile = aws_iam_instance_profile.instance_profile.name
  associate_public_ip_address = true
    subnet_id = aws_subnet.main-public-1.id
    vpc_security_group_ids = [aws_security_group.security_rule.id]

  provisioner "file" {
    source      = "script.sh"
    destination = "/tmp/script.sh"
  }
  
  provisioner "remote-exec" {
    inline  = [
      "chmod  x /tmp/script.sh",
      "/tmp/script.sh ${var.gh_user} ${var.gh_token} ${var.gh_url} ${aws_db_instance.lms_mysql_db.address} ${var.db_name} ${var.db_username} ${var.db_password} ${aws_sqs_queue.lms_queue.id} ${var.sqs_name} ${self.public_ip} ${var.aws_region} ${var.bucket_name}",
    ]
  }
  
  connection {
    type        = "ssh"
    host        = "${self.public_ip}"
    user        = var.user_name
    private_key = "${file("lms_key.pem")}"
  }
  
  root_block_device {
      volume_size   =   var.volume_size
  }

  tags = {
    lms_app = "lms_server"
  }
}

As you can see here, I access the EC2 via SSH and copied script.sh file that includes all commands. Then run it. I think EC2 was created successfully and all packages were installed, but terraform CLI keeps ec2 instance: still creating status. This means that the creation of EC2 instance is not finished yet. so If I drop this(Ctrl C) and then run terraform apply again, it used to destroy and create instance from the first again. Also it's installing all packages again.

This operation is happening each time I update the terraform script for other, not EC2.

I'm looking forward to getting some help about this problem. Thank you for your time and consideration.

CodePudding user response:

Can you show us the scripts.sh content? Maybe there is something keep that script executing so that it can not finish.

You can try using user_data instead. It will run your script after the EC2 is created in the bootstrap phase and it is logged in the EC2.

https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/instance#user_data

  •  Tags:  
  • Related