使用Ubuntu 18.04系统,使用Ansible安装Docker和docker-compose
由于业务需要,我开始使用 Ansible,并且正在用 Ansible 配置我的私人 Ubuntu 机器。我只是按照官方网站上的步骤,重新编写成符合 Ansible 的方式,结果安装成功了?。
请参考以下链接:
1. Docker在Ubuntu上安装指南:https://docs.docker.com/install/linux/docker-ce/ubuntu/
2. Docker Compose安装指南:https://docs.docker.com/compose/install/
3. Docker安装脚本(GitHub Gist):https://gist.github.com/rbq/886587980894e98b23d0eee2a1d84933
前提 tí)
-
- Ansible Roles を使用
-
- sudo のパスワードは別途指定が必要
- Docker/docker-compose のバージョンを固定したい場合はそれぞれ追加の指定が必要
完成品
---
- name: Add docker GPG key
apt_key:
url: https://download.docker.com/linux/ubuntu/gpg
become: yes
- name: Install basic list of packages
apt:
name: "{{ packages }}"
state: present
update_cache: yes
vars:
packages:
- apt-transport-https
- ca-certificates
- curl
- gnupg-agent
- software-properties-common
become: yes
- name: Add apt repository
apt_repository:
repo: "deb [arch=amd64] https://download.docker.com/linux/ubuntu {{ ansible_distribution_release }} stable"
become: yes
- name: Install Docker packages
apt:
name: "{{ packages }}"
state: present
vars:
packages:
- docker-ce
- docker-ce-cli
- containerd.io
become: yes
- name: Add user to docker group
user:
name: "{{ ansible_env.USER }}"
groups: docker
append: yes
become: yes
- name: Ensure docker service is enabled
systemd:
name: docker
state: started
enabled: yes
become: yes
- name: Install docker-compose
get_url:
url: "https://github.com/docker/compose/releases/download/1.24.0/docker-compose-{{ ansible_system }}-{{ ansible_architecture }}"
dest: /usr/local/bin/docker-compose
mode: +x
become: yes
一个解释
GPG 密钥
$ curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
在公式中,上述的命令可以通过apt-key模块的参数来指定URL,从而简化。
- name: Add docker GPG key
apt_key:
url: https://download.docker.com/linux/ubuntu/gpg
become: yes
Docker 使用仓库。
$ sudo add-apt-repository \
"deb [arch=amd64] https://download.docker.com/linux/ubuntu \
$(lsb_release -cs) \
stable"
lsb_release -cs 命令可以获取到 Ubuntu 的发行版本,如 bionic 或 xenial。但在 Ansible 中,如果启用了 gather_facts,则可以使用 ansible_distribution_release 来获取该信息。
- name: Add apt repository
apt_repository:
repo: "deb [arch=amd64] https://download.docker.com/linux/ubuntu {{ ansible_distribution_release }} stable"
become: yes
docker-compose 用于定义和运行多个 Docker 容器的工具。
$ sudo curl -L "https://github.com/docker/compose/releases/download/1.24.1/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
$ sudo chmod +x /usr/local/bin/docker-compose
由于公式是 curl,因此我们使用 get_url 模块。
uname -s/uname -m 分别通过 ansible_system/ansible_architecture 进行获取。
此外,我们还可以同时指定下载目录的权限,因此可以在一次任务中完成。
- name: Install docker-compose
get_url:
url: "https://github.com/docker/compose/releases/download/1.24.0/docker-compose-{{ ansible_system }}-{{ ansible_architecture }}"
dest: /usr/local/bin/docker-compose
mode: +x
become: yes