Report this

What is the reason for this report?

Processes locked on newly created droplet (terraform)

Posted on January 20, 2025

Hey guys im using terraform to create some resources in my script i have setup a couple scripts to auto run once the droplets been created but it seems when i try to do any that are apt related i get the error saying its locked out

Error Could not get lock /var/lib/dpkg/lock-frontend. It is held by process 1348 (apt-get)

Terraform Script

resource "digitalocean_droplet" "Test-Server" {
  image = "docker-20-04"
  name = "Test-Server"
  region = "ams3"
  size = "s-1vcpu-2gb"
  ssh_keys = [
    data.digitalocean_ssh_key.terraform.id
  ]

  connection {
    host = self.ipv4_address
    user = "root"
    type = "ssh"
    private_key = file(var.pvt_key)
    timeout = "2m"
  }

  provisioner "remote-exec" {
    inline = [
      "sudo ufw allow 25565",
      "sudo apt-get install -y s3cmd s3fs curl",
      "do more...."
    ]
  }
}

I am using the docker image ISO on the droplet

any thoughts on how to fix this?

thanks!



This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Hey there! 👋

I’ve seen this in the past, this issue happens because apt-get is already running on the Droplet shortly after it’s created, because of the automatic updates running in the background right after the server creation. As the apt-get command locks the process, your Terraform provisioner script can’t acquire the lock and fails.

To fix this you can add a small wait loop to ensure that apt-get has finished its tasks before your Terraform provisioner commands run, eg:

provisioner "remote-exec" {
  inline = [
    # Wait for any apt-related processes to finish
    "while sudo lsof /var/lib/dpkg/lock-frontend; do echo 'Waiting for apt to finish...'; sleep 5; done",

    # Update package lists and install the desired packages
    "sudo apt-get update -y",
    "sudo apt-get install -y s3cmd s3fs curl",
    "sudo ufw allow 25565",

    # Your additional commands
    "do more...."
  ]
}

The while loop checks if the lock file (/var/lib/dpkg/lock-frontend) is in use by another process (like apt-get). If so, it waits for 5 seconds and checks again, ensuring that no conflicts occur.

Another option is to disable the automated updates, but I would not recommend this for security reasons.

Let me know if this resolves your issue! 😊

- Bobby

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.