2

У меня ест такой файл hosts, со следующим содержимым:

 192.168.77.101 ansible_user=vagrant ansible_ssh_pass=vagrant zookeeperId=1 kafkaBrokerId=1
 192.168.77.102 ansible_user=vagrant ansible_ssh_pass=vagrant zookeeperId=2 kafkaBrokerId=2
 192.168.77.103 ansible_user=vagrant ansible_ssh_pass=vagrant zookeeperId=3 kafkaBrokerId=3

Мне не нравится, что все переменные для одного сервера необходимо указывать в одну строку. Есть ли способ сделать это более симпатичным? В документации нашел только описание списка переменных для группы серверов.

1 ответ 1

3

Нет никакой необходимости указывать все переменные в inventory файле. Собственно по лучшим практикам в inventory вообще переменных нет, только имена групп и хостов.

Ansible предполагает использовать дерево директорий:

production                # inventory file for production servers
staging                   # inventory file for staging environment

group_vars/
   group1.yml             # here we assign variables to particular groups
   group2.yml
host_vars/
   hostname1.yml          # here we assign variables to particular systems
   hostname2.yml

library/                  # if any custom modules, put them here (optional)
module_utils/             # if any custom module_utils to support modules, put them here (optional)
filter_plugins/           # if any custom filter plugins, put them here (optional)

site.yml                  # master playbook
webservers.yml            # playbook for webserver tier
dbservers.yml             # playbook for dbserver tier

roles/
    common/               # this hierarchy represents a "role"
        tasks/            #
            main.yml      #  <-- tasks file can include smaller files if warranted
        handlers/         #
            main.yml      #  <-- handlers file
        templates/        #  <-- files for use with the template resource
            ntp.conf.j2   #  <------- templates end in .j2
        files/            #
            bar.txt       #  <-- files for use with the copy resource
            foo.sh        #  <-- script files for use with the script resource
        vars/             #
            main.yml      #  <-- variables associated with this role
        defaults/         #
            main.yml      #  <-- default lower priority variables for this role
        meta/             #
            main.yml      #  <-- role dependencies
        library/          # roles can also include custom modules
        module_utils/     # roles can also include custom module_utils
        lookup_plugins/   # or other types of plugins, like lookup in this case

    webtier/              # same kind of structure as "common" was above, done for the webtier role
    monitoring/           # ""
    fooapp/               # ""

В group_vars кладутся файлы с именем имя группы.yml в формате yml, в host_vars - файлы с именем hostname. Имена групп и хостов те которые указаны в inventory. В этих файлах вы можете определить или переопределить переменные для группы или хоста.

Переменные могут объявляться много где, порядок приоритета переменных определён в документации.

Так, вы можете сделать файл group_vars/vagrant.yml

---
ansible_user: vagrant
ansible_ssh_pass: vagrant

Затем файлы host_vars/192.168.77.101.yml с содержимым:

---
zookeeperId: 1
kafkaBrokerId: 1

И аналогично два других хоста.

После этого вы можете оставить в inventory только

[vagrant]
192.168.77.101
192.168.77.102
192.168.77.103

После чего можно было бы улучшить читаемость - как-то назвать этот хосты, а в переменных хостов указать ansible_ssh_host: 192.168.77.101 для подключения.


Собственно две переменные явно выглядят как перечисления. Возможно вам подойдёт отдать эту заботу так же самому ansible? Объедините хосты в группу и возьмите вместо переменной позицию этого хоста в списке группы:

 {{groups['zookeeper'].index(inventory_hostname)}}
1
  • Я в inventory обычно пишу dns имена хостов. Но писать можно что угодно в качестве имён, inventory_hostname потому и отдельная переменная что зависит только от именования хоста в inventory файле 19 окт 2019 в 11:21

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.