в ansible, debian, ubuntu

Знакомство с Ansible. Часть1: введение

ansible
Ansible – одна из систем управления конфигурациями (автоматизации настройки и развертывания серверов).

Особенность Ansible – наличие управляющего сервера, с которого отправляются команды или наборы инструкций (playbooks) на удаленные хосты посредством протокола SSH.

Ansible успешно решает следующие задачи:

  • правильная и быстрая настройка серверов до нужной конфигурации;
  • управление развертыванием облачных серверов (через API, с помощью Docker);
  • установка и обновление приложений;
  • координация звеньев инфраструктуры для выполнения развертываний;
  • централизованный сбор логов.

Ansible не требует установки на удаленные хосты клиентских приложений, так как подключается к ним по протоколу SSH — это и есть главное отличие от других инструментов управления конфигурациями.

Чтобы «пощупать» Ansible потребуется один управляющий сервер и несколько хостов для настройки. На управляющем сервере у нас установлена операционная система Debian Wheezy, на удаленных хостах — Ubuntu 14.04.

Установка Ansible не должна вызывать трудностей:

  • перед установкой обновим имеющиеся в системе пакеты:
apt-get update && apt-get upgrade
  • непосредственно установка Ansible:
echo 'deb http://http.debian.net/debian wheezy-backports main' > /etc/apt/sources.list.d/backports.list
apt-get update
apt-get -t wheezy-backports install "ansible"

Для настройки Ansible используется файл конфигурации ansible.cfg, который может находиться в таких местах:

  • ./ansible.cfg – в текущем каталоге;
  • ~/.ansible.cfg — в домашнем каталоге;
  • /etc/ansible/ansible.cfg — в каталоге, созданном при установке через менеджер пакетов (наш случай).

Примечание. Некоторые параметры или даже всю конфигурацию также можно переопределить в playbook или переменных окружения.

Параметров настройки Ansible довольно много, вот некоторые из наиболее часто используемых:

  • hostfile: — путь к inventory file, содержит список ip-адресов (или имен) хостов для подключения;
  • library: — путь к модулям Ansible;
  • forks: — кол-во потоков, которые может создать Ansible;
  • sudo_user: — пользователь, от которого запускаются команды/инструкции на удаленных хостах;
  • remote_port: — порт для подключения по протоколу SSH;
  • host_key_checking: — включить/отключить проверку SSH–ключа на удаленном хосте;
  • timeout: — таймаут подключения по SSH;
  • log_path: — путь к файлу логов.

Перечислим имена удаленных хостов, с которыми будем проводить эксперименты в файле /etc/ansible/hosts. Для этого:

  • переходим в каталог /etc/ansible:
cd /etc/ansible
  • переименуем существующий файл hosts:
mv hosts hosts.orig
  • и создадим новый файл hosts:
touch hosts

Содержимое файла будет следующим:

[test]
test-1
test-2

Также нужно сгенерировать на управляющем сервере ключ для доступа к удаленным хостам по SSH, для этого используем утилиту ssh-keygen. Копируем публичный ключ на удаленные хосты утилитой ssh-copy-id.

Для проверки правильности настройки Ansible делаем следующее:

  • пингуем удаленные хосты:
ansible test -m ping
test-1 | success >> {
    "changed": false, 
    "ping": "pong"
}

test-2 | success >> {
    "changed": false, 
    "ping": "pong"
}
  • просмотрим информацию об использовании оперативной памяти на удаленных хостах:
ansible test -a "free -h"
test-1 | success | rc=0 >>
             total       used       free     shared    buffers     cached
Mem:          7.6G       6.4G       1.2G       471M        64M       1.2G
-/+ buffers/cache:       5.2G       2.4G
Swap:         4.0G       616M       3.4G

test-2 | success | rc=0 >>
             total       used       free     shared    buffers     cached
Mem:          3.9G       3.3G       573M       333M       4.8M       442M
-/+ buffers/cache:       2.9G       1.0G
Swap:         4.0G       1.7G       2.3G

Работа с наборами инструкций (playbooks) — главная задача Ansible. Наборы инструкций содержат задачи и должны быть описаны в формате YAML. Задача использует часть кода-модуля, который может быть написан на любом языке программирования (но есть одно важное требование — сообщения от модулей должны быть в формате JSON).

Несколько слов о правилах написания YAML-файлов:

  • все YAML-файлы должны начинаться с ---. Эта часть формата YAML означает начало документа;
  • члены списка должны начинаться с пробела или - и иметь одинаковые отступы от начала строки;
  • комментарии начинаются с символа #;
  • словарь описывается в виде ключ: значение и может быть представлен в сокращенной форме.

В playbook может находиться список удаленных хостов, переменных пользователя, задач, обработчиков (как уже упоминалось ранее, здесь можно переопределять параметры конфигурации). Каждый набор инструкций (за исключением ролей) обязательно должен иметь поле hosts:. Кроме этого, набор инструкций содержит задачи — список действий, которые нужно выполнить на удаленных хостах.

Давайте разберемся с синтаксисом конкретного набора инструкций на примере установки web-сервера nginx:

  • создаем каталог, для хранения наших playbooks:
mkdir /etc/ansible/playbooks
  • в каталоге /etc/ansible/playbooks создаем файл install_nginx.yml:
touch /etc/ansible/playbooks/install_nginx.yml

Содержимое файла следующее:

---
- hosts: test
  tasks:

  - name: Install package nginx
    apt: name=nginx update_cache=yes
    sudo: yes

  - name: Starting service nginx
    service: name=nginx state=started
    sudo: yes

В данном примере поле hosts: содержит группу, на которой будет запущена задача (test).

Узнать, на каких хостах будет происходить работа, можно командой:

ansible-playbook <имя_набора_инструкций> --list-host

Поле tasks: содержит имена задач (Install package nginx и Starting service nginx), имена модулей, которые должны выполняться (apt и service) и аргументы, необходимые для выполнения модуля (для первого это name=nginx update_cache=yes, для второго — name=nginx state=started).
Дополнительно указано, что для выполнения задач необходимы права суперпользователя (sudo: yes).

Запустить только что созданный набор инструкций можно следующей командой:

ansible-playbook install_nginx.yml 

PLAY [test] ****************************************************************** 

GATHERING FACTS *************************************************************** 
ok: [test-1]
ok: [test-2]

TASK: [Install package nginx] ************************************************* 
changed: [test-1]
changed: [test-2]

TASK: [Starting service nginx] ************************************************ 
ok: [test-1]
ok: [test-2]

PLAY RECAP ******************************************************************** 
test-1                 : ok=3    changed=1    unreachable=0    failed=0   
test-2                 : ok=3    changed=1    unreachable=0    failed=0   

После выполнения набора инструкций убедимся что nginx корректно установлен перейдя в браузере на ip-адрес удаленных хостов.
На этом все, в следующей статье разберем вывод данного playbook и продолжим разбираться с Ansible.

Добавить комментарий

20 Комментария

  1. user@ansible:/etc/ansible/playbooks$ ansible test -m ping
    Enter passphrase for key ‘/home/user/.ssh/id_rsa’:
    192.168.66.176 | SUCCESS => {
    «changed»: false,
    «ping»: «pong»
    }
    user@ansible:/etc/ansible/playbooks$ ansible-playbook install_nginx.yml
    [DEPRECATION WARNING]: Instead of sudo/sudo_user, use become/become_user and
    make sure become_method is ‘sudo’ (default). This feature will be removed in a
    future release. Deprecation warnings can be disabled by setting
    deprecation_warnings=False in ansible.cfg.

    PLAY ***************************************************************************

    TASK [setup] *******************************************************************
    ok: [192.168.66.176]

    TASK [Install package nginx] ***************************************************
    fatal: [192.168.66.176]: FAILED! => {«changed»: false, «failed»: true, «module_stderr»: «», «module_stdout»: «sudo: a password is required\r\n», «msg»: «MODULE FAILURE», «parsed»: false}

    PLAY RECAP *********************************************************************
    192.168.66.176 : ok=1 changed=0 unreachable=0 failed=1

    user@ansible:/etc/ansible/playbooks$ ansible —version
    ansible 2.0.0.2
    config file = /etc/ansible/ansible.cfg
    configured module search path = Default w/o overrides

  2. не знаю в чем была проблема, но я переустановил виртуалки Убунту 16,04 и установил Ансибл (правда установилась версия 2.0) и все заработало. Только на Убунту 16,04 стоит python 3, а нужен 2,7 и 2.

  3. Добрый день,
    ключ создал, заходи по ключу, пинг есть
    P500CA@P500CA:/etc/ansible$ ping 192.168.66.168
    PING 192.168.66.168 (192.168.66.168) 56(84) bytes of data.
    64 bytes from 192.168.66.168: icmp_seq=1 ttl=64 time=0.616 ms

    Выдает ошибку
    ansible test -m ping
    192.168.66.168 | UNREACHABLE! => {
    «changed»: false,
    «msg»: «Failed to connect to the host via ssh: Permission denied (publickey,password).\r\n»,
    «unreachable»: true
    }

    в чем где копать?

      • artem@artem-P500CA:/etc/ansible$ ansible test -m ping -vvvv
        Using /etc/ansible/ansible.cfg as config file
        Loading callback plugin minimal of type stdout, v2.0 from /usr/lib/python2.7/dist-packages/ansible/plugins/callback/__init__.pyc
        Using module file /usr/lib/python2.7/dist-packages/ansible/modules/core/system/ping.py
        ESTABLISH SSH CONNECTION FOR USER: None
        SSH: EXEC ssh -vvv -C -o ControlMaster=auto -o ControlPersist=60s -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o ConnectTimeout=10 -o ControlPath=/home/artem/.ansible/cp/ansible-ssh-%h-%p-%r 192.168.66.168 ‘/bin/sh -c ‘»‘»‘( umask 77 && mkdir -p «` echo $HOME/.ansible/tmp/ansible-tmp-1480433333.61-224886006734803 `» && echo ansible-tmp-1480433333.61-224886006734803=»` echo $HOME/.ansible/tmp/ansible-tmp-1480433333.61-224886006734803 `» ) && sleep 0′»‘»»
        192.168.66.168 | UNREACHABLE! => {
        «changed»: false,
        «msg»: «Failed to connect to the host via ssh: OpenSSH_6.9p1 Ubuntu-2ubuntu0.2, OpenSSL 1.0.2d 9 Jul 2015\r\ndebug1: Reading configuration data /etc/ssh/ssh_config\r\ndebug1: /etc/ssh/ssh_config line 19: Applying options for *\r\ndebug1: auto-mux: Trying existing master\r\ndebug1: Control socket \»/home/artem/.ansible/cp/ansible-ssh-192.168.66.168-22-artem\» does not exist\r\ndebug2: ssh_connect: needpriv 0\r\ndebug1: Connecting to 192.168.66.168 [192.168.66.168] port 22.\r\ndebug2: fd 3 setting O_NONBLOCK\r\ndebug1: fd 3 clearing O_NONBLOCK\r\ndebug1: Connection established.\r\ndebug3: timeout: 9991 ms remain after connect\r\ndebug1: key_load_public: No such file or directory\r\ndebug1: identity file /home/artem/.ssh/id_rsa type -1\r\ndebug1: key_load_public: No such file or directory\r\ndebug1: identity file /home/artem/.ssh/id_rsa-cert type -1\r\ndebug1: key_load_public: No such file or directory\r\ndebug1: identity file /home/artem/.ssh/id_dsa type -1\r\ndebug1: key_load_public: No such file or directory\r\ndebug1: identity file /home/artem/.ssh/id_dsa-cert type -1\r\ndebug1: key_load_public: No such file or directory\r\ndebug1: identity file /home/artem/.ssh/id_ecdsa type -1\r\ndebug1: key_load_public: No such file or directory\r\ndebug1: identity file /home/artem/.ssh/id_ecdsa-cert type -1\r\ndebug1: key_load_public: No such file or directory\r\ndebug1: identity file /home/artem/.ssh/id_ed25519 type -1\r\ndebug1: key_load_public: No such file or directory\r\ndebug1: identity file /home/artem/.ssh/id_ed25519-cert type -1\r\ndebug1: Enabling compatibility mode for protocol 2.0\r\ndebug1: Local version string SSH-2.0-OpenSSH_6.9p1 Ubuntu-2ubuntu0.2\r\ndebug1: Remote protocol version 2.0, remote software version OpenSSH_7.2p2 Ubuntu-4ubuntu2.1\r\ndebug1: match: OpenSSH_7.2p2 Ubuntu-4ubuntu2.1 pat OpenSSH* compat 0x04000000\r\ndebug2: fd 3 setting O_NONBLOCK\r\ndebug1: Authenticating to 192.168.66.168:22 as ‘artem’\r\ndebug3: hostkeys_foreach: reading file \»/home/artem/.ssh/known_hosts\»\r\ndebug3: record_hostkey: found key type ECDSA in file /home/artem/.ssh/known_hosts:1\r\ndebug3: load_hostkeys: loaded 1 keys from 192.168.66.168\r\ndebug3: order_hostkeyalgs: prefer hostkeyalgs: ecdsa-sha2-nistp256-cert-v01@openssh.com,ecdsa-sha2-nistp384-cert-v01@openssh.com,ecdsa-sha2-nistp521-cert-v01@openssh.com,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521\r\ndebug1: SSH2_MSG_KEXINIT sent\r\ndebug1: SSH2_MSG_KEXINIT received\r\ndebug2: kex_parse_kexinit: curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1\r\ndebug2: kex_parse_kexinit: ecdsa-sha2-nistp256-cert-v01@openssh.com,ecdsa-sha2-nistp384-cert-v01@openssh.com,ecdsa-sha2-nistp521-cert-v01@openssh.com,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,ssh-ed25519-cert-v01@openssh.com,ssh-rsa-cert-v01@openssh.com,ssh-dss-cert-v01@openssh.com,ssh-rsa-cert-v00@openssh.com,ssh-dss-cert-v00@openssh.com,ssh-ed25519,ssh-rsa,ssh-dss\r\ndebug2: kex_parse_kexinit: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,rijndael-cbc@lysator.liu.se\r\ndebug2: kex_parse_kexinit: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,rijndael-cbc@lysator.liu.se\r\ndebug2: kex_parse_kexinit: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1,hmac-md5-etm@openssh.com,hmac-ripemd160-etm@openssh.com,hmac-sha1-96-etm@openssh.com,hmac-md5-96-etm@openssh.com,hmac-md5,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96\r\ndebug2: kex_parse_kexinit: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1,hmac-md5-etm@openssh.com,hmac-ripemd160-etm@openssh.com,hmac-sha1-96-etm@openssh.com,hmac-md5-96-etm@openssh.com,hmac-md5,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96\r\ndebug2: kex_parse_kexinit: zlib@openssh.com,zlib,none\r\ndebug2: kex_parse_kexinit: zlib@openssh.com,zlib,none\r\ndebug2: kex_parse_kexinit: \r\ndebug2: kex_parse_kexinit: \r\ndebug2: kex_parse_kexinit: first_kex_follows 0 \r\ndebug2: kex_parse_kexinit: reserved 0 \r\ndebug2: kex_parse_kexinit: curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group14-sha1\r\ndebug2: kex_parse_kexinit: ssh-rsa,rsa-sha2-512,rsa-sha2-256,ecdsa-sha2-nistp256,ssh-ed25519\r\ndebug2: kex_parse_kexinit: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com\r\ndebug2: kex_parse_kexinit: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com\r\ndebug2: kex_parse_kexinit: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1\r\ndebug2: kex_parse_kexinit: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1\r\ndebug2: kex_parse_kexinit: none,zlib@openssh.com\r\ndebug2: kex_parse_kexinit: none,zlib@openssh.com\r\ndebug2: kex_parse_kexinit: \r\ndebug2: kex_parse_kexinit: \r\ndebug2: kex_parse_kexinit: first_kex_follows 0 \r\ndebug2: kex_parse_kexinit: reserved 0 \r\ndebug1: kex: server->client chacha20-poly1305@openssh.com zlib@openssh.com\r\ndebug1: kex: client->server chacha20-poly1305@openssh.com zlib@openssh.com\r\ndebug1: expecting SSH2_MSG_KEX_ECDH_REPLY\r\ndebug1: Server host key: ecdsa-sha2-nistp256 SHA256:c9YGC5xGfEjbq+6xSoV/MwYTSENaXLUrJmGsK0GEBtY\r\ndebug3: hostkeys_foreach: reading file \»/home/artem/.ssh/known_hosts\»\r\ndebug3: record_hostkey: found key type ECDSA in file /home/artem/.ssh/known_hosts:1\r\ndebug3: load_hostkeys: loaded 1 keys from 192.168.66.168\r\ndebug1: Host ‘192.168.66.168’ is known and matches the ECDSA host key.\r\ndebug1: Found key in /home/artem/.ssh/known_hosts:1\r\ndebug2: set_newkeys: mode 1\r\ndebug1: SSH2_MSG_NEWKEYS sent\r\ndebug1: expecting SSH2_MSG_NEWKEYS\r\ndebug2: set_newkeys: mode 0\r\ndebug1: SSH2_MSG_NEWKEYS received\r\ndebug1: SSH2_MSG_SERVICE_REQUEST sent\r\ndebug2: service_accept: ssh-userauth\r\ndebug1: SSH2_MSG_SERVICE_ACCEPT received\r\ndebug2: key: artem@artem-P500CA (0x5645f956a300),\r\ndebug2: key: /home/artem/.ssh/id_rsa ((nil)),\r\ndebug2: key: /home/artem/.ssh/id_dsa ((nil)),\r\ndebug2: key: /home/artem/.ssh/id_ecdsa ((nil)),\r\ndebug2: key: /home/artem/.ssh/id_ed25519 ((nil)),\r\ndebug1: Authentications that can continue: publickey,password\r\ndebug3: start over, passed a different list publickey,password\r\ndebug3: preferred gssapi-with-mic,gssapi-keyex,hostbased,publickey\r\ndebug3: authmethod_lookup publickey\r\ndebug3: remaining preferred: ,gssapi-keyex,hostbased,publickey\r\ndebug3: authmethod_is_enabled publickey\r\ndebug1: Next authentication method: publickey\r\ndebug1: Offering RSA public key: artem@artem-P500CA\r\ndebug3: send_pubkey_test\r\ndebug2: we sent a publickey packet, wait for reply\r\ndebug1: Authentications that can continue: publickey,password\r\ndebug1: Trying private key: /home/artem/.ssh/id_rsa\r\ndebug3: no such identity: /home/artem/.ssh/id_rsa: No such file or directory\r\ndebug1: Trying private key: /home/artem/.ssh/id_dsa\r\ndebug3: no such identity: /home/artem/.ssh/id_dsa: No such file or directory\r\ndebug1: Trying private key: /home/artem/.ssh/id_ecdsa\r\ndebug3: no such identity: /home/artem/.ssh/id_ecdsa: No such file or directory\r\ndebug1: Trying private key: /home/artem/.ssh/id_ed25519\r\ndebug3: no such identity: /home/artem/.ssh/id_ed25519: No such file or directory\r\ndebug2: we did not send a packet, disable method\r\ndebug1: No more authentication methods to try.\r\nPermission denied (publickey,password).\r\n»,
        «unreachable»: true
        }

      • пробовали подключаться к хосту той же командой, которую использует ansible?
        ssh -vvv -C -o ControlMaster=auto -o ControlPersist=60s -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o ConnectTimeout=10 -o ControlPath=/home/artem/.ansible/cp/ansible-ssh-%h-%p-%r 192.168.66.168

        какая версия ansible? как выглядит конфиг ansible?

        • artem@artem-P500CA:~/.ssh$ ansible —version
          ansible 2.2.0.0
          config file = /etc/ansible/ansible.cfg
          configured module search path = Default w/o overrides

        • # config file for ansible — http://ansible.com/
          # ==============================================

          # nearly all parameters can be overridden in ansible-playbook
          # or with command line flags. ansible will read ANSIBLE_CONFIG,
          # ansible.cfg in the current working directory, .ansible.cfg in
          # the home directory or /etc/ansible/ansible.cfg, whichever it
          # finds first

          [defaults]

          # some basic default values…

          inventory = /etc/ansible/hosts
          #library = /usr/share/my_modules/
          remote_tmp = $HOME/.ansible/tmp
          local_tmp = $HOME/.ansible/tmp
          forks = 5
          poll_interval = 15
          sudo_user = root
          ask_sudo_pass = True
          ask_pass = True
          transport = smart
          #remote_port = 22
          module_lang = C
          module_set_locale = False

          # plays will gather facts by default, which contain information about
          # the remote system.
          #
          # smart — gather by default, but don’t regather if already gathered
          # implicit — gather by default, turn off with gather_facts: False
          # explicit — do not gather by default, must say gather_facts: True
          #gathering = implicit

          # by default retrieve all facts subsets
          # all — gather all subsets
          # network — gather min and network facts
          # hardware — gather hardware facts (longest facts to retrieve)
          # virtual — gather min and virtual facts
          # facter — import facts from facter
          # ohai — import facts from ohai
          # You can combine them using comma (ex: network,virtual)
          # You can negate them using ! (ex: !hardware,!facter,!ohai)
          # A minimal set of facts is always gathered.
          #gather_subset = all

          # some hardware related facts are collected
          # with a maximum timeout of 10 seconds. This
          # option lets you increase or decrease that
          # timeout to something more suitable for the
          # environment.
          gather_timeout = 10

          # additional paths to search for roles in, colon separated
          #roles_path = /etc/ansible/roles

          # uncomment this to disable SSH key host checking
          #host_key_checking = False

          # change the default callback
          #stdout_callback = skippy
          # enable additional callbacks
          #callback_whitelist = timer, mail

          # Determine whether includes in tasks and handlers are «static» by
          # default. As of 2.0, includes are dynamic by default. Setting these
          # values to True will make includes behave more like they did in the
          # 1.x versions.
          #task_includes_static = True
          #handler_includes_static = True

          # Controls if a missing handler for a notification event is an error or a warnin
          g
          #error_on_missing_handler = True

          # change this for alternative sudo implementations
          #sudo_exe = sudo

          # What flags to pass to sudo
          # WARNING: leaving out the defaults might create unexpected behaviours
          #sudo_flags = -H -S -n

          # SSH timeout
          #timeout = 10

          # default user to use for playbooks if user is not specified
          # (/usr/bin/ansible will use current user as default)
          #remote_user = root

          # logging is off by default unless this path is defined
          # if so defined, consider logrotate
          log_path = /var/log/ansible.log

          # default module name for /usr/bin/ansible
          #module_name = command

          # use this shell for commands executed under sudo
          # you may need to change this to bin/bash in rare instances
          # if sudo is constrained
          #executable = /bin/sh

          # if inventory variables overlap, does the higher precedence one win
          # or are hash values merged together? The default is ‘replace’ but
          # this can also be set to ‘merge’.
          #hash_behaviour = replace

          # by default, variables from roles will be visible in the global variable
          # scope. To prevent this, the following option can be enabled, and only
          # tasks and handlers within the role will see the variables there
          #private_role_vars = yes

          # list any Jinja2 extensions to enable here:
          #jinja2_extensions = jinja2.ext.do,jinja2.ext.i18n

          # if set, always use this private key file for authentication, same as
          # if passing —private-key to ansible or ansible-playbook
          #private_key_file = /path/to/file
          private_key_file = /home/artem/.ssh/id_rsa

          # If set, configures the path to the Vault password file as an alternative to
          # specifying —vault-password-file on the command line.
          #vault_password_file = /path/to/vault_password_file

          # format of string {{ ansible_managed }} available within Jinja2
          # templates indicates to users editing templates files will be replaced.
          # replacing {file}, {host} and {uid} and strftime codes with proper values.
          #ansible_managed = Ansible managed: {file} modified on %Y-%m-%d %H:%M:%S by {uid} on {host}
          # {file}, {host}, {uid}, and the timestamp can all interfere with idempotence
          # in some situations so the default is a static string:
          #ansible_managed = Ansible managed

          # by default, ansible-playbook will display «Skipping [host]» if it determines a task
          # should not be run on a host. Set this to «False» if you don’t want to see these «Skipping»
          # messages. NOTE: the task header will still be shown regardless of whether or not the
          # task is skipped.
          #display_skipped_hosts = True

          # by default, if a task in a playbook does not include a name: field then
          # ansible-playbook will construct a header that includes the task’s action but
          # not the task’s args. This is a security feature because ansible cannot know
          # if the *module* considers an argument to be no_log at the time that the
          # header is printed. If your environment doesn’t have a problem securing
          # stdout from ansible-playbook (or you have manually specified no_log in your
          # playbook on all of the tasks where you have secret information) then you can
          # safely set this to True to get more informative messages.
          #display_args_to_stdout = False

          # by default (as of 1.3), Ansible will raise errors when attempting to dereference
          # Jinja2 variables that are not set in templates or action lines. Uncomment this line
          # to revert the behavior to pre-1.3.
          #error_on_undefined_vars = False

          # by default (as of 1.6), Ansible may display warnings based on the configuration of the
          # system running ansible itself. This may include warnings about 3rd party packages or
          # other conditions that should be resolved if possible.
          # to disable these warnings, set the following value to False:
          #system_warnings = True

          # by default (as of 1.4), Ansible may display deprecation warnings for language
          # features that should no longer be used and will be removed in future versions.
          # to disable these warnings, set the following value to False:
          #deprecation_warnings = True

          # (as of 1.8), Ansible can optionally warn when usage of the shell and
          # command module appear to be simplified by using a default Ansible module
          # instead. These warnings can be silenced by adjusting the following
          # setting or adding warn=yes or warn=no to the end of the command line
          # parameter string. This will for example suggest using the git module
          # instead of shelling out to the git command.
          # command_warnings = False

          # set plugin path directories here, separate with colons
          action_plugins = /usr/share/ansible/plugins/action
          cache_plugins = /usr/share/ansible/plugins/cache
          callback_plugins = /usr/share/ansible/plugins/callback
          connection_plugins = /usr/share/ansible/plugins/connection
          lookup_plugins = /usr/share/ansible/plugins/lookup
          inventory_plugins = /usr/share/ansible/plugins/inventory
          vars_plugins = /usr/share/ansible/plugins/vars
          filter_plugins = /usr/share/ansible/plugins/filter
          test_plugins = /usr/share/ansible/plugins/test
          strategy_plugins = /usr/share/ansible/plugins/strategy

          # by default callbacks are not loaded for /bin/ansible, enable this if you
          # want, for example, a notification or logging callback to also apply to
          # /bin/ansible runs
          #bin_ansible_callbacks = False

          # don’t like cows? that’s unfortunate.
          # set to 1 if you don’t want cowsay support or export ANSIBLE_NOCOWS=1
          #nocows = 1

          # set which cowsay stencil you’d like to use by default. When set to ‘random’,
          # a random stencil will be selected for each task. The selection will be filtered
          # against the `cow_whitelist` option below.
          #cow_selection = default
          #cow_selection = random

          # when using the ‘random’ option for cowsay, stencils will be restricted to this list.
          # it should be formatted as a comma-separated list with no spaces between names.
          # NOTE: line continuations here are for formatting purposes only, as the INI parser
          # in python does not support them.
          #cow_whitelist=bud-frogs,bunny,cheese,daemon,default,dragon,elephant-in-snake,elephant,eyes,\
          # hellokitty,kitty,luke-koala,meow,milk,moofasa,moose,ren,sheep,small,stegosaurus,\
          # stimpy,supermilker,three-eyes,turkey,turtle,tux,udder,vader-koala,vader,www

          # don’t like colors either?
          # set to 1 if you don’t want colors, or export ANSIBLE_NOCOLOR=1
          #nocolor = 1

          # if set to a persistent type (not ‘memory’, for example ‘redis’) fact values
          # from previous runs in Ansible will be stored. This may be useful when
          # wanting to use, for example, IP information from one group of servers
          # without having to talk to them in the same playbook run to get their
          # current IP information.
          #fact_caching = memory

          # retry files
          # When a playbook fails by default a .retry file will be created in ~/
          # You can disable this feature by setting retry_files_enabled to False
          # and you can change the location of the files by setting retry_files_save_path

          #retry_files_enabled = False
          #retry_files_save_path = ~/.ansible-retry

          # squash actions
          # Ansible can optimise actions that call modules with list parameters
          # when looping. Instead of calling the module once per with_ item, the
          # module is called once with all items at once. Currently this only works
          # under limited circumstances, and only with parameters named ‘name’.
          #squash_actions = apk,apt,dnf,homebrew,package,pacman,pkgng,yum,zypper

          # prevents logging of task data, off by default
          #no_log = False

          # prevents logging of tasks, but only on the targets, data is still logged on the master/control
          ler
          #no_target_syslog = False

          # controls whether Ansible will raise an error or warning if a task has no
          # choice but to create world readable temporary files to execute a module on
          # the remote machine. This option is False by default for security. Users may
          # turn this on to have behaviour more like Ansible prior to 2.1.x. See
          # https://docs.ansible.com/ansible/become.html#becoming-an-unprivileged-user
          # for more secure ways to fix this than enabling this option.
          #allow_world_readable_tmpfiles = False

          # controls the compression level of variables sent to
          # worker processes. At the default of 0, no compression
          # is used. This value must be an integer from 0 to 9.
          #var_compression_level = 9

          # controls what compression method is used for new-style ansible modules when
          # they are sent to the remote system. The compression types depend on having
          # support compiled into both the controller’s python and the client’s python.
          # The names should match with the python Zipfile compression types:
          # * ZIP_STORED (no compression. available everywhere)
          # * ZIP_DEFLATED (uses zlib, the default)
          # These values may be set per host via the ansible_module_compression inventory
          # variable
          #module_compression = ‘ZIP_DEFLATED’

          # This controls the cutoff point (in bytes) on —diff for files
          # set to 0 for unlimited (RAM may suffer!).
          #max_diff_size = 1048576

          [privilege_escalation]
          #become=True
          #become_method=sudo
          #become_user=root
          #become_ask_pass=False

          [paramiko_connection]

          # uncomment this line to cause the paramiko connection plugin to not record new host
          # keys encountered. Increases performance on new host additions. Setting works independently o
          f the
          # host key checking setting above.
          #record_host_keys=False

          # by default, Ansible requests a pseudo-terminal for commands executed under sudo. Uncomment thi
          s
          # line to disable this behaviour.
          #pty=False

          [ssh_connection]

          # ssh arguments to use
          # Leaving off ControlPersist will result in poor performance, so use
          # paramiko on older platforms rather than removing it, -C controls compression use
          #ssh_args = -C -o ControlMaster=auto -o ControlPersist=60s

          # The path to use for the ControlPath sockets. This defaults to
          # «%(directory)s/ansible-ssh-%%h-%%p-%%r», however on some systems with
          # very long hostnames or very long path names (caused by long user names or
          # deeply nested home directories) this can exceed the character limit on
          # file socket names (108 characters for most platforms). In that case, you
          # may wish to shorten the string below.
          #
          # Example:
          # control_path = %(directory)s/%%h-%%r
          #control_path = %(directory)s/ansible-ssh-%%h-%%p-%%r

          # Enabling pipelining reduces the number of SSH operations required to
          # execute a module on the remote server. This can result in a significant
          # performance improvement when enabled, however when using «sudo:» you must
          # first disable ‘requiretty’ in /etc/sudoers
          #
          # By default, this option is disabled to preserve compatibility with
          # sudoers configurations that have requiretty (the default on many distros).
          #
          #pipelining = False

          # Control the mechanism for transfering files
          # * smart = try sftp and then try scp [default]
          # * True = use scp only
          # * False = use sftp only
          #scp_if_ssh = smart

          # if False, sftp will not use batch mode to transfer files. This may cause some
          # types of file transfer failures impossible to catch however, and should
          # only be disabled if your sftp version has problems with batch mode
          #sftp_batch_mode = False

          [accelerate]
          accelerate_port = 5099
          accelerate_timeout = 30
          accelerate_connect_timeout = 5.0

          # The daemon timeout is measured in minutes. This time is measured
          # from the last activity to the accelerate daemon.
          #accelerate_daemon_timeout = 30

          # If set to yes, accelerate_multi_key will allow multiple
          # private keys to be uploaded to it, though each user must
          # have access to the system via SSH to add a new key. The default
          # is «no».
          #accelerate_multi_key = yes

          [selinux]
          # file systems that require special treatment when dealing with security context
          # the default behaviour that copies the existing context or uses the user default
          # needs to be changed to use the file system dependent context.
          #special_context_filesystems=nfs,vboxsf,fuse,ramfs

          # Set this to yes to allow libvirt_lxc connections to work without SELinux.
          #libvirt_lxc_noseclabel = yes

          [colors]
          #highlight = white
          #verbose = blue
          #warn = bright purple
          #error = red
          #debug = dark gray
          #deprecate = purple
          #skip = cyan
          #unreachable = red
          #ok = green
          #changed = yellow
          #diff_add = green
          #diff_remove = red
          #diff_lines = cyan

          • версия моего ansible:

            ansible --version
            ansible 2.1.1.0
              config file = /Users/e.lebed/ansible/ansible.cfg
              configured module search path = Default w/o overrides

            а вот конфиг, в котором только реально необходимые строки:

            cat /Users/e.lebed/ansible/ansible.cfg
            [defaults]
            hostfile       = ~/ansible/hosts
            pattern        = *
            forks          = 5
            poll_interval  = 15
            sudo_user      = root
            remote_port    = 22
            log_path       = ~/ansible/logs/ansible.log
            timeout        = 30
            host_key_checking = False

            попробуйте упростить свой конфиг, подумайте и оставьте в нем только нужные параметры

        • при конфиге который указный в комментариях выводиться следующая ошибка

          artem@artem-P500CA:/etc/ansible$ ansible test -m ping
          SSH password:
          SUDO password[defaults to SSH password]:
          192.168.66.168 | UNREACHABLE! => {
          «changed»: false,
          «msg»: «Authentication failure.»,
          «unreachable»: true
          }

          если закоментировать все параметры в конфиге то ошибка

          192.168.66.168 | UNREACHABLE! => {
          «changed»: false,
          «msg»: «Failed to connect to the host via ssh: Permission denied (publickey,password).\r\n»,
          «unreachable»: true
          }

          также нюанс, разные пользователи на АНСИБЛЕ artem на тестовом(192.168.66.168) user

          • этот «нюанс» может быть важным, у меня пользователь один на всех хостах. Попробуйте на тестовом тоже создать пользователя artem и добавить его в группу sudo

  4. клевая статья. спасибо. (Ошибка в ссылке «в следующей статье» — httsp -> https)