# Ansible

# Ansible Top Commands

**Запуск playbook с ключом**

```ruby
ansible-playbook -u <user> -i '<ip>,' --private-key ~/.ssh/<key> playbook.yml
```

**Отключение проверки Host-ов при запуске playbook**

```ruby
sudo sh -c 'echo "[defaults]\nhost_key_checking = False" >> /etc/ansible/ansible.cfg'
```

# Ansible HandBook

- **[Установка Ansible](https://docs.ansible.com/projects/ansible-core/devel/installation_guide/installation_distros.html#installing-ansible-on-ubuntu) <span style="color:rgb(22,145,121);">[+Pip](https://docs.ansible.com/projects/ansible/latest/installation_guide/intro_installation.html#pip-install)</span>**
- <span style="color:rgb(53,152,219);">**[Ansible CLI CheatSheet](https://docs.ansible.com/projects/ansible-core/devel/command_guide/cheatsheet.html)**</span>
- <span style="color:rgb(185,106,217);">**[Ansible Master Setup](https://wiki-docs.ru/books/ansible/page/ansible-masterclient-setup "Ansible Master Setup")**</span>
- <span style="color:rgb(53,152,219);">**<span style="color:rgb(132,63,161);">[Ansible-playbook CLI-flags](https://docs.ansible.com/projects/ansible-core/devel/cli/ansible-playbook.html)</span>**</span>
- <span style="color:rgb(53,152,219);">**<span style="color:rgb(132,63,161);">[Ansible Ad-hoc Commands](https://docs.ansible.com/projects/ansible/latest/command_guide/intro_adhoc.html)</span>**</span>
- [**Ansible Modules**](https://docs.ansible.com/projects/ansible-core/devel/collections/index_module.html#index-of-all-modules)

##### <span style="color:rgb(53,152,219);">Ansible Advanced Tools</span>

<table id="bkmrk-ansible-roles-%26-depe" style="border-collapse:collapse;width:56.3095%;height:533.453px;"><tbody><tr style="height:84.1719px;"><td style="width:45.4545%;padding:8px;vertical-align:top;height:84.1719px;">**Ansible Roles &amp; Dependencies**</td><td style="width:54.5455%;padding:8px;vertical-align:top;height:84.1719px;">**[Roles](https://docs.ansible.com/ansible/latest/user_guide/playbooks_reuse_roles.html)**

**[Role Dependencies](https://docs.ansible.com/ansible/latest/user_guide/playbooks_reuse_roles.html#role-dependencies)**

**[Ansible Galaxy](https://docs.ansible.com/projects/galaxy-ng/en/latest/community/userguide.html#ansible-core-cli-setup) [<span style="color:rgb(22,145,121);">+Collections</span>](https://galaxy.ansible.com/ui/collections/)**

</td></tr><tr style="height:61.7812px;"><td style="width:45.4545%;padding:8px;vertical-align:top;height:61.7812px;">**Security &amp; Code Quality**</td><td style="width:54.5455%;padding:8px;vertical-align:top;height:61.7812px;">**[Ansible Vault](https://docs.ansible.com/ansible/latest/user_guide/vault.html)**

**[Ansible Lint](https://docs.ansible.com/projects/lint/usage/)**

</td></tr><tr style="height:61.7812px;"><td style="width:45.4545%;padding:8px;vertical-align:top;height:61.7812px;">**Data &amp; Environment**</td><td style="width:54.5455%;padding:8px;vertical-align:top;height:61.7812px;">**[Ansible Facts](https://docs.ansible.com/projects/ansible-core/devel/playbook_guide/playbooks_vars_facts.html)**

**[Get host ENV vars](https://docs.ansible.com/ansible/latest/reference_appendices/faq.html#how-do-i-access-shell-environment-variables)**

</td></tr><tr style="height:61.7812px;"><td style="width:45.4545%;padding:8px;vertical-align:top;height:61.7812px;">**Modules &amp; Templating**</td><td style="width:54.5455%;padding:8px;vertical-align:top;height:61.7812px;">**[Ansible Expect](https://docs.ansible.com/projects/ansible-core/devel/collections/ansible/builtin/expect_module.html#examples)**

**[Jinja2 templates](https://docs.ansible.com/projects/ansible-core/2.15/playbook_guide/playbooks_templating.html)**

</td></tr><tr style="height:84.1719px;"><td style="width:45.4545%;padding:8px;vertical-align:top;height:84.1719px;">**Integrations &amp;  
Dynamic Inventory**</td><td style="width:54.5455%;padding:8px;vertical-align:top;height:84.1719px;">**[AWS Dynamic Inventory](https://docs.ansible.com/ansible/latest/user_guide/intro_dynamic_inventory.html#inventory-script-example-aws-ec2)**

**[Linux Storage Role](https://linux-system-roles.github.io/storage/)**

**[Handlers](https://docs.ansible.com/projects/ansible-core/devel/playbook_guide/playbooks_handlers.html#handler-example)**

</td></tr><tr style="height:78.5781px;"><td style="width:45.4545%;padding:8px;vertical-align:top;height:78.5781px;">**<span>Loops and Conditionals</span>**</td><td style="width:54.5455%;padding:8px;vertical-align:top;height:78.5781px;">[**loop**](https://docs.ansible.com/projects/ansible/latest/playbook_guide/playbooks_conditionals.html#loops-and-conditionals)  
[**with\_items**](https://docs.ansible.com/projects/ansible-core/devel/collections/ansible/builtin/items_lookup.html#examples)  
[**with\_fileglob**](https://docs.ansible.com/projects/ansible-core/devel/collections/ansible/builtin/fileglob_lookup.html#examples)

</td></tr><tr style="height:50.5938px;"><td style="width:45.4545%;padding:8px;vertical-align:top;height:50.5938px;">**<span>Task Delegation &amp; Scope</span>**</td><td style="width:54.5455%;padding:8px;vertical-align:top;height:50.5938px;">[**delegate\_to**](https://docs.ansible.com/projects/ansible-core/devel/playbook_guide/playbooks_delegation.html#delegating-tasks)

[**run\_once**](https://docs.ansible.com/projects/ansible-core/devel/playbook_guide/playbooks_delegation.html#delegation-and-parallel-execution)

</td></tr><tr style="height:50.5938px;"><td style="width:45.4545%;padding:8px;vertical-align:top;height:50.5938px;">**<span>Error Handling</span>**</td><td style="width:54.5455%;padding:8px;vertical-align:top;height:50.5938px;">**[ignore\_errors](https://docs.ansible.com/projects/ansible-core/devel/playbook_guide/playbooks_error_handling.html#ignoring-failed-commands)  
[failed\_when](https://docs.ansible.com/projects/ansible-core/devel/playbook_guide/playbooks_error_handling.html#defining-failure)** </td></tr></tbody></table>

# Ansible Master/Client Setup

##### <span style="color:rgb(53,152,219);">Настройка ansible.cfg </span>

**Отключаем проверку ключей хостов и задаём базовые параметры:**

```ruby
sudo tee /etc/ansible/ansible.cfg > /dev/null <<EOF
[defaults]
host_key_checking = False
inventory = /etc/ansible/hosts
forks = 10
timeout = 30
EOF
```

<p class="callout info">Вместо глобального файла можно использовать локальный ./ansible.cfg в каталоге проекта  
или переменную окружения ANSIBLE\_HOST\_KEY\_CHECKING=False.</p>

##### <span style="color:rgb(53,152,219);">Настройка inventory</span>

<span style="color:rgb(22,145,121);">[**+Manual**](https://docs.ansible.com/projects/ansible/latest/inventory_guide/intro_inventory.html#assigning-a-variable-to-one-machine-host-variables)</span>

**Linux-серверы (SSH, ключи)**

```ruby
sudo tee -a /etc/ansible/hosts > /dev/null <<EOF
[unix_servers]
Ubuntu1 ansible_host=192.168.1.10 ansible_user=ubuntu ansible_ssh_private_key_file=/home/ec2-user/.ssh/aws.note_private.pem
CentOS1 ansible_host=192.168.1.11 ansible_user=centos ansible_ssh_private_key_file=/home/ec2-user/.ssh/aws.note_private.pem
EOF
```

**Windows-серверы (WinRM, HTTPS)**

```ruby
sudo tee -a /etc/ansible/hosts > /dev/null <<EOF
[win_servers]
WinSrv2012R2 ansible_host=192.168.1.20
WinSrv2016  ansible_host=192.168.1.21

[win_servers:vars]
ansible_user = Administrator
ansible_password = YourStrongPassword
ansible_port = 5986
ansible_connection = winrm
ansible_winrm_server_cert_validation = ignore
ansible_winrm_transport = ntlm   # или kerberos для домена
EOF
```

<p class="callout warning">Используйте групповые переменные в отдельном файле group\_vars/win\_servers.yml  
с шифрованием (ansible-vault), а не храните пароли открыто в hosts.</p>

**Установка пакета pywinrm**

```ruby
pip3 install "pywinrm>=0.3.0"
```

##### <span style="color:rgb(53,152,219);">Настройка Ansible Clients</span>

**Требования к Linux клиенту:**

- Учётная запись с правами на выполнение команд (желательно с `sudo` без пароля).
- Открытый SSH-порт 22.
- SSH-ключ добавлен в `~/.ssh/authorized_keys`.

**Требования к Windows клиенту:**

- Учётная запись администратора.
- PowerShell 3.0 или выше.
- WinRM-порт 5986 (HTTPS) открыт в брандмауэре.

**Настройка WinRM на Windows-клиенте:** <span style="color:rgb(22,145,121);">[**+Manual**](https://docs.ansible.com/projects/ansible/latest/os_guide/windows_winrm.html#winrm-setup)</span>

```ruby
# Автоматический способ (рекомендуется для тестов)
Invoke-Expression (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/ansible/ansible/devel/examples/scripts/ConfigureRemotingForAnsible.ps1')
```

##### <span style="color:rgb(53,152,219);">Проверка подключения</span>

**Linux:**

```ruby
ansible unix_servers -m ping
```

**Windows:**

```ruby
ansible win_servers -m win_ping
```