Interview Prep/Real-World Interview/Write-an-Ansible-playbook tasks

Install Docker on Ubuntu with Ansible using the official repository.

IntermediateHands-onWrite-an-Ansible-playbook tasks
Answer
- hosts: docker_hosts
  become: true
  tasks:
    - name: Prereqs
      ansible.builtin.apt: { name: [ca-certificates, curl], state: present, update_cache: true }

    - name: Docker GPG key
      ansible.builtin.get_url:
        url: https://download.docker.com/linux/ubuntu/gpg
        dest: /etc/apt/keyrings/docker.asc
        mode: "0644"

    - name: Docker repo
      ansible.builtin.apt_repository:
        repo: "deb [arch=amd64 signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu {{ ansible_facts['distribution_release'] }} stable"
        state: present

    - name: Install Docker
      ansible.builtin.apt:
        name: [docker-ce, docker-ce-cli, containerd.io, docker-buildx-plugin, docker-compose-plugin]
        state: present
        update_cache: true

    - name: Let ubuntu user run docker
      ansible.builtin.user: { name: ubuntu, groups: docker, append: true }

Key trick → signed-by scopes the key to this one repo. apt-key is deprecated, so don't use it.

All Real-World Interview questions Roadmap: Interview readiness

More on Write-an-Ansible-playbook tasks