0

I create a new user using ansible called nginx, nginx is part of the sudo group a, but when I try to do an apt install with this user I get the below error

: FAILED! => {"changed": false, "msg": "Failed to lock apt for exclusive operation"}

What is the cause of the error and how can it be fixed?

Below is my playbook, the playbook runs until it tries to run the task Install aptitude using apt

- name: Install Nginx Ubuntu
  hosts: web
  remote_user: "{{ NGINX_USER }}"
  become: yes
  become_method: sudo
  become_user: "{{ NGINX_USER }}"
  connection: ssh
  gather_facts: no
  vars:
    NGINX_VERSION: nginx-1.17.10
    NGINX_SBIN_PATH: /usr/sbin/
    NGINX_ERROR_LOG_PATH: /var/log/nginx/error.log
    NGINX_HTTP_LOG_PATH: /var/log/nginx/access.log
    NGINX_PID_PATH: /var/run/nginx.pid
  vars_files:
    - ../vars/global.yaml
  tasks:
    - name: Check if Nginx Exists
      stat: path=/etc/init.d/nginx
      register: nginx_status
      become: yes
    - name: Stop nginx Service
      service: name=nginx state=stopped
      when: nginx_status.stat.exists
      register: service_stopped
    - name: Make sure a systemd is not running
      systemd:
        state: stopped
        name: nginx
    - name: Install aptitude using apt
      apt:
        name: aptitude
        state: latest
        update_cache: yes
        force_apt_get: yes
    - name: Update apt repo
      apt:
        update_cache: yes
        cache_valid_time: 3600
    - name: Install required system packages
      apt: name={{ item }} state=latest update_cache=yes
      loop:
        [
          "build-essential",
          "libpcre3",
          "libpcre3-dev",
          "zlib1g",
          "zlib1g-dev",
          "libssl-dev",
        ]
George
  • 113
  • 1
  • 2
  • 7

2 Answers2

1

Not sure, but I think you are switching to same user.

  • Try to use become_user: root (if you can)
  • Check the group a got enough permission to install the package
  • and hope you run it multiple times; but just make sure no other user/program using the apt at the same time.

Give a try.

Gineesh
  • 181
  • 1
  • 1
  • 8
  • Check especially the last point. `Failed to lock apt for exclusive operation` indicates that there is already an apt operation running. If another process is hanging (maybe it waits for user input) you may have to kill it. – Gerald Schneider Apr 20 '20 at 06:16
  • @GeraldSchneider Won't `apt` fail with the same reason if you're not root, as it can't create the locking file? – vidarlo Nov 06 '21 at 17:10
0

If your machine has literally only just been installed, with unattended upgrades enabled, it could be doing the upgrades in the background and locking the apt packages in the process.

Try and leave the machines for 30 minutes or so before running Ansible against them.