--- - name: Install Docker on Production Server hosts: production become: yes gather_facts: yes tasks: - name: Install prerequisites ansible.builtin.apt: name: - ca-certificates - curl state: present update_cache: yes - name: Create keyrings directory ansible.builtin.file: path: /etc/apt/keyrings state: directory mode: '0755' - name: Detect distribution (Debian or Ubuntu) ansible.builtin.set_fact: docker_distribution: "{{ 'debian' if ansible_distribution == 'Debian' else 'ubuntu' }}" changed_when: false - name: Add Docker GPG key ansible.builtin.shell: cmd: | curl -fsSL https://download.docker.com/linux/{{ docker_distribution }}/gpg -o /etc/apt/keyrings/docker.asc chmod a+r /etc/apt/keyrings/docker.asc creates: /etc/apt/keyrings/docker.asc - name: Add Docker repository ansible.builtin.shell: cmd: | echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/{{ docker_distribution }} $(. /etc/os-release && echo "$VERSION_CODENAME") stable" | tee /etc/apt/sources.list.d/docker.list > /dev/null creates: /etc/apt/sources.list.d/docker.list - name: Update apt cache after adding Docker repo ansible.builtin.apt: update_cache: yes - name: Install Docker packages ansible.builtin.apt: name: - docker-ce - docker-ce-cli - containerd.io - docker-buildx-plugin - docker-compose-plugin state: present - name: Start and enable Docker service ansible.builtin.systemd: name: docker state: started enabled: yes - name: Add deploy user to docker group ansible.builtin.user: name: "{{ ansible_user | default('deploy') }}" groups: docker append: yes - name: Verify Docker installation ansible.builtin.command: docker --version register: docker_version changed_when: false - name: Display Docker version ansible.builtin.debug: msg: "Docker installed successfully: {{ docker_version.stdout }}" - name: Verify Docker Compose installation ansible.builtin.command: docker compose version register: compose_version changed_when: false - name: Display Docker Compose version ansible.builtin.debug: msg: "Docker Compose installed successfully: {{ compose_version.stdout }}" - name: Run Docker hello-world test ansible.builtin.command: docker run --rm hello-world register: docker_test changed_when: false - name: Display Docker test result ansible.builtin.debug: msg: "Docker is working correctly!" when: "'Hello from Docker!' in docker_test.stdout"