Что такое ansible playbook
Intro to playbooks
Ansible Playbooks offer a repeatable, re-usable, simple configuration management and multi-machine deployment system, one that is well suited to deploying complex applications. If you need to execute a task with Ansible more than once, write a playbook and put it under source control. Then you can use the playbook to push out new configuration or confirm the configuration of remote systems. The playbooks in the ansible-examples repository illustrate many useful techniques. You may want to look at these in another tab as you read the documentation.
orchestrate steps of any manual ordered process, on multiple sets of machines, in a defined order
launch tasks synchronously or asynchronously
Playbook syntax
Playbooks are expressed in YAML format with a minimum of syntax. If you are not familiar with YAML, look at our overview of YAML Syntax and consider installing an add-on for your text editor (see Other Tools and Programs ) to help you write clean YAML syntax in your playbooks.
A playbook is composed of one or more ‘plays’ in an ordered list. The terms ‘playbook’ and ‘play’ are sports analogies. Each play executes part of the overall goal of the playbook, running one or more tasks. Each task calls an Ansible module.
Playbook execution
A playbook runs in order from top to bottom. Within each play, tasks also run in order from top to bottom. Playbooks with multiple ‘plays’ can orchestrate multi-machine deployments, running one play on your webservers, then another play on your database servers, then a third play on your network infrastructure, and so on. At a minimum, each play defines two things:
the managed nodes to target, using a pattern
at least one task to execute
In this example, the first play targets the web servers; the second play targets the database servers.
Task execution
By default, Ansible executes each task in order, one at a time, against all machines matched by the host pattern. Each task executes a module with specific arguments. When a task has executed on all target machines, Ansible moves on to the next task. You can use strategies to change this default behavior. Within each play, Ansible applies the same task directives to all hosts. If a task fails on a host, Ansible takes that host out of the rotation for the rest of the playbook.
When you run a playbook, Ansible returns information about connections, the name lines of all your plays and tasks, whether each task has succeeded or failed on each machine, and whether each task has made a change on each machine. At the bottom of the playbook execution, Ansible provides a summary of the nodes that were targeted and how they performed. General failures and fatal “unreachable” communication attempts are kept separate in the counts.
Desired state and ‘idempotency’
Most Ansible modules check whether the desired final state has already been achieved, and exit without performing any actions if that state has been achieved, so that repeating the task does not change the final state. Modules that behave this way are often called ‘idempotent.’ Whether you run a playbook once, or multiple times, the outcome should be the same. However, not all playbooks and not all modules behave this way. If you are unsure, test your playbooks in a sandbox environment before running them multiple times in production.
Running playbooks
To run your playbook, use the ansible-playbook command.
Ansible-Pull
Should you want to invert the architecture of Ansible, so that nodes check in to a central location, instead of pushing configuration out to them, you can.
The ansible-pull is a small script that will checkout a repo of configuration instructions from git, and then run ansible-playbook against that content.
Assuming you load balance your checkout location, ansible-pull scales essentially infinitely.
There’s also a clever playbook available to configure ansible-pull via a crontab from push mode.
Verifying playbooks
ansible-lint
You can use ansible-lint for detailed, Ansible-specific feedback on your playbooks before you execute them. For example, if you run ansible-lint on the playbook called verify-apache.yml near the top of this page, you should get the following results:
Learn how to test Ansible Playbooks syntax
Learn about YAML syntax
Tips for managing playbooks in the real world
Browse existing collections, modules, and plugins
Learn to extend Ansible by writing your own modules
Learn about how to select hosts
Complete end-to-end playbook examples
Questions? Help? Ideas? Stop by the list on Google Groups
© Copyright Ansible project contributors. Last updated on Dec 21, 2021.
Intro to Playbooks¶
About Playbooks¶
Playbooks are a completely different way to use ansible than in adhoc task execution mode, and are particularly powerful.
Simply put, playbooks are the basis for a really simple configuration management and multi-machine deployment system, unlike any that already exist, and one that is very well suited to deploying complex applications.
Playbooks can declare configurations, but they can also orchestrate steps of any manual ordered process, even as different steps must bounce back and forth between sets of machines in particular orders. They can launch tasks synchronously or asynchronously.
While you might run the main /usr/bin/ansible program for ad-hoc tasks, playbooks are more likely to be kept in source control and used to push out your configuration or assure the configurations of your remote systems are in spec.
There are also some full sets of playbooks illustrating a lot of these techniques in the ansible-examples repository. We’d recommend looking at these in another tab as you go along.
There are also many jumping off points after you learn playbooks, so hop back to the documentation index after you’re done with this section.
Playbook Language Example¶
Playbooks are expressed in YAML format (see YAML Syntax ) and have a minimum of syntax, which intentionally tries to not be a programming language or script, but rather a model of a configuration or a process.
Each playbook is composed of one or more ‘plays’ in a list.
The goal of a play is to map a group of hosts to some well defined roles, represented by things ansible calls tasks. At a basic level, a task is nothing more than a call to an ansible module (see About Modules ).
By composing a playbook of multiple ‘plays’, it is possible to orchestrate multi-machine deployments, running certain steps on all machines in the webservers group, then certain steps on the database server group, then more commands back on the webservers group, etc.
“plays” are more or less a sports analogy. You can have quite a lot of plays that affect your systems to do different things. It’s not as if you were just defining one particular state or model, and you can run different plays at different times.
For starters, here’s a playbook that contains just one play:
When working with tasks that have really long parameters or modules that take many parameters, you can break tasks items over multiple lines to improve the structure. Below is another version of the above example but using YAML dictionaries to supply the modules with their key=value arguments.:
Playbooks can contain multiple plays. You may have a playbook that targets first the web servers, and then the database servers. For example:
You can use this method to switch between the host group you’re targeting, the username logging into the remote servers, whether to sudo or not, and so forth. Plays, like tasks, run in the order specified in the playbook: top to bottom.
Below, we’ll break down what the various features of the playbook language are.
Basics¶
Hosts and Users¶
For each play in a playbook, you get to choose which machines in your infrastructure to target and what remote user to complete the steps (called tasks) as.
The hosts line is a list of one or more groups or host patterns, separated by colons, as described in the Patterns documentation. The remote_user is just the name of the user account:
Remote users can also be defined per task:
The remote_user parameter for tasks was added in 1.4.
Support for running things as another user is also available (see Become (Privilege Escalation) ):
You can also use become on a particular task instead of the whole play:
The become syntax deprecates the old sudo/su specific syntax beginning in 1.9.
You can also login as you, and then become a user different than root:
You can also use other privilege escalation methods, like su:
Tasks list¶
Each play contains a list of tasks. Tasks are executed in order, one at a time, against all machines matched by the host pattern, before moving on to the next task. It is important to understand that, within a play, all hosts are going to get the same task directives. It is the purpose of a play to map a selection of hosts to tasks.
When running the playbook, which runs top to bottom, hosts with failed tasks are taken out of the rotation for the entire playbook. If things fail, simply correct the playbook file and rerun.
The goal of each task is to execute a module, with very specific arguments. Variables, as mentioned above, can be used in arguments to modules.
Modules should be idempotent, that is, running a module multiple times in a sequence should have the same effect as running it just once. One way to achieve idempotency is to have a module check whether its desired final state has already been achieved, and if that state has been achieved, to exit without performing any actions. If all the modules a playbook uses are idempotent, then the playbook itself is likely to be idempotent, so re-running the playbook should be safe.
Tasks can be declared using the legacy action: module options format, but it is recommended that you use the more conventional module: options format. This recommended format is used throughout the documentation, but you may encounter the older format in some playbooks.
Here is what a basic task looks like. As with most modules, the service module takes key=value arguments:
The command and shell modules are the only modules that just take a list of arguments and don’t use the key=value form. This makes them work as simply as you would expect:
The command and shell module care about return codes, so if you have a command whose successful exit code is not zero, you may wish to do this:
If the action line is getting too long for comfort you can break it on a space and indent any continuation lines:
Variables can be used in action lines. Suppose you defined a variable called vhost in the vars section, you could do this:
Those same variables are usable in templates, which we’ll get to later.
Now in a very basic playbook all the tasks will be listed directly in that play, though it will usually make more sense to break up tasks using the include: directive. We’ll show that a bit later.
Action Shorthand¶
Ansible prefers listing modules like this in 0.8 and later:
You will notice in earlier versions, this was only available as:
The old form continues to work in newer versions without any plan of deprecation.
Handlers: Running Operations On Change¶
As we’ve mentioned, modules should be idempotent and can relay when they have made a change on the remote system. Playbooks recognize this and have a basic event system that can be used to respond to change.
These ‘notify’ actions are triggered at the end of each block of tasks in a play, and will only be triggered once even if notified by multiple different tasks.
For instance, multiple resources may indicate that apache needs to be restarted because they have changed a config file, but apache will only be bounced once to avoid unnecessary restarts.
Here’s an example of restarting two services when the contents of a file change, but only if the file changes:
The things listed in the notify section of a task are called handlers.
Handlers are lists of tasks, not really any different from regular tasks, that are referenced by a globally unique name, and are notified by notifiers. If nothing notifies a handler, it will not run. Regardless of how many tasks notify a handler, it will run only once, after all of the tasks complete in a particular play.
Here’s an example handlers section:
As of Ansible 2.2, handlers can also “listen” to generic topics, and tasks can notify those topics as follows:
This use makes it much easier to trigger multiple handlers. It also decouples handlers from their names, making it easier to share handlers among playbooks and roles (especially when using 3rd party roles from a shared source like Galaxy).
Roles are described later on, but it’s worthwhile to point out that:
If you ever want to flush all the handler commands immediately though, in 1.2 and later, you can:
In the above example any queued up handlers would be processed early when the meta statement was reached. This is a bit of a niche case but can come in handy from time to time.
Executing A Playbook¶
Now that you’ve learned playbook syntax, how do you run a playbook? It’s simple. Let’s run a playbook using a parallelism level of 10:
Ansible-Pull¶
Should you want to invert the architecture of Ansible, so that nodes check in to a central location, instead of pushing configuration out to them, you can.
The ansible-pull is a small script that will checkout a repo of configuration instructions from git, and then run ansible-playbook against that content.
Assuming you load balance your checkout location, ansible-pull scales essentially infinitely.
There’s also a clever playbook available to configure ansible-pull via a crontab from push mode.
Tips and Tricks¶
Look at the bottom of the playbook execution for a summary of the nodes that were targeted and how they performed. General failures and fatal “unreachable” communication attempts are kept separate in the counts.
Ansible playbook output is vastly upgraded if the cowsay package is installed. Try it!
To see what hosts would be affected by a playbook before you run it, you can do this:
YAML Syntax Learn about YAML syntax Best Practices Various tips about managing playbooks in the real world Ansible Documentation Hop back to the documentation index for a lot of special topics about playbooks About Modules Learn about available modules Developing Modules Learn how to extend Ansible by writing your own modules Patterns Learn about how to select hosts Github examples directory Complete end-to-end playbook examples Mailing List Questions? Help? Ideas? Stop by the list on Google Groups
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 Playbooks
В инструкции описано применение и работа с Ansible Playbook, а также кратко рассмотрена их структура.
Что такое Ansible Playbooks?
Playbook в Ansible определяет серию некоторых действий для выполнения и адресованы определенным наборам серверов. В отличие от некоторых других инструментов для выполнения настроек, Playbook не описывает состояние машины, а Ansible самостоятельно определяет все изменения, которые необходимо внести. Тем не менее, плейбуки должны быть разработаны как идемпотенты, а это значит, что они могут запускаться более одного раза без негативных последствий.
Например, следующий playbook будет входить на все серверы группы marketingservers и обеспечивать запуск веб-сервера Apache:
В плейбуке выше приведен пример задания (task):
Каждое задание должно иметь имя, которое впоследствии регистрируется и может помочь отслеживать прогресс. После строки имени (name) находится модуль, который будет запущен, в данном случае это служебный модуль. Другие атрибуты разрешают больше опций, в примере Ansible разрешается использовать привилегии sudo.
Запуск Ansible Playbook
Запустить готовый плейбук можно используя следующую команду:
Однако, если есть необходимость отфильтровать список хостов, чтобы сценарий применялся только к одному из этих хостов, можно добавить флаг и указать подмножество хостов в файле:
Регистрация результатов
Когда вы устанавливаете и настраиваете службы вручную, почти всегда необходимо знать результат действий. Настроить эту функциональность можно с помощью регистрации.
Для каждой задачи при желании возможно зарегистрировать ее результат (сбой или успех) в переменной, которую можно проверить позже. При использовании этой функциональности рекомендуется указывать Ansible игнорировать ошибки для такой задачи, так как обычно выполнение playbook прерывается в случае возникновения каких-либо проблем.
Таким образом, если необходимо проверить, выполнилась ли задача или нет и принять решение о последующих шагах, необходимо использовать функциональность регистрации.
🐹 Ansible: Часть 3. Сценарии (плейбуки) — Playbooks.
Опубликовано 2021-04-07 · Обновлено 2021-04-15
Содержание:
На чем было опробовано:
1. Введение.
Официальную документацию с официальными примерами всегда можно почитать на сайте разработчиков Ansible.
Как установить и первоначально настроить Ansible описано здесь:
Так как простые задачи для Ansible реально простые, в буквальном смысле слова, то я принял решение вынести их в отдельную инструкцию:
По данной ссылке я создам небольшую подборку самых интересных и типовых плейбуков, которые могут пригодиться вам в повседневной работе.
Как настраивать защищенные плейбуки описано в этом разделе.
2. Сценарии — playbooks.
Ansible позволяет не только выполнять единичные задачи, но и писать сценарии, которые необходимо выполнить на управляемых узлах.
Рассмотрим структуру и правила написания таких сценариев более подробно.
Все сценарии в Ansible пишутся на YAML — это удобный для человека формат данных, гораздо более простой, чем XML или JSON.
Чтобы выполнить сценарий используется команда ansible-playbook со следующим синтаксисом:
Для Ansible практически каждый YAML файл начинается со списка. Каждый элемент списка — список пар «ключ-значение», часто называемая словарем.
Основными параметрами/группами простого сценария являются:
Также в сценарии перед непосредственным описанием задач могут быть указаны следующие параметры или группы параметров:
Рассмотрим все эти разделы более подробно.
В разделе hosts указывается группа управляемых узлов, к которой будут применены описываемые в сценарии изменения.
Так, строка формата:
Сценарии могут выполняться не только от имени пользователя, под именем которого установлено соединение, но и любого другого.
Если добавить параметр ‘ user: postgres ‘, то все действия будут выполняться с привилегиями пользователя postgres.
В разделе vars указываются переменные, которые будут использованы в сценарии, и их значения:
Далее указываются модули Ansible, которые будут задействованы при ее выполнении:
Для каждой задачи можно указывать пользователя, от имени которого она будет выполнена:
Еще некоторые примеры.
Словарь представлен в виде « ключ: » (двоеточие и пробел) « значение »:
При необходимости словари могут быть представлены в сокращенной форме:
Можно указать логические значение (истина/ложь) так:
Целиком наш пример YAML–файла будет выглядеть так:
Для переменных Ansible использует « << var >> ». Если значение после двоеточия начинается с « < », то YAML будет думать, что это словарь.
Для использования переменных нужно заключить скобки в кавычки:
Этого достаточно для начала написания playbooks.
По данной ссылке я создам небольшую подборку самых интересных и типовых плейбуков, которые могут пригодиться вам в повседневной работе.
3. Обработчики событий — handlers.
4. Контроль выполнения.
Допустим, что при выполнении сценария нам нужно проверять определённые переменные или состояния и, в зависимости от них, выполнять или не выполнять какие-либо задачи.
Для этого можно использовать оператор « when »:
5. Шаблонизация.
В Ansible используется шаблонизатор Jinja2.
Приведём пример шаблона (часть конфигурации powerdns):
В приведённом примере мы подставляем в шаблон следующие значения:
Обработку шаблонов и, в данном случае, генерацию конфигурационного файла выполняет модуль template ; он же может задать необходимые права доступа и изменить владельца/группу:
Внимание! Файл шаблона и файл с паролем пользователя базы данных находятся на машине управления, а результатом будет файл на удалённом узле.
6. Делегирование задачи другому узлу.
Иногда требуется выполнить задачу на определённом узле, но в контексте другого узла.
7. Роли.
Ролью называется типовой набор переменных и задач, назначаемых для одного или нескольких серверов. Если вам нужно применить к серверу или группе серверов типовой набор операций, вам достаточно просто назначить ему роль. Предварительно в проекте каталоге проекта должна быть создана соответствующая структура.
В сценариях роли назначаются следующим образом:
8. Структура проекта.
9. Пишем первые playbook’и.
Playbook может состоять из списка обслуживаемых серверов, переменных пользователя, задач, обработчиков (хендлеров) и так далее. Большинство настроек конфигурации можно переопределить в playbook. Каждый playbook состоит из одного или более действия (игры) в списке.
Цель игры — связать группу хостов с предопределенными ролями, представленными как вызов задач Ansible.
В качестве другого примера давайте рассмотрим процесс установки nginx.
Создадим директорию, где будут хранится playbooks:
Создадим файл setup_nginx.yml в директории playbooks со следующим содержанием:
Давайте рассмотрим содержимое:
Узнать, на каких узлах будет происходить работа, можно командой:
где – путь к вашему playbook ( playbooks/setup_nginx.yml ).
Задача — это список действий, которые вы хотите выполнить. Поле задачи содержит имя задачи (справочная информация о задаче для пользователя playbook), модуль, который должен быть выполнен и аргументы, требуемые для модуля. Параметр « name » может добавляться опционально, но, в целом, рекомендуемый.
10. Пример сценария.
В этом примере первое воспроизведение предназначено для web-серверов, а второе — для серверов баз данных:
11. Практические примеры плейбуков.
По данной ссылке я создам небольшую подборку типовых плейбуков, которые могут пригодиться вам в повседневной работе.
12. Запуск плейбуков.
Чтобы запустить плейбук и выполнить все определенные в нем задачи, используйте команду ansible-playbook:
13. Запрос информации о play.
Точно так же можно запросить все узлы, которые будут затронуты выполнением play, без запуска каких-либо задач на удаленных серверах:
Вы можете использовать теги, чтобы ограничить выполнение play.
14. Управление выполнением плейбука.
Эта опция в качестве аргумента требует правильное имя задачи:
Например, если вы хотите выполнить только задачи, помеченные как nginx или mysql, вы можете использовать:
15. Настройка защищенных плейбуков.
Если ваши плейбуки Ansible содержат конфиденциальные данные, такие как пароли, ключи API и учетные данные, важно обеспечить их безопасность с помощью шифрования. Ansible предоставляет ansible-vault для шифрования файлов и переменных.
Несмотря на то, что любой файл данных Ansible, а также двоичные файлы, возможно зашифровать изначально, чаще для шифрования переменных файлов, содержащих конфиденциальные данные, используется ansible-vault. После шифрования файла с помощью этого инструмента вы сможете выполнять, редактировать или просматривать его, только предоставив соответствующий пароль, указанный при первом шифровании файла.