Что такое ansible inventory
Автоматизируем и ускоряем процесс настройки облачных серверов с Ansible. Часть 3: Переменные и файл inventory
В первой части мы начали изучение Ansible, популярного инструмента для автоматизации настройки и развертывания ИТ-инфраструктуры. Ansible был успешно установлен, описаны принципы работы, базовая настройка. В завершении статьи мы показали как быстро установить nginx на несколько серверов.
Во второй части мы разобрались в выводе playbook, научились отлаживать и повторно использовать скрипты Ansible.
В этой части вы узнаете, как писать единый Ansible playbook для разных ОС (например с rpm и deb), как обслуживать множество хостов и не писать их все в inventory, как сгруппировать сервера по регионам InfoboxCloud и многое другое.
Переменные в Ansible
Переменные используются для хранения значений, которые могут применяться в playbook. В процессе использования переменные можно переопределять множество раз. Информация о серверах из inventory также может использоваться как переменные.
Задача установит в переменную package_name значение httpd или apache2 в зависимости от семейства ОС на сервере.
Переменные можно использовать для установки значений пользователя в процессе исполнения playbook:
В переменные удобно сохранить список значений для его многократного использования. Если одна и та же переменная используется во множестве playbook – их использование уменьшит сложность скриптов.
Все переменные в Ansible должны начинаться с буквы. В имени можно использовать буквы, цифры и подчеркивания.
Переменные, определенные в include файлах будут перегружать (заменять) переменные, определенные на других уровнях иерархии, кроме переменных, переданных через —extra-vars.
Переменные в импортированных файлах
/ansible/playbooks/tasks/pkg_apache_install.yml):
Включим его в файл установки Apache и проверки, что сервис запущен (
/ansible/setup_apache.yml):
Как мы видим, в файле setup_apache.yml мы успешно используем переменную, определенную во включенном файле. Данный playbook будет правильно устанавливать apache и на rpm дистрибутивы и на deb, используя правильное имя пакета с apache.
Переменные в playbook
Переменные в playbook устанавливаются с помощью ключевого слова vars:. Переменные устанавливаются в виде имя_переменной: значение. Переменные перегрузят другие переменные, которые установлены в глобальном файле или в inventory.
Пример описания переменной в playbook:
Переменные в глобальном файле
/ansible/common/vars/global.yml
В данном примере мы задаем переменную package_name напрямую (после # можно написать комментарий), а ключи доступа для InfoboxCloud API ищем в переменных окружения с помощью плагина lookup.
В playbook путь к файлам переменных задается через vars_files:
Использование фактов как переменных
Вы можете использовать любой факт как переменную, который собирается при gather_facts. Для получения списка всех фактов для конкретной группы машин используйте команду:
, где experiments – название группы машин в inventory.
Погружаемся в inventory–файл
В первой части мы кратко рассматривали простой inventory–файл. Давайте посмотрим на него внимательнее.
/ansible/inventory):
Можно просто записать имена хостов и ip адреса и будут использоваться все сервера при исполнении playbook с этим файлом inventory.
Группы в inventory
Использование групп мы также уже видели ранее:
Группа для исполнения playbook указывается в разделе «hosts:» playbook
Если вы хотите использовать конкретный хост — можно в раздел hosts передать его.
Если вы хотите использовать все хосты всех групп — можно использовать
Группы групп в inventory
Очень полезная функция, позволяющая, например, сгруппировать хосты не только по назначению, но и по региону размещения, что очень актуально для InfoboxCloud (Москва, Амстердам). Нередко бывают и другие задачи, где нужно использовать группы групп.
В этом примере в группу web my входят сервера в Москве и Амстердаме. Можно из playbook обращаться как к группе web, так и к группам серверов в конкретном регионе.
Регулярные выражения в inventory
Если у вас есть большое количество серверов, использование соглашений о наименовании (например web001, web002… web00N) позволит проще указывать их в inventory. Можно использовать регулярные выражения в inventory файле:
Переменные в inventory–файле
Рассмотренные ранее способы установки переменных применяли их сразу ко всем хостам в inventory. Иногда может потребоваться использование специфических переменных для конкретной группы хостов или конкретного хоста.
Установка переменных для конкретных хостов:
Установка переменных для группы хостов (web):
Вынос переменных в отдельные файлы для inventory
Можно создавать файлы переменных для хостов и для групп. Папки с этими файлами должны быть в одной директории с файлом inventory. Файлы переменных, относящиеся к конкретным хостам, нужно сохранять в папку host_vars, относящиеся к конкретным группам — в папку group_vars.
Пример файла переменных для хоста web001 (
/ansible/host_vars/web001):
Пример файла переменных для группы db (
Переменные inventory следуют иерархии: переменные в глобальном файле перегружают любые хост-переменные, групповые переменные и переменные в файле inventory. Хост-переменные перегружают групповые переменные, а в свою очередь групповые переменные перегружают переменные файла inventory.
Через ansible.cfg можно переопределить параметры конфигурации Ansible.
Заключение
В написании статьи очень помогла книга «Learning Ansible» и конечно официальная документация.
Все эксперименты с Ansible удобно проводить в InfoboxCloud, так как имеется возможность для каждого виртуального сервера установить именно то количество ресурсов, которое необходимо для задачи (CPU/Ram/диск независимо друг от друга) или использовать автомасштабирование, а не выбирать VM из готовых шаблонов. Когда эксперименты не проводятся — можно просто выключить VM и оплачивать только стоимость диска.
Если вы обнаружили ошибку в статье, автор ее с удовольствием исправит. Пожалуйста напишите в ЛС или на почту о ней. Туда же можно задавать вопросы по Ansible для освещения в последующих статьях.
Inventory¶
option on the command line.
Hosts and Groups¶
The format for /etc/ansible/hosts is an INI-like format and looks like this:
The headings in brackets are group names, which are used in classifying systems and deciding what systems you are controlling at what times and for what purpose.
It is ok to put systems in more than one group, for instance a server could be both a webserver and a dbserver. If you do, note that variables will come from all of the groups they are a member of. Variable precedence is detailed in a later chapter.
If you have hosts that run on non-standard SSH ports you can put the port number after the hostname with a colon. Ports listed in your SSH config file won’t be used with the paramiko connection but will be used with the openssh connection.
To make things explicit, it is suggested that you set them if things are not running on the default port:
Suppose you have just static IPs and want to set up some aliases that live in your host file, or you are connecting through tunnels. You can also describe hosts like this:
In the above example, trying to ansible against the host alias “jumper” (which may not even be a real hostname) will contact 192.0.2.50 on port 5555. Note that this is using a feature of the inventory file to define some special variables. Generally speaking this is not the best way to define variables that describe your system policy, but we’ll share suggestions on doing this later. We’re just getting started.
Adding a lot of hosts? If you have a lot of hosts following similar patterns you can do this rather than listing each hostname:
For numeric patterns, leading zeros can be included or removed, as desired. Ranges are inclusive. You can also define alphabetic ranges:
You can also select the connection type and user on a per host basis:
As mentioned above, setting these in the inventory file is only a shorthand, and we’ll discuss how to store them in individual files in the ‘host_vars’ directory a bit later on.
Host Variables¶
As alluded to above, it is easy to assign variables to hosts that will be used later in playbooks:
Group Variables¶
Variables can also be applied to an entire group at once:
Groups of Groups, and Group Variables¶
It is also possible to make groups of groups using the :children suffix. Just like above, you can apply variables using :vars :
If you need to store lists or hash data, or prefer to keep host and group specific variables separate from the inventory file, see the next section.
Default groups¶
Splitting Out Host and Group Specific Data¶
The preferred practice in Ansible is actually not to store variables in the main inventory file.
In addition to storing variables directly in the INI file, host and group variables can be stored in individual files relative to the inventory file.
These variable files are in YAML format. Valid file extensions include ‘.yml’, ‘.yaml’, ‘.json’, or no file extension. See YAML Syntax if you are new to YAML.
Assuming the inventory file path is:
If the host is named ‘foosball’, and in groups ‘raleigh’ and ‘webservers’, variables in YAML files at the following locations will be made available to the host:
For instance, suppose you have hosts grouped by datacenter, and each datacenter uses some different servers. The data in the groupfile ‘/etc/ansible/group_vars/raleigh’ for the ‘raleigh’ group might look like:
It is ok if these files do not exist, as this is an optional feature.
As an advanced use-case, you can create directories named after your groups or hosts, and Ansible will read all the files in these directories. An example with the ‘raleigh’ group:
All hosts that are in the ‘raleigh’ group will have the variables defined in these files available to them. This can be very useful to keep your variables organized when a single file starts to be too big, or when you want to use Ansible Vault on a part of a group’s variables. Note that this only works on Ansible 1.4 or later.
Tip: In Ansible 1.2 or later the group_vars/ and host_vars/ directories can exist in the playbook directory OR the inventory directory. If both paths exist, variables in the playbook directory will override variables set in the inventory directory.
Tip: Keeping your inventory file and variables in a git repo (or other version control) is an excellent way to track changes to your inventory and host variables.
List of Behavioral Inventory Parameters¶
As alluded to above, setting the following variables controls how ansible interacts with remote hosts.
Privilege escalation (see Ansible Privilege Escalation for further details):
Remote host environment parameters:
Examples from a host file:
Non-SSH connection types¶
local
This connector can be used to deploy the playbook to the control machine itself.
docker
This connector deploys the playbook directly into Docker containers using the local Docker client. The following parameters are processed by this connector:
ansible_host The name of the Docker container to connect to. ansible_user The user name to operate within the container. The user must exist inside the container. ansible_become If set to true the become_user will be used to operate within the container. ansible_docker_extra_args Could be a string with any additional arguments understood by Docker, which are not command specific. This parameter is mainly used to configure a remote Docker daemon to use.
Here is an example of how to instantly deploy to created containers:
Dynamic Inventory Pulling inventory from dynamic sources, such as cloud providers Introduction To Ad-Hoc Commands Examples of basic commands Playbooks Learning Ansible’s configuration, deployment, and orchestration language. Mailing List Questions? Help? Ideas? Stop by the list on Google Groups irc.freenode.net #ansible IRC chat channel
Copyright © 2017 Red Hat, Inc.
Last updated on Dec 01, 2020.
Ansible docs are generated from GitHub sources using Sphinx using a theme provided by Read the Docs.
Создание файла инвентаря Ansible
Ansible – это современный инструмент управления конфигурацией, который упрощает настройку и обслуживание удаленных серверов. Ansible предлагает минималистичный дизайн, благодаря чему вы можете быстро разобраться с функциями и начать работу. Файл инвентаря Ansible позволяет отслеживать, какие хосты являются частью вашей инфраструктуры, и обеспечивает выполнение необходимых команд и сценариев на этих хостах.
Существует несколько способов настройки этого файла Ansible (в зависимости от вашей среды и потребностей проекта). В этом мануале мы покажем, как создавать файлы инвентаря и организовывать серверы в группы и подгруппы, как настраивать переменные хоста и использовать шаблоны для управления командами и сценариями Ansible для каждого хоста и каждой группы.
Требования
1: Создание пользовательского инвентаря
Вы можете без проблем использовать этот стандартный инвентарь, но лучше все же создавать индивидуальные файлы инвентаря для каждого отдельного проекта: это позволяет избежать путаницы и некоторых ошибок при выполнении команд и плейбуков. Наличие индивидуального инвентаря для каждого проекта также упростит совместное использование настроек (если вы хотите включить этот файл в репозиторий кода проекта).
Для начала войдите в домашний каталог и создайте новый каталог для хранения ваших файлов Ansible:
Перейдите в него и откройте новый файл инвентаря в текстовом редакторе:
cd ansible
nano inventory
Для создания рабочего файла инвентаря достаточно поместить в него список ваших хостов (каждый новый хост – с новой строки). Имена хостов и IP-адреса взаимозаменяемы:
203.0.113.111
203.0.113.112
203.0.113.113
server_hostname
После настройки инвентаря вы можете использовать команду ansible-inventory для проверки и получения информации о вашем инвентаре Ansible:
Пока что мы не создали никаких групп в нашем инвентаре, но вывод показывает две отдельные группы, которые Ansible выдает автоматически: all и ungrouped. Как следует из названия, группа all используется для ссылки на все серверы из инвентаря, независимо от того, как они организованы. Группа ungrouped используется для ссылки на серверы, которые не входят в какую-либо группу.
Запуск команд и плейбуков с пользовательским инвентарем
Это запустит модуль ping на всех хостах, перечисленных в вашем файле инвентаря.
Точно так же можно запустить сценарии Ansible:
Итак, мы создали базовый инвентарь и попробовали использовать его для выполнения команд и сценариев. Теперь давайте объединим хосты в группы и подгруппы.
2: Объединение хостов в группы и подгруппы
В файле инвентаря вы можете распределить серверы по различным группам и подгруппам. Это не только помогает поддерживать порядок на ваших хостах, но и позволяет использовать групповые переменные – функцию, которая может значительно облегчить управление промежуточными средами с помощью Ansible.
Один хост может входить в несколько групп. Следующий файл инвентаря в формате INI демонстрирует настройку с четырьмя группами: webservers, dbservers, development и production. Обратите внимание, что серверы сгруппированы по двум разным характеристикам: их назначение (интернет и база данных) и среда их использования (разработка и производство).
[webservers] 203.0.113.111
203.0.113.112
[dbservers] 203.0.113.113
server_hostname
[development] 203.0.113.111
203.0.113.113
[production] 203.0.113.112
server_hostname
Если запустить этот инвентарь с помощью ansible-inventory, вы получите:
<
«_meta»: <
«hostvars»: <>
>,
«all»: <
«children»: [
«dbservers»,
«development»,
«production»,
«ungrouped»,
«webservers»
] >,
«dbservers»: <
«hosts»: [
«203.0.113.113»,
«server_hostname»
] >,
«development»: <
«hosts»: [
«203.0.113.111»,
«203.0.113.113»
] >,
«production»: <
«hosts»: [
«203.0.113.112»,
«server_hostname»
] >,
«webservers»: <
«hosts»: [
«203.0.113.111»,
«203.0.113.112»
] >
>
Также внутри родительских групп можно создавать дочерние группы. В таком случае «родительский элемент» также называется метагруппой. В следующем примере вы увидите тот же инвентарь, что и в предыдущем, но организованный по-другому. Здесь используются метагруппы, что позволяют более подробно организовать инфраструктуру:
[web_dev] 203.0.113.111
[web_prod] 203.0.113.112
[db_dev] 203.0.113.113
[db_prod] server_hostname
[webservers:children] web_dev
web_prod
[dbservers:children] db_dev
db_prod
[development:children] web_dev
db_dev
[production:children] web_prod
db_prod
Чем больше у вас серверов, тем больше смысла имеет деление их на группы или метагруппы.
3: Настройка псевдонимов
Вы можете использовать псевдонимы для ваших хостов, чтобы облегчить обращение к этим серверам позже, при выполнении команд и плейбуков.
Чтобы использовать псевдоним, сначала введите его в файл, а затем включите после него переменную ansible_host, содержащую соответствующий IP-адрес или имя хоста сервера, который должен отвечать на этот псевдоним:
server1 ansible_host=203.0.113.111
server2 ansible_host=203.0.113.112
server3 ansible_host=203.0.113.113
server4 ansible_host=server_hostname
Если бы вы запустили команду ansible-inventory с этим инвентарем, вы бы увидели примерно такой результат:
<
«_meta»: <
«hostvars»: <
«server1»: <
«ansible_host»: «203.0.113.111»
>,
«server2»: <
«ansible_host»: «203.0.113.112»
>,
«server3»: <
«ansible_host»: «203.0.113.113»
>,
«server4»: <
«ansible_host»: «server_hostname»
>
>
>,
«all»: <
«children»: [
«ungrouped»
] >,
«ungrouped»: <
«hosts»: [
«server1»,
«server2»,
«server3»,
«server4»
] >
>
Обратите внимание, теперь на серверы ссылаются их псевдонимы, а не IP-адреса или имена хостов. Так проще ссылаться на отдельные серверы при выполнении команд и плейбуков.
4: Настройка переменных хоста
Файл инвентаря можно использовать для настройки переменных, которые изменят поведение Ansible по умолчанию при подключении и выполнении команд на ваших нодах. Фактически мы сделали это на предыдущем шаге, при настройке псевдонимов хостов. По сути переменная ansible_host сообщает Ansible, где найти удаленные ноды, если для ссылки на этот сервер используется псевдоним.
Переменные инвентаря можно установить для любого хоста или для любой группы. Помимо переопределения параметров Ansible по умолчанию, эти переменные также позволяют выполнять дальнейшую настройку для отдельных хостов и групп в плейбуках.
В следующем примере показано, как определить удаленного пользователя по умолчанию при подключении к каждой ноде, перечисленной в этом инвентаре:
server1 ansible_host=203.0.113.111 ansible_user=8host
server2 ansible_host=203.0.113.112 ansible_user=8host
server3 ansible_host=203.0.113.113 ansible_user=myuser
server4 ansible_host=server_hostname ansible_user=myuser
Вы объединить хосты с одинаковыми настройками в одну группу, а затем настроить их переменные на уровне группы:
[group_a] server1 ansible_host=203.0.113.111
server2 ansible_host=203.0.113.112
[group_b] server3 ansible_host=203.0.113.113
server4 ansible_host=server_hostname
[group_a:vars] ansible_user=8host
[group_b:vars] ansible_user=myuser
Команда ansible-inventory, запущенная с таким инвентарем, выдаст следующий результат:
<
«_meta»: <
«hostvars»: <
«server1»: <
«ansible_host»: «203.0.113.111»,
«ansible_user»: «8host»
>,
«server2»: <
«ansible_host»: «203.0.113.112»,
«ansible_user»: «8host»
>,
«server3»: <
«ansible_host»: «203.0.113.113»,
«ansible_user»: «myuser»
>,
«server4»: <
«ansible_host»: «server_hostname»,
«ansible_user»: «myuser»
>
>
>,
«all»: <
«children»: [
«group_a»,
«group_b»,
«ungrouped»
] >,
«group_a»: <
«hosts»: [
«server1»,
«server2»
] >,
«group_b»: <
«hosts»: [
«server3»,
«server4»
] >
>
Обратите внимание, все переменные инвентаря перечислены в ноде _meta.
5: Использование шаблонов для запуска команд и плейбуков
При выполнении команд и плейбуков с помощью Ansible вы должны указать цель. Шаблоны позволяют настраивать определенные целевые ноды, группы или подгруппы в файле инвентаря. Шаблоны очень гибкие, поддерживают регулярные выражения и подстановочные знаки.
Давайте рассмотрим следующий файл инвентаря:
[webservers] 203.0.113.111
203.0.113.112
[dbservers] 203.0.113.113
server_hostname
[development] 203.0.113.111
203.0.113.113
[production] 203.0.113.112
server_hostname
Теперь представьте, что вам нужно выполнить команду, нацеленную только на сервер(ы) базы данных, которые работают в производственной среде. В этом примере этому критерию соответствует только server_hostname; однако легко предположить, что в этой группе может оказаться гораздо больше серверов баз данных. Чтобы не настраивать индивидуальный таргетинг на каждый сервер, вы можете использовать следующий шаблон:
Этот шаблон будет нацелен на серверы, которые присутствуют и в группе dbservers, и в production одновременно. Если же вы хотите нацелить шаблон на серверы, которые состоят только в группе dbservers, исключив группу production, – вы должны вместо этого использовать следующий шаблон:
В следующей таблице вы найдете несколько общих шаблонов, которые вы можете использовать при запуске команд и плейбуков Ansible:
Шаблон | цель |
all | Все хосты из указанного инвентаря |
host1 | Единственный хост (host1) |
host1:host2 | Оба хоста, host1 и host2 |
group1 | Единственная группа (group1) |
group1:group2 | Все серверы в группах group1 и group2 |
group1:&group2 | Cерверы, которые состоят и в группе group1, и в group2 |
group1:!group2 | Серверы, которые состоят только в group1, исключая те, что состоят одновременно в группе group2 |
Для получения дополнительной информации о параметрах шаблонов (например, о позиционных шаблонах и регулярных выражениях) обратитесь к официальной документации Ansible.
Заключение
В этом мануале мы подробно рассмотрели инвентарь Ansible. Теперь вы знаете, как организовать ноды в группы и подгруппы, как настроить переменные инвентаря и как использовать шаблоны для определения целевых групп серверов при выполнении команд и плейбуков.
How to build your inventory
Ansible works against multiple managed nodes or “hosts” in your infrastructure at the same time, using a list or group of lists known as inventory. Once your inventory is defined, you use patterns to select the hosts or groups you want Ansible to run against.
Inventory basics: formats, hosts, and groups
The inventory file can be in one of many formats, depending on the inventory plugins you have. The most common formats are INI and YAML. A basic INI /etc/ansible/hosts might look like this:
Here’s that same basic inventory file in YAML format:
Default groups
Hosts in multiple groups
You can (and probably will) put each host in more than one group. For example a production webserver in a datacenter in Atlanta might be included in groups called [prod] and [atlanta] and [webservers]. You can create groups that track:
Extending the previous YAML inventory to include what, when, and where would look like:
You can also use nested groups to simplify prod and test in this inventory, for the same result:
Adding ranges of hosts
If you have a lot of hosts with a similar pattern, you can add them as a range rather than listing each hostname separately:
You can specify a stride (increments between sequence numbers) when defining a numeric range of hosts:
For numeric patterns, leading zeros can be included or removed, as desired. Ranges are inclusive. You can also define alphabetic ranges:
Adding variables to inventory
You can store variable values that relate to a specific host or group in inventory. To start with, you may add variables directly to the hosts and groups in your main inventory file. As you add more and more managed nodes to your Ansible inventory, however, you will likely want to store variables in separate host and group variable files. See Defining variables in inventory for details.
Assigning a variable to one machine: host variables
You can easily assign a variable to a single host, then use it later in playbooks. In INI:
Unique values like non-standard SSH ports work well as host variables. You can add them to your Ansible inventory by adding the port number after the hostname with a colon:
Connection variables also work well as host variables:
If you list non-standard SSH ports in your SSH config file, the openssh connection will find and use them, but the paramiko connection will not.
Inventory aliases
You can also define aliases in your inventory:
In the above example, running Ansible against the host alias “jumper” will connect to 192.0.2.50 on port 5555. See behavioral inventory parameters to further customize the connection to hosts.
Values passed in the INI format using the key=value syntax are interpreted differently depending on where they are declared:
When declared inline with the host, INI values are interpreted as Python literal structures (strings, numbers, tuples, lists, dicts, booleans, None). Host lines accept multiple key=value parameters per line. Therefore they need a way to indicate that a space is part of a value rather than a separator.
When declared in a :vars section, INI values are interpreted as strings. For example var=FALSE would create a string equal to ‘FALSE’. Unlike host lines, :vars sections accept only a single entry per line, so everything after the = must be the value for the entry.
If a variable value set in an INI inventory must be a certain type (for example, a string or a boolean value), always specify the type with a filter in your task. Do not rely on types set in INI inventories when consuming variables.
Consider using YAML format for inventory sources to avoid confusion on the actual type of a variable. The YAML inventory plugin processes variable values consistently and correctly.
Generally speaking, this is not the best way to define variables that describe your system policy. Setting variables in the main inventory file is only a shorthand. See Organizing host and group variables for guidelines on storing variable values in individual files in the ‘host_vars’ directory.
Assigning a variable to many machines: group variables
If all hosts in a group share a variable value, you can apply that variable to an entire group at once. In INI:
Inheriting variable values: group variables for groups of groups
You can make groups of groups using the :children suffix in INI or the children: entry in YAML. You can apply variables to these groups of groups using :vars or vars: :
Child groups have a couple of properties to note:
Any host that is member of a child group is automatically a member of the parent group.
A child group’s variables will have higher precedence (override) a parent group’s variables.
Groups can have multiple parents and children, but not circular relationships.
Hosts can also be in multiple groups, but there will only be one instance of a host, merging the data from the multiple groups.
Organizing host and group variables
Although you can store variables in the main inventory file, storing separate host and group variables files may help you organize your variable values more easily. Host and group variable files must use YAML syntax. Valid file extensions include ‘.yml’, ‘.yaml’, ‘.json’, or no file extension. See YAML Syntax if you are new to YAML.
Ansible loads host and group variable files by searching paths relative to the inventory file or the playbook file. If your inventory file at /etc/ansible/hosts contains a host named ‘foosball’ that belongs to two groups, ‘raleigh’ and ‘webservers’, that host will use variables in YAML files at the following locations:
For example, if you group hosts in your inventory by datacenter, and each datacenter uses its own NTP server and database server, you can create a file called /etc/ansible/group_vars/raleigh to store the variables for the raleigh group:
You can also create directories named after your groups or hosts. Ansible will read all the files in these directories in lexicographical order. An example with the ‘raleigh’ group:
All hosts in the ‘raleigh’ group will have the variables defined in these files available to them. This can be very useful to keep your variables organized when a single file gets too big, or when you want to use Ansible Vault on some group variables.
Keeping your inventory file and variables in a git repo (or other version control) is an excellent way to track changes to your inventory and host variables.
How variables are merged
By default variables are merged/flattened to the specific host before a play is run. This keeps Ansible focused on the Host and Task, so groups don’t really survive outside of inventory and host matching. By default, Ansible overwrites variables including the ones defined for a group and/or host (see DEFAULT_HASH_BEHAVIOUR ). The order/precedence is (from lowest to highest):
all group (because it is the ‘parent’ of all other groups)
By default Ansible merges groups at the same parent/child level in ASCII order, and the last group loaded overwrites the previous groups. For example, an a_group will be merged with b_group and b_group vars that match will overwrite the ones in a_group.
You can change this behavior by setting the group variable ansible_group_priority to change the merge order for groups of the same level (after the parent/child order is resolved). The larger the number, the later it will be merged, giving it higher priority. This variable defaults to 1 if not set. For example:
ansible_group_priority can only be set in the inventory source and not in group_vars/, as the variable is used in the loading of group_vars.
Using multiple inventory sources
Target two sources from the command line like this:
Aggregating inventory sources with a directory
You can also create an inventory by combining multiple inventory sources and source types under a directory. This can be useful for combining static and dynamic hosts and managing them as one inventory. The following inventory combines an inventory plugin source, a dynamic inventory script, and a file with static hosts:
You can target this inventory directory simply like this:
It can be useful to control the merging order of the inventory sources if there’s variable conflicts or group of groups dependencies to the other inventory sources. The inventories are merged in ASCII order according to the filenames so the result can be controlled by adding prefixes to the files:
Connecting to hosts: behavioral inventory parameters
As described above, setting the following variables control how Ansible interacts with remote hosts.
Ansible does not expose a channel to allow communication between the user and the ssh process to accept a password manually to decrypt an ssh key when using the ssh connection plugin (which is the default). The use of ssh-agent is highly recommended.
General for all connections:
The name of the host to connect to, if different from the alias you wish to give to it.
The connection port number, if not the default (22 for ssh)
The user name to use when connecting to the host
The password to use to authenticate to the host (never store this variable in plain text; always use a vault. See Keep vaulted variables safely visible )
Specific to the SSH connection:
Private key file used by ssh. Useful if using multiple keys and you don’t want to use SSH agent.
This setting is always appended to the default command line for sftp, scp, and ssh. Useful to configure a ProxyCommand for a certain host (or group).
This setting is always appended to the default sftp command line.
This setting is always appended to the default scp command line.
This setting is always appended to the default ssh command line.
ansible_ssh_executable (added in version 2.2)
Privilege escalation (see Ansible Privilege Escalation for further details):
Allows to set privilege escalation method
Remote host environment parameters:
The target host python path. This is useful for systems with more than one Python or not located at /usr/bin/python such as *BSD, or where /usr/bin/python is not a 2.X series Python. We do not use the /usr/bin/env mechanism as that requires the remote user’s path to be set right and also assumes the python executable is named python, where the executable might be named something like python2.6.
This sets the shell the ansible controller will use on the target machine, overrides executable in ansible.cfg which defaults to /bin/sh. You should really only change it if is not possible to use /bin/sh (in other words, if /bin/sh is not installed on the target machine or cannot be run from sudo.).
Examples from an Ansible-INI host file:
Non-SSH connection types
local
This connector can be used to deploy the playbook to the control machine itself.
docker
This connector deploys the playbook directly into Docker containers using the local Docker client. The following parameters are processed by this connector:
The name of the Docker container to connect to.
The user name to operate within the container. The user must exist inside the container.
If set to true the become_user will be used to operate within the container.
Could be a string with any additional arguments understood by Docker, which are not command specific. This parameter is mainly used to configure a remote Docker daemon to use.
Here is an example of how to instantly deploy to created containers:
If you’re reading the docs from the beginning, this may be the first example you’ve seen of an Ansible playbook. This is not an inventory file. Playbooks will be covered in great detail later in the docs.
Inventory setup examples
Example: One inventory per environment
If you need to manage multiple environments it’s sometimes prudent to have only hosts of a single environment defined per inventory. This way, it is harder to, for instance, accidentally change the state of nodes inside the “test” environment when you actually wanted to update some “staging” servers.
For the example mentioned above you could have an inventory_test file:
That file only includes hosts that are part of the “test” environment. Define the “staging” machines in another file called inventory_staging :
To apply a playbook called site.yml to all the app servers in the test environment, use the following command:
Example: Group by function
In the previous section you already saw an example for using groups in order to cluster hosts that have the same function. This allows you, for instance, to define firewall rules inside a playbook or role affecting only database servers:
Example: Group by location
Other tasks might be focused on where a certain host is located. Let’s say that db01.test.example.com and app01.test.example.com are located in DC1 while db02.test.example.com is in DC2:
In practice, you might even end up mixing all these setups as you might need to, on one day, update all nodes in a specific data center while, on another day, update all the application servers no matter their location.
Pulling inventory from dynamic or static sources
Pulling inventory from dynamic sources, such as cloud providers
Examples of basic commands
Learning Ansible’s configuration, deployment, and orchestration language.
Questions? Help? Ideas? Stop by the list on Google Groups
How to join Ansible chat channels
© Copyright Ansible project contributors. Last updated on Dec 21, 2021.