Урок 2-3: Установка Ansible и первое подключение
Часть 1: Установка Ansible
Ubuntu / Debian
# Обновить репозитории
sudo apt update
# Способ 1: Через официальный репозиторий
sudo apt install ansible
# Способ 2: Через pip (более свежая версия)
sudo apt install python3-pip
pip3 install ansible
# Проверка установки
ansible --version
# Ожидаемый результат:
# ansible [core 2.15.0]
# config file = /etc/ansible/ansible.cfg
# python version = 3.11.2
CentOS / RHEL
# Способ 1: Через yum
sudo yum install -y epel-release
sudo yum install -y ansible
# Способ 2: Через pip
sudo yum install python3-pip
pip3 install ansible
# Проверка
ansible --version
Amazon Linux
# Amazon Linux использует похожий на CentOS пакетный менеджер
sudo yum install -y python3 python3-pip git
pip3 install ansible
# Проверка
ansible --version
macOS
# Через Homebrew
brew install ansible
# Через pip
pip3 install ansible
# Проверка
ansible --version
Windows (Для Control Server)
⚠️ Важно: Ansible Control Server (управляющий сервер) НЕ может быть Windows!
Решения для Windows: 1. Установить WSL 2 (Windows Subsystem for Linux 2) → установить Ubuntu → Ansible 2. Использовать виртуальную машину с Linux 3. Использовать Docker с Linux контейнером
Для управления Windows серверов из Linux:
# Установить pywinrm
pip3 install pywinrm
# Дальше можно управлять Windows серверами
Часть 2: Основная конфигурация
Файл ansible.cfg
Местоположение: /etc/ansible/ansible.cfg или ./ansible.cfg в проекте
Основные параметры:
[defaults]
# Путь к inventory файлу
inventory = /etc/ansible/hosts
# Пользователь для подключения
remote_user = ansible
# Использовать sudo без пароля
become = True
become_method = sudo
become_user = root
# SSH настройки
host_key_checking = False
timeout = 10
# Логирование
log_path = /var/log/ansible.log
# Параллельные потоки (по умолчанию 5)
forks = 10
# Папка где искать роли
roles_path = ./roles
SSH ключи
# Генерировать SSH ключ (если его еще нет)
ssh-keygen -t rsa -b 4096 -f ~/.ssh/id_rsa
# Копировать публичный ключ на управляемые серверы
ssh-copy-id -i ~/.ssh/id_rsa.pub ansible@192.168.1.10
ssh-copy-id -i ~/.ssh/id_rsa.pub ansible@192.168.1.11
# Или вручную добавить в ~/.ssh/authorized_keys на удаленном сервере
cat ~/.ssh/id_rsa.pub | ssh ansible@192.168.1.10 "cat >> ~/.ssh/authorized_keys"
# Проверить подключение
ssh ansible@192.168.1.10
Пользователь ansible
# На каждом управляемом сервере создать пользователя
sudo useradd -m -s /bin/bash ansible
# Добавить в sudoers
sudo usermod -aG sudo ansible
# Настроить sudo без пароля (опционально)
echo "ansible ALL=(ALL) NOPASSWD:ALL" | sudo tee /etc/sudoers.d/ansible
sudo chmod 0440 /etc/sudoers.d/ansible
Часть 3: Inventory (Список управляемых хостов)
Простой inventory
Файл: /etc/ansible/hosts или inventory.ini
# Группа веб-серверов
[webservers]
web1 ansible_host=192.168.1.10
web2 ansible_host=192.168.1.11
web3 ansible_host=192.168.1.12
# Группа database серверов
[databases]
db1 ansible_host=192.168.1.20
db2 ansible_host=192.168.1.21
# Все серверы
[all]
web1 ansible_host=192.168.1.10
web2 ansible_host=192.168.1.11
web3 ansible_host=192.168.1.12
db1 ansible_host=192.168.1.20
db2 ansible_host=192.168.1.21
Inventory с параметрами
[webservers]
web1 ansible_host=192.168.1.10 ansible_port=22 ansible_user=ansible
web2 ansible_host=192.168.1.11 ansible_port=22 ansible_user=root
[databases]
db1 ansible_host=db1.example.com ansible_user=dbadmin
[all:vars]
ansible_python_interpreter=/usr/bin/python3
YAML Inventory
Файл: inventory.yml
all:
hosts:
localhost:
ansible_connection: local
children:
webservers:
hosts:
web1:
ansible_host: 192.168.1.10
web2:
ansible_host: 192.168.1.11
web3:
ansible_host: 192.168.1.12
databases:
hosts:
db1:
ansible_host: 192.168.1.20
db2:
ansible_host: 192.168.1.21
all:
vars:
ansible_user: ansible
ansible_python_interpreter: /usr/bin/python3
Часть 4: Первое подключение
Проверка доступности хостов
# Проверить все хосты из inventory
ansible all -i inventory.ini -m ping
# Ожидаемый результат:
# web1 | SUCCESS => {
# "changed": false,
# "ping": "pong"
# }
# web2 | SUCCESS => {
# "changed": false,
# "ping": "pong"
# }
Проверка конкретной группы
# Только webservers
ansible webservers -i inventory.ini -m ping
# Только databases
ansible databases -i inventory.ini -m ping
# Один хост
ansible web1 -i inventory.ini -m ping
Получение информации о хостах
# Получить все facts (информация о системе)
ansible all -i inventory.ini -m setup
# Получить конкретный fact
ansible all -i inventory.ini -m setup -a "filter=ansible_os_family"
# Посмотреть только на одного хоста
ansible web1 -i inventory.ini -m setup
Основные команды проверки
# Посмотреть версию ОС
ansible all -i inventory.ini -m debug -a "msg={{ ansible_os_family }}"
# Посмотреть свободное место
ansible all -i inventory.ini -m shell -a "df -h"
# Посмотреть версию Python
ansible all -i inventory.ini -m shell -a "python3 --version"
# Проверить есть ли sudo доступ
ansible all -i inventory.ini -b -m shell -a "whoami"
Часть 5: Подключение к Windows
Требования на Windows сервере
# 1. Запустить PowerShell как администратор
# 2. Проверить версию PowerShell
$PSVersionTable.PSVersion
# 3. Разрешить выполнение скриптов
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
# 4. Включить WinRM
Enable-PSRemoting -Force
# 5. Создать и скопировать сертификат
$hostname = hostname
New-Item -Path WSMan:\localhost\Listener -Transport HTTPS -Address * -CertThumbprint (New-SelfSignedCertificate -CertstoreLocation cert:\LocalMachine\My -DnsName $hostname).Thumbprint -Force
# 6. Открыть порт 5985 в firewall
New-NetFirewallRule -Name "WinRM HTTP" -DisplayName "WinRM HTTP" -Enabled True -Profile Any -Action Allow -Direction Inbound -LocalPort 5985 -Protocol TCP
Inventory для Windows
[windows]
win1 ansible_host=192.168.1.30 ansible_user=Administrator ansible_password=YourPassword ansible_connection=winrm ansible_winrm_server_cert_validation=ignore
Тест подключения к Windows
# Установить pywinrm
pip3 install pywinrm
# Проверить подключение
ansible windows -i inventory.ini -m win_ping
Часть 6: Структура проекта Ansible
Рекомендуемая структура
ansible-project/
├── ansible.cfg # Конфигурация
├── inventory/ # Inventory файлы
│ ├── production.ini
│ ├── staging.ini
│ └── development.ini
├── playbooks/ # Playbooks
│ ├── site.yml
│ ├── deploy-web.yml
│ └── update-system.yml
├── roles/ # Роли
│ ├── webserver/
│ │ ├── tasks/
│ │ ├── handlers/
│ │ ├── templates/
│ │ └── files/
│ └── database/
├── files/ # Статические файлы
├── templates/ # Jinja2 шаблоны
├── group_vars/ # Переменные для групп
│ ├── webservers.yml
│ └── databases.yml
├── host_vars/ # Переменные для хостов
│ ├── web1.yml
│ └── db1.yml
└── README.md
Быстрый старт проекта
# Создать структуру
mkdir -p ansible-project/{inventory,playbooks,roles,group_vars,host_vars}
cd ansible-project
# Создать inventory
cat > inventory/hosts.ini << EOF
[webservers]
web1 ansible_host=192.168.1.10
[all:vars]
ansible_user=ansible
EOF
# Проверить
ansible all -i inventory/hosts.ini -m ping
Часть 7: Часто встречаемые ошибки
Ошибка 1: "Permission denied (publickey)"
Причина: SSH ключ не скопирован или неверный пользователь
Решение:
ssh-copy-id -i ~/.ssh/id_rsa.pub ansible@192.168.1.10
Ошибка 2: "Failed to import the required Python library"
Причина: Python не установлен на управляемом сервере
Решение:
sudo apt install python3
# или указать path к Python
ansible_python_interpreter=/usr/bin/python3
Ошибка 3: "Authentication or permission failure"
Причина: Пользователь не может выполнить sudo
Решение:
# Добавить в sudoers
echo "ansible ALL=(ALL) NOPASSWD:ALL" | sudo tee /etc/sudoers.d/ansible
Ошибка 4: "SSH port 22 refused"
Причина: Неверный порт или firewall блокирует
Решение:
ansible all -i inventory.ini -m ping -e ansible_port=2222
Проверочный список
- [ ] Ansible установлен и работает
- [ ] SSH ключи настроены
- [ ] Inventory файл создан
- [ ] Все хосты доступны через ping
- [ ] Получаете информацию о хостах через setup
- [ ] Структура проекта создана
- [ ] Готовы к первому playbook
Готовы? Переходите к Уроку 4 - Ad-Hoc команды! 🚀