How to run ansible playbook

How to run ansible playbook

Creating and Running your First Ansible Playbook

How to run ansible playbook. Смотреть фото How to run ansible playbook. Смотреть картинку How to run ansible playbook. Картинка про How to run ansible playbook. Фото How to run ansible playbook

How to run ansible playbook. Смотреть фото How to run ansible playbook. Смотреть картинку How to run ansible playbook. Картинка про How to run ansible playbook. Фото How to run ansible playbook

Playbooks use the YAML format to define one or more plays. A play is a set of ordered tasks that are arranged in a way to automate a process, such as setting up a web server or deploying an application to production.

In a playbook file, plays are defined as a YAML list. A typical play starts off by determining which hosts are the target of that particular setup. This is done with the hosts directive.

Start by creating a new directory on your home folder where you can save your practice playbooks. First, make sure you’re in your Ubuntu user’s home directory. From there, create a directory named ansible-practice and then navigate into that directory with the cd command:

If you followed all prerequisites, you should already have a working inventory file. You can copy that file into your new ansible-practice directory now. For instance, if you created your test inventory file in an ansible directory in your home folder, you could copy the file to the new directory with:

Next, create a new playbook file:

The following playbook defines a play targeting all hosts from a given inventory. It contains a single task to print a debug message.

Note: We’ll learn more about tasks in the next section of this series.

Add the following content to your playbook-01.yml file:

To try this playbook on the server(s) that you set up in your inventory file, run ansible-playbook with the same connection arguments you used when running a connection test within the introduction of this series. Here, we’ll be using an inventory file named inventory and the sammy user to connect to the remote server, but be sure to change these details to align with your own inventory file and administrative user:

You’ll see output like this:

You might have noticed that even though you have defined only one task within your playbook, two tasks were listed in the play output. At the beginning of each play, Ansible executes by default an additional task that gathers information — referred to as facts — about the remote nodes. Because facts can be used on playbooks to better customize the behavior of tasks, the fact-gathering task must happen before any other tasks are executed.

We’ll learn more about Ansible facts in a later section of this series.

Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.

Tutorial Series: How To Write Ansible Playbooks

Ansible is a modern configuration management tool that doesn’t require the use of an agent software on remote nodes, using only SSH and Python to communicate and execute commands on managed servers. This series will walk you through the main Ansible features that you can use to write playbooks for server automation. At the end, we’ll see a practical example of how to create a playbook to automate setting up a remote Nginx web server and deploy a static HTML website to it.

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 Aug 05, 2022.

User Guide

Making Open Source More Inclusive

Red Hat is committed to replacing problematic language in our code, documentation, and web properties. We are beginning with these four terms: master, slave, blacklist, and whitelist. We ask that you open an issue or pull request if you come upon a term that we have missed. For more details, see our CTO Chris Wright’s message.

Welcome to the Ansible User Guide! This guide covers how to work with Ansible, including using the command line, working with inventory, interacting with data, writing tasks, plays, and playbooks; executing playbooks, and reference materials. Quickly find answers in the following sections or expand the table of contents below to scroll through all resources.

Writing tasks, plays, and playbooks

I have a specific use case for a task or play:

Executing tasks with elevated privileges or as a different user with become

Repeating a task once for each item in a list with loops

Executing tasks on a different machine with delegation

Running tasks only when certain conditions apply with conditionals and evaluating conditions with tests

Grouping a set of tasks together with blocks

Running tasks only when something has changed with handlers

Changing the way Ansible handles failures

Working with inventory

I have a list of servers and devices I want to automate. How do I create inventory to track them?

Interacting with data

I want to use a single playbook against multiple systems with different attributes. How do I use variables to handle the differences?

I want to change the data I have, so I can use it in a task. How do I use filters to transform my data?

I need to retrieve data from an external datastore. How do I use lookups to access databases and APIs?

Executing playbooks

Once your playbook is ready to run, you may need to use these topics:

Executing “dry run” playbooks with check mode and diff

Running playbooks while troubleshooting with start and step

Correcting tasks during execution with the Ansible debugger

Controlling how my playbook executes with strategies and more

Running tasks, plays, and playbooks asynchronously

Getting Started: Writing Your First Playbook

August 1, 2017 by John Lieske

How to run ansible playbook. Смотреть фото How to run ansible playbook. Смотреть картинку How to run ansible playbook. Картинка про How to run ansible playbook. Фото How to run ansible playbook

Welcome to another post in our Getting Started series. Keep reading to learn how to draft a Playbook that can be run in Ansible or Ansible Tower. You can also use it along with the Module Index and the other docs to build your own Playbooks later.

What is a Playbook?

Playbooks are essentially sets of instructions (plays) that you send to run on a single target or groups of targets (hosts). Think about the instructions you get for assembling an appliance or furniture. The manufacturer includes instructions so you can put the parts together in the correct order. When followed in order, the furniture looks like what was purchased.

That’s basically how a playbook works.

Modules

The Playbook we’re building will install a web server on a target RHEL/CentOS 7 host, then write an index.html file based on a template file that will reside with the final Playbook. You’ll be able to take the example Playbook and additional files from this blog and test it out for yourself. While going over the example Playbook, we’ll explain the modules that are used.

Authors

The author adds instructions for the modules to run, often with additional values (arguments, locations, etc.). The target host has modules run against it in the order the Playbook lays out (with includes or other additional files). The host’s state is changed (or not) based on the results of the module running, which Ansible and Tower displays in output.

Running Playbooks

Keeping that in mind, you’re still going to need to understand a few things about running Playbooks. With the furniture analogy, a Playbook is shorthand to tell the modules to perform a task. You must understand the following to run your Playbook successfully:

1. The target

2. The tasks

If part of the Playbook needs to start the web server, you’re going to need to know how that’s done so you know to use the service module and start the web server by name. If the Playbook is installing software, then you have to know how installation is done on the target. You’re also still going to need to understand the basics of the tasks being performed. Does the software you’re installing have a configuration setup to it? Are there multiple steps that require conditions or argument values? If there are variables that are being passed, these will all need to be understood by those constructing a Playbook as well.

Example Playbook

We’ll share an example Playbook with a simple play to demonstrate what I’ve explained. The target host will be a RHEL/CentOS 7 base install. There will be a web server installed (NGINX) and then an index.html file will be created in the default webroot. After the install and file tasks are completed the service will be started.
*Note to run this example Playbook with Ansible Tower your inventory and credentials must be configured.

Playbooks start with the YAML three dashes (—) followed by:

Name: good for keeping the Playbooks readable

Hosts: identifies the target for Ansible to run against

Become statements: true statement is included here to ensure nginx installs without a problem (it’s not always required)

On the same indent level as the three prior statements will go the tasks: statement, after which any plays are listed another indent deeper (per YAML nesting). There are two tasks listed but both are using the Yum module. The first Yum task is adding the epel-release repo so that nginx can be installed. Once epel is present Yum is used to install the nginx package.

The state: present statement lets Ansible check the state on the target first before performing any further action. In both cases if the repo or package is already present, Ansible knows it doesn’t have to do any more for this task and continues.

The default install page for nginx is fine if you want to test that nginx installed properly, but you might have a basic html file that you’d like to have as your confirmation. For simplicity, the template index file is in the same directory I’ll run the Playbook from for the example. The destination is simply the default for nginix with no configured sites.

The last thing the Playbook will do is make sure that the nginx service has been started (and if not, start it).

The entire Playbook is about the same length as the introduction paragraph:

Recap

What’s Next

In future posts we’ll be running more complex Playbooks in Tower for deeper examples of functionality, including posts on using dynamic inventory and running jobs against them.

Want to learn more about how Ansible works? Visit our overview page.

ansible-playbook

Runs Ansible playbooks, executing the defined tasks on the targeted hosts.

Synopsis

Description

the tool to run Ansible playbooks, which are a configuration and multinode deployment system. See the project home page (https://docs.ansible.com) for more information.

Common Options

ask for vault password

Become password file

run operations as this user (default=root)

Connection password file

clear the fact cache for every host in inventory

run handlers even if a task fails

outputs a list of matching hosts; does not execute anything else

list all available tags

list all tasks that would be executed

use this file to authenticate the connection

only run plays and tasks whose tags do not match these values

specify common arguments to pass to sftp/scp/ssh (e.g. ProxyCommand)

start the playbook at the task matching this name

one-step-at-a-time: confirm each task before running

perform a syntax check on the playbook, but do not execute it

the vault identity to use

vault password file

show program’s version number, config file location, configured module search path, module location, executable location and exit

don’t make any changes; instead, try to predict some of the changes that may occur

when changing (small) files and templates, show the differences in those files; works great with –check

ask for privilege escalation password

prepend colon-separated path(s) to module library (default=

override the connection timeout in seconds (default=10)

run operations with become (does not imply password prompting)

connection type to use (default=smart)

set additional variables as key=value or YAML/JSON, if filename prepend with @

specify number of parallel processes to use (default=5)

show this help message and exit

specify inventory host path or comma separated host list. –inventory-file is deprecated

ask for connection password

further limit selected hosts to an additional pattern

only run plays and tasks tagged with these values

connect as this user (default=None)

Environment

The following environment variables may be specified.

ANSIBLE_CONFIG – Override the default ansible config file

Many more are available for most options in ansible.cfg

Files

/etc/ansible/ansible.cfg – Config file, used if present

/.ansible.cfg – User config file, overrides the default config if present

Author

Ansible was originally written by Michael DeHaan.

See the AUTHORS file for a complete list of contributors.

License

Ansible is released under the terms of the GPLv3+ License.

See also

ansible(1), ansible-config(1), ansible-console(1), ansible-doc(1), ansible-galaxy(1), ansible-inventory(1), ansible-playbook(1), ansible-pull(1), ansible-vault(1),

© Copyright Ansible project contributors. Last updated on Aug 05, 2022.

Источники информации:

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

Ваш адрес email не будет опубликован. Обязательные поля помечены *