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!
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
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.