Ansible
Содержание
Об Ansible
Ansible — система управления конфигурациями, написанная на Python, с использованием декларативного языка разметки для описания конфигураций. Используется для автоматизации настройки и развертывания программного обеспечения. Обычно используется для управления Linux-узлами, но Windows также поддерживается. Поддерживает работу с сетевыми устройствами, на которых установлен Python версии 2.4 и выше по SSH или WinRM соединению.
Подготовка сервера
1. Устанавливаем ansible:
apt-get install ansible
2. Прописываем управляемые компьютеры в группу (local). В файл /etc/ansible/hosts требуется добавить (а в новых версиях Ansible желательно указать пользователя, под которым будет запущены команды на управляемых узлах (root)):
[all:vars]
ansible_user=ansible_user=root
[local]
10.10.3.77
3. Так как управление будет осуществляться через ssh по ключам, создаём ключ SSH:
ssh-keygen -t ed25519 -f ~/.ssh/manager
Пароль ключа можно оставить пустым.
4. Добавить ключ на сервере:
eval `ssh-agent`
ssh-add ~/.ssh/manager
5. Создадим каталог для пакетов рецептов (playbooks):
mkdir -p /etc/ansible/playbooks
Подготовка клиента
1. Устанавливаем необходимые компоненты:
apt-get install openssh-server python3
2. Включаем и запускаем службу sshd:
для SystemV:
chkconfig sshd on
service sshd start
для SystemD:
systemctl enable sshd.service
systemctl start sshd.service
3. Размещаем публичную часть созданного на сервере ключа пользователю root (в модуле Администратор или вручную добавить содержимое файла manager.pub в /etc/openssh/authorized_keys/root.
4. Проверим доступ по ключу с сервера:
ssh root@10.10.3.77
Проверка доступности
Используем модуль «ping»:
# ansibleansible -m pingping local
10.10.3.77 | SUCCESS => {
"changed": false,false,
"failed": false,false,
"ping": "pong"
}
Полезные рецепты
Рецепты применяются командой:
ansible-playbook <имя файла>
Прописывание репозитория
Файл: /etc/ansible/playbooks/repo.yml
- hosts:hosts: local
remote_user: remote_user:root
roottasks:
- tasks:name:
- name: Remove all repositories
shell: shell: apt-repo rm all
- -name: name: Add official mirror
shell: shell: apt-repo add http://10.10.3.77/repo/p8
- -name: name: Add official mirror with arepo
shell: shell: apt-repo add 'rpm http://10.10.3.77/repo/p8 x86_64-i586 classic'
- -name: name: Add extra repository
shell: shell: apt-repo add 'rpm http://10.10.3.77/repo/extra x86_64 extra'
Установка пакета
Файл: /etc/ansible/playbooks/install-ifcplugin.yml
- hosts:hosts: local
remote_user: remote_user:root
roottasks:
- tasks:name: - name: Update cache and install ifcplugin
apt_rpm:
apt_rpm:name: ifcplugin
name:state: ifcpluginpresent
update_cache: state: present
update_cache: yes
Обновление системы
С версии ansible-2.9.27-alt2 и ansible-core-2.14.2-alt1:
- hosts:hosts: local
remote_user: remote_user:root
rootgather_facts: no
gather_facts:tasks:
no- name: tasks:
- name: Update cache
apt_rpm:
apt_rpm:update_cache: true
update_cache:- truename: - name: Upgrade system
apt_rpm:
apt_rpm:dist_upgrade: true
dist_upgrade:- truename: - name: Upgrade kernel
apt_rpm:
apt_rpm:update_kernel: true
update_kernel:- truename: - name: Clean package cache
apt_rpm:
apt_rpm:clean: clean: true
Или всё в одном:
- hosts:hosts: local
remote_user: remote_user:root
rootgather_facts: no
gather_facts:tasks:
no- name: tasks:
- name: Upgrade system
apt_rpm:
apt_rpm:update_cache: true
update_cache:dist_upgrade: true
update_kernel: dist_upgrade:true
clean: true
update_kernel: true
clean: true
Сбор информации об управляемых узлах для инвентаризации и мониторинга
Файл: /etc/ansible/playbooks/system_inventory.yml
- name:name: System Inventory Collection
hosts: hosts:all
allgather_facts: yes
gather_facts:tasks:
yes- name: tasks:
- name: Create inventory directory
file:
file:path: path: "/etc/ansible/inventory/{{ inventory_hostname }}"
state: state:directory
directorymode: mode: '0755'
delegate_to: delegate_to:localhost
localhostrun_once: true
run_once:- truename: - name: Collect system information
copy:
copy:dest: dest: "/etc/ansible/inventory/{{ inventory_hostname }}/system_info.txt"
content: content:|
|
OS Family: {{ ansible_os_family }}
Distribution: {{ ansible_distribution }} {{ ansible_distribution_version }}
Architecture: {{ ansible_architecture }}
Kernel: {{ ansible_kernel }}
CPU Cores: {{ ansible_processor_cores }} ({{ ansible_processor_vcpus }} vCPUs)
CPU Model: {{ ansible_processor[2] if ansible_processor[2] is defined else 'N/A' }}
RAM Total: {{ (ansible_memtotal_mb / 1024) | round(2) }} GB
RAM Free: {{ (ansible_memfree_mb / 1024) | round(2) }} GB
Swap Total: {{ (ansible_swaptotal_mb / 1024) | round(2) }} GB
{% for interface in ansible_interfaces %}
{{ interface }}:
IPv4: {{ hostvars[inventory_hostname]['ansible_' + interface].get('ipv4', {}).get('address', 'N/A') }}
MAC: {{ hostvars[inventory_hostname]['ansible_' + interface].get('macaddress', 'N/A') }}
{% endfor %}
Current User: {{ ansible_user_id }}
User ID: {{ ansible_user_uid }}
User Home: {{ ansible_user_dir }}
Collected by: {{ ansible_user_id }}
Collection time: {{ ansible_date_time.iso8601 }}
delegate_to: delegate_to: localhost
Ссылки