Bobby R
Bobby R

Reputation: 91

Ansible apt Task: Failed to Lock apt for Exclusive Operation

I have written an Ansible playbook that includes running apt-get dist-upgrade. I made sure to have become: true and become_user: root at the top of the playbook in order to get sudo access to run the upgrade. This works fine locally on my Vagrant VMs, but when running on our production systems (Ubuntu 16.04) we get the following error:

Failed to lock apt for exclusive operation

Our current workaround is to SSH into the machine and then manually run sudo apt-get dist-upgrade. Then exit the SSH session and run the ansible playbook again and it works.

Other tasks in our playbook require sudo access and work fine. It is just the apt command that fails. We have tried rebooting the machines and replacing become: true and become_user: root with sudo: yes to no avail.

Any ideas on how to solve this problem? I'll include the pertinent parts of our playbook below.

- become: true
  become_user: root
  name: Setup the mongo database servers
  hosts: sgmongo-{{ customer }}-ciadmin
  tasks:
    -
      name: Ensure OS is upgraded with all patches
      apt: upgrade=dist update_cache=yes

Upvotes: 3

Views: 6649

Answers (2)

TJ Zimmerman
TJ Zimmerman

Reputation: 3484

I do it by calling a shell script with Ansible like so:

- script: ./files/bash_scripts/monitor_automatic_updates_status.sh

The script in question that Ansible calls is here:

#!/bin/bash  
#Debian automatically checks for updates on first boot. This ensures that has completed before continuing.
#If it hasn't finished in 10 minutes, the script will exit ungracefully.
timeout=$(($(date +%s) + 600))

while pgrep apt > /dev/null; do

    time=$(date +%s)

    if [[ $time -ge $timeout ]];
    then
        exit 1
    fi

    sleep 1
done;
exit 0

It just continually checks if apt is running on the system or not. And, when it finally finishes running, allows Ansible to continue.

Upvotes: 4

wxrdaniel
wxrdaniel

Reputation: 25

It seems like you have interrupted the apt command. Try to delete the apt lock file under /var/lib/apt by running:

sudo rm /var/lib/apt/lists/lock sudo rm /var/cache/apt/archives/lock sudo rm /var/lib/dpkg/lock

Upvotes: -1

Related Questions