Данная роль установит docker и docker-compose, если необходимо чтобы работало через прокси, то в плейбуке:
/etc/ansible/playbooks/roles_play/docker-doc-compose.yml
в переменной proxy: ставим или true или false
создаём структуру директорий:
mkdir -p /etc/ansible/{playbooks/roles_play,roles/docker_docker_compose/{defaults,handlers,meta,tasks,templates}}
В файле:
/etc/ansible/hosts
создаём группы по которым будет проходиться плейбук:
cat /etc/ansible/hosts
[test]
192.168.1.173
192.168.1.175
[test2]
192.168.1.171
192.168.1.172
[NOproxy]
localhost
127.0.0.1
192.168.1.171
192.168.1.172
192.168.1.173
192.168.1.175
Группа NOproxy нужна, если будет использоваться прокси сервер(а между собой докеры должны общаться не через прокси)
в директории:
/etc/ansible/roles/docker_docker_compose/tasks/
создаём:
cat /etc/ansible/roles/docker_docker_compose/tasks/add-repo-docker.yml
[codesyntax lang="bash"]
1 2 3 4 5 6 |
- name: Add Docker repo get_url: url: https://download.docker.com/linux/centos/docker-ce.repo dest: /etc/yum.repos.d/docer-ce.repo become: yes |
[/codesyntax]
cat /etc/ansible/roles/docker_docker_compose/tasks/docker-compose-preinstall.yml
[codesyntax lang="bash"]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
--- - name: purge docker-compose package yum: name: docker-compose state: removed - name: install pip yum: name: python-pip - name: install the package, force upgrade pip: name: pip executable: pip state: latest |
[/codesyntax]
cat /etc/ansible/roles/docker_docker_compose/tasks/docker-preinstall.yml
[codesyntax lang="bash"]
1 2 3 4 5 6 7 8 |
- name: default packages for docker yum: name: "{{item}}" state: present with_items: - yum-utils - device-mapper-persistent-data - lvm2 |
[/codesyntax]
cat /etc/ansible/roles/docker_docker_compose/tasks/install-docker-compose.yml
[codesyntax lang="bash" blockstate="collapsed"]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
- name: Check current docker-compose version. command: docker-compose --version register: docker_compose_current_version changed_when: false failed_when: false - name: Delete existing docker-compose version if it's different. file: path: "{{ docker_compose_path }}" state: absent when: > docker_compose_current_version.stdout is defined and docker_compose_version not in docker_compose_current_version.stdout - name: Install Docker Compose (if configured). get_url: url: https://github.com/docker/compose/releases/download/{{ docker_compose_version }}/docker-compose-Linux-x86_64 dest: "{{ docker_compose_path }}" mode: 0755 - name: install docker-compose stuff with pip pip: name: " {{ item }}" with_items: - pyyaml - docker-py # - docker-compose |
[/codesyntax]
cat /etc/ansible/roles/docker_docker_compose/tasks/install-docker.yml
[codesyntax lang="bash"]
1 2 3 4 5 6 7 8 |
- name: Install Docker package: name: docker-ce state: latest become: yes notify: - Restart docker |
[/codesyntax]
cat /etc/ansible/roles/docker_docker_compose/tasks/docker_proxy.yaml
[codesyntax lang="bash"]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
--- - name: create dir for .docker and service.d file: path: "{{item}}" state: directory mode: 0755 with_items: - /root/.docker/ - /etc/systemd/system/docker.service.d/ - name: copy template for proxy to /root/.docker/config.json template: src: /etc/ansible/roles/docker_docker_compose/templates/config.json dest: /root/.docker/config.json mode: 644 - name: copy template for proxy to /etc/systemd/system/docker.service.d/http-proxy.conf template: src: /etc/ansible/roles/docker_docker_compose/templates/http-proxy.conf dest: /etc/systemd/system/docker.service.d/http-proxy.conf mode: 644 notify: - Reload systemd - Reload docker |
[/codesyntax]
cat /etc/ansible/roles/docker_docker_compose/tasks/main.yml
[codesyntax lang="bash"]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
--- - import_tasks: add-repo-docker.yml tags: Add repo docker when: not proxy - import_tasks: proxy-add-repo-docker.yml tags: Add repo docker with proxy when: proxy - import_tasks: docker-preinstall.yml tags: install packpage fo docker when: not proxy - import_tasks: proxy-docker-preinstall.yml tags: install packpage fo docker when: proxy - import_tasks: install-docker.yml tags: install docker when: not proxy - import_tasks: proxy-install-docker.yml tags: install docker when: proxy - import_tasks: docker-compose-preinstall.yml tags: install packpage fo docker-compose when: not proxy - import_tasks: proxy-docker-compose-preinstall.yml tags: install packpage fo docker-compose when: proxy - import_tasks: install-docker-compose.yml tags: install docker-compose when: not proxy - import_tasks: proxy-install-docker-compose.yml tags: install docker-compose when: proxy - import_tasks: docker_proxy.yaml tags: use docker proxy when: proxy |
[/codesyntax]
cat /etc/ansible/roles/docker_docker_compose/tasks/proxy-add-repo-docker.yml
[codesyntax lang="php" blockstate="collapsed"]
1 2 3 4 5 6 7 8 9 |
- name: Add Docker repo through proxy "{{ http_proxy }}" get_url: url: https://download.docker.com/linux/centos/docker-ce.repo dest: /etc/yum.repos.d/docer-ce.repo environment: http_proxy: "{{ http_proxy }}" https_proxy: "{{ https_proxy }}" become: yes |
[/codesyntax]
cat /etc/ansible/roles/docker_docker_compose/tasks/proxy-docker-compose-preinstall.yml
[codesyntax lang="php" blockstate="collapsed"]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
--- - name: purge docker-compose package yum: name: docker-compose state: removed - name: install pip through proxy "{{ http_proxy }}" yum: name: python-pip environment: http_proxy: "{{ http_proxy }}" https_proxy: "{{ https_proxy }}" - name: install the package, force upgrade through proxy "{{ http_proxy }}" pip: name: pip executable: pip state: latest environment: http_proxy: "{{ http_proxy }}" https_proxy: "{{ https_proxy }}" |
[/codesyntax]
cat /etc/ansible/roles/docker_docker_compose/tasks/proxy-docker-preinstall.yml
[codesyntax lang="php" blockstate="collapsed"]
1 2 3 4 5 6 7 8 9 10 11 12 |
- name: default packages for docker through proxy "{{ http_proxy }}" yum: name: "{{item}}" state: present with_items: - yum-utils - device-mapper-persistent-data - lvm2 environment: http_proxy: "{{ http_proxy }}" https_proxy: "{{ https_proxy }}" |
[/codesyntax]
cat /etc/ansible/roles/docker_docker_compose/tasks/proxy-install-docker-compose.yml
[codesyntax lang="php" blockstate="collapsed"]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
- name: Check current docker-compose version. command: docker-compose --version register: docker_compose_current_version changed_when: false failed_when: false - name: Delete existing docker-compose version if it's different. file: path: "{{ docker_compose_path }}" state: absent when: > docker_compose_current_version.stdout is defined and docker_compose_version not in docker_compose_current_version.stdout - name: Install Docker Compose (if configured). through proxy "{{ http_proxy }}" get_url: url: https://github.com/docker/compose/releases/download/{{ docker_compose_version }}/docker-compose-Linux-x86_64 dest: "{{ docker_compose_path }}" mode: 0755 environment: http_proxy: "{{ http_proxy }}" https_proxy: "{{ https_proxy }}" - name: install docker-compose stuff with pip through proxy "{{ http_proxy }}" pip: name: " {{ item }}" with_items: - pyyaml - docker-py # - docker-compose environment: http_proxy: "{{ http_proxy }}" https_proxy: "{{ https_proxy }}" |
[/codesyntax]
cat /etc/ansible/roles/docker_docker_compose/tasks/proxy-install-docker.yml
[codesyntax lang="php" blockstate="collapsed"]
1 2 3 4 5 6 7 8 9 10 11 |
- name: Install Docker through proxy "{{ http_proxy }}" package: name: docker-ce state: latest become: yes notify: - Restart docker environment: http_proxy: "{{ http_proxy }}" https_proxy: "{{ https_proxy }}" |
[/codesyntax]
cat /etc/ansible/roles/docker_docker_compose/handlers/main.yml
[codesyntax lang="bash"]
1 2 3 4 5 6 7 8 9 10 |
--- - name: Reload systemd command: systemctl daemon-reload - name: Reload docker service: name=docker state=reloaded - name: Restart docker service: name=docker state=restarted enabled=yes |
[/codesyntax]
cat /etc/ansible/roles/docker_docker_compose/templates/config.json
[codesyntax lang="php" blockstate="collapsed"]
1 2 3 4 5 6 7 8 9 10 11 12 |
{ "proxies": { "default": { "httpProxy": "{{ http_proxy }}", "httpsProxy": "{{ http_proxy }}", "noProxy": "{{groups['NOproxy'] | to_yaml(width=1300)| replace('\n', '')}}" } } } |
[/codesyntax]
1 |
<span class="nv"><code class="docutils literal notranslate"><span class="pre">to_yaml</span></code>и <code class="docutils literal notranslate"><span class="pre">to_nice_yaml</span></code>фильтры используют библиотеку PyYAML, которая имеет ограничение длины строки в 80 символов по умолчанию. Это вызывает разрыв строки после 80-го символа (если после 80-го символа есть пробел). Чтобы избежать такого поведения и генерировать длинные строки, можно использовать <code class="docutils literal notranslate"><span class="pre">width</span></code>опцию </span> |
1 2 3 |
<span class="nv">Также при отработке данного действия, в конце устанавливается знак перевода строки, мы его убираем </span><span class="nv">с помощью: replace('\n', '') </span> |
cat /etc/ansible/roles/docker_docker_compose/templates/http-proxy.conf
[codesyntax lang="php" blockstate="collapsed"]
1 2 3 4 5 |
[Service] Environment="HTTP_PROXY={{ http_proxy }}" Environment="HTTPS_PROXY={{ https_proxy }}" Environment="NO_PROXY={{groups['NOproxy'] | to_yaml(width=1300)| replace('\n', '')}}" |
[/codesyntax]
cat /etc/ansible/playbooks/roles_play/docker-doc-compose.yml
[codesyntax lang="php"]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
--- - hosts: 192.168.1.112 become: true ignore_errors: yes become_method: sudo gather_facts: yes vars: - proxy: true # here use true/false - http_proxy: "http://192.168.1.170:3128" - https_proxy: "http://192.168.1.170:3128" - docker_package_state: latest - docker_install_compose: True - docker_compose_version: "1.22.0" - docker_compose_path: /usr/local/bin/docker-compose roles: - docker_docker_compose # tasks: # - include_role: # name: name1 |
[/codesyntax]
Запускаем плейбук без прокси, меняем в /etc/ansible/playbooks/roles_play/docker-doc-compose.yml переменную proxy на false
- proxy: false
ansible-playbook -u ansible /etc/ansible/playbooks/roles_play/docker-doc-compose.yml
Запускаем плейбук с прокси, меняем в /etc/ansible/playbooks/roles_play/docker-doc-compose.yml переменную proxy на true - proxy: true ansible-playbook -u ansible /etc/ansible/playbooks/roles_play/docker-doc-compose.yml
1 2 3 4 5 6 7 |
чтобы подключить данную роль к плейбуку на установку сервера, необходимо добавить таск с включением роли: tasks: - include_role: name: docker_docker_compose и переменные в var |
1 2 3 |
cat <strong>/etc/ansible/playbooks/roles_play/new_server.yml </strong>[codesyntax lang="bash"] |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
--- - hosts: 192.168.1.175 become: true ignore_errors: yes become_method: sudo gather_facts: yes vars: - proxy: true - proxyIP: "9.9.9.9:3128" roles: - new_server tasks: - include_role: name: docker_docker_compose |
1 |
[/codesyntax] |
1 |
====================== Чтобы произвести запись всех ip адресов из группы NOpoxy в файле /etc/ansible/hosts нужно использовать конструкцию: |
1 2 3 4 5 |
- name: check add ip debug: msg: "{{ item }}" with_items: - "{{ groups['NOproxy'] | to_yaml(width=1300)| replace('\n', '') }}" |
=================
Чтобы проверить корректно ли работает установка через прокси сервер, нам понадобится прокси сервер и на целевом сервере настроить iptables, вот скрипт для простоты
[codesyntax lang="bash"]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
#!/bin/bash ### Скрипт конфигурации IPTables ### # Очищаем предыдущие записи iptables -F # Установка политик по умолчанию iptables -P INPUT DROP iptables -P FORWARD ACCEPT iptables -P OUTPUT DROP # Разрешаем локальный интерфейс iptables -A INPUT -i lo -j ACCEPT # REL, ESTB allow iptables -A INPUT -p tcp -m state --state RELATED,ESTABLISHED -j ACCEPT iptables -A INPUT -p udp -m state --state RELATED,ESTABLISHED -j ACCEPT iptables -A OUTPUT -p tcp -m state --state RELATED,ESTABLISHED -j ACCEPT iptables -A OUTPUT -p udp -m state --state RELATED,ESTABLISHED -j ACCEPT # Разрешаем рабочие порты # 22 порт для всех iptables -A INPUT -p tcp --dport 22 -j ACCEPT # Ansible iptables -A INPUT -p tcp -s 192.168.1.177 --dport 22 -j ACCEPT # Прокси iptables -A OUTPUT -p tcp -d 192.168.1.170 --dport 3128 -j ACCEPT # DNS у нас гугловые iptables -A OUTPUT -d 8.8.8.8 -j ACCEPT # Просмотр iptables -L --line-number echo service iptables save echo service iptables reload echo "Done" |
[/codesyntax]
запускаем его и у нас на внешку доступ будет только через наш прокси.