Ansible: up and running pdf download






















We could create a separate ntp role, but then we would have to remember that whenever we apply the web or database role to a host, we have to apply the ntp role as well. What we really want is to have an ntp role that is always applied to a host whenever we apply the web role or the database role. When you define a role, you can specify that it depends on one or more other roles. Ansible will ensure that roles that are specified as dependencies are executed first. For example, if we have a django role for setting up a Django web server, and we want to specify nginx and memcached as dependent roles, then the role metadata file might look like Example Ansible Galaxy If you need to deploy an open source software system onto your hosts, chances are somebody has already written an Ansible role to do it.

Although Ansible does make it easier to write scripts for deploying software, some systems are just plain tricky to deploy. Ansible Galaxy is an open source repository of Ansible roles contributed by the Ansible community. The roles themselves are stored on GitHub. Command-Line Interface The ansible-galaxy command-line tool allows you to download roles from Ansible Galaxy.

This is a role that will configure a host to synchronize its clock with an NTP server. Ansible will install some metadata about the installation to the. Because the roles are hosted on GitHub, you need to have a GitHub account to contribute. At this point, you should have an understanding of how to use roles, how to write your own roles, and how to download roles written by others.

Roles are a great way to organize your playbooks. I use them all the time, and I highly recommend them. This chapter touches on those additional features, which makes it a bit of a grab bag.

Calling django manage. Then add a debug task to print out the variable, and finally a fail clause so that the playbook stops executing, as shown in Example To see what happens the first time, delete the database and then have the playbook re-create it. Idempotent manage. Using filters resembles using Unix pipes, whereby a variable is piped through a filter. Jinja2 ships with a set of built-in filters.

In addition, Ansible ships with its own filters to augment the Jinja2 filters. The Default Filter The default filter is a useful one. However, if the task does fail, we want Ansible to fail for that host after printing the output.

The basename filter will let us extract the index. However, we can write it ourselves. In fact, Hanfei Sun on Stack Overflow covered this very topic. Example shows what the filter implementation looks like.

Lookups In an ideal world, all of your configuration information would be stored as Ansible variables, in the various places that Ansible lets you define variables e. Alas, the world is a messy place, and sometimes a piece of configuration data you need lives somewhere else.

Ansible supports a collection of lookups for retrieving data from different sources. Some of the lookups are shown in Table The first is a string with the name of the lookup, and the second is a string that contains one or more arguments to pass to the lookup. In this section, I provided only a brief overview of lookups that are available. The Ansible documentation provides more details on available lookups and how to use them.

All Ansible lookup plugins execute on the control machine, not the remote host. Example shows how to use the file lookup to read the contents of a file and pass that as a parameter to a module. Say we have a template that looks like Example Assume we have a. In the case of csvfile, the first argument is an entry that must appear exactly once in column 0 the first column, 0-indexed of the table. The other arguments specify the name of the. In our example, we want to look in the file named users.

This evaluates to sue example. DNS works by associating one or more records with a hostname. A TXT record is just an arbitrary string that you can attach to a hostname. You can look up the TXT record by using the dig command-line tool, as shown in Example For example, if there were a second TXT record on ansiblebook. You can use the etcd lookup to retrieve the value of a key.

Although this is the most common way to do loops, Ansible supports other mechanisms for iteration. Table provides a summary of the constructs that are available. Example shows how to iterate over files that end in. You just slap a with at the beginning of a lookup plugin to use it in its loop form.

Loop Controls With version 2. In Example , we would like to loop over multiple tasks at once. However, the vhosts. Use vhost as loop variable - name: run a set of tasks in one loop include: vhosts. In the included task file vhosts. Labeling the Output The label control was added in Ansible 2. Includes The include feature allows you to include tasks or even whole playbooks, depending on where you define an include.

It is often used in roles to separate or even group tasks and task arguments to each task in the included file. Example contains two tasks of a play that share an identical tag, a when condition, and a become argument. Separate tasks into a different file - name: install nginx package: name: nginx - name: ensure nginx is running service: name: nginx state: started enabled: yes Example Depending on the number of operating systems supported by the role, this can lead to a lot of boilerplate for the include tasks.

For example, fact variables see Chapter 4 are not populated when the --list-tasks argument is used. Similarly to the include clause, the mode can be static or dynamic, and Ansible does a best guess as to what is needed. However, we can always append static to enforce the desired mode.

Imagine that in the role dependency, which runs before the main role, a file task changes the owner of a file. But the system user used as the owner does not yet exist at that point. It will be created later in the main role during a package installation. Include and run configure. Blocks Much like the include clause, the block clause provides a mechanism for grouping tasks.

The block clause has an even more interesting application: error handling. Error Handling with Blocks Dealing with error scenarios has always been a challenge. Historically, Ansible has been error agnostic in the sense that errors and failures may occur on a host. With the blocks clause as shown in Example , Ansible advances error handling a bit further and lets us automate recovery and rollback of tasks in case of a failure.

To demonstrate how this can work, we start with a daily business job: upgrading an application. Furthermore, the cloud provides the functionality to snapshot a VM. The simplified playbook looks like the following: 1. Take VM out of the load balancer. Create a VM snapshot before the app upgrade.

Upgrade the application. Run smoke tests. Roll back when something goes wrong. Move VM back to the load balancer. Clean up and remove the VM snapshot. Be careful what you put in the always clause. In case we want to get only upgraded VMs back to the load balancer cluster, the play would look a bit different, as shown in Example This ensures that the two tasks will be executed only if the rescue went through.

As a result, we get only upgraded VMs back to the load balancer. The final playbook looks like Example We dealt with this in Chapter 6 by putting all of the sensitive information in a separate file called secrets. Ansible provides an alternative solution: instead of keeping the secrets. The ansible-vault command-line tool allows you to create and edit an encrypted file that ansible-playbook will recognize and decrypt automatically, given the password.

If that variable is not defined, it defaults to vim. Example shows an example of the contents of a file encrypted using ansible- vault. We do need to tell ansible-playbook to prompt us for the password of the encrypted file, or it will simply error out. This allows you to use a script to provide the password to Ansible. Table shows the available ansible-vault commands. In this chapter, we cover Ansible features that provide customization by controlling which hosts to run against, how tasks are run, and how handlers are run.

Patterns for Specifying Hosts So far, the host parameter in our plays has specified a single host or group, like this: hosts: web Instead of specifying a single host or group, you can specify a pattern. You specify all dev and staging machines as follows: hosts: dev:staging You can specify an intersection by using a colon and ampersand. Note that the regular expression pattern always starts with a tilde. In this case, we want this module to execute on our laptop, not on the remote host.

Assume we have an entry in our inventory named nagios. Sometimes you want to run your task on one host at a time. Typically, you take the application server out of the load balancer, upgrade it, and put it back. You can use the serial clause on a play to tell Ansible to restrict the number of hosts that a play runs on. Example shows an example that removes hosts one at a time from an Amazon EC2 elastic load balancer, upgrades the system packages, and then puts them back into the load balancer.

We cover Amazon EC2 in more detail in Chapter If we had passed 2, Ansible would have run two hosts at a time. Normally, when a task fails, Ansible stops running tasks against the host that fails, but continues to run against other hosts. Otherwise, you might end up with the situation where you have taken each host out of the load balancer, and have it fail, leaving no hosts left inside your load balancer.

Running on a Batch of Hosts at a Time You can also pass serial a percentage value instead of a fixed number. Ansible will apply this percentage to the total number of hosts per play to determine the number of hosts per batch, as shown in Example For example, you might want to run the play on one host first, to verify that the play works as expected, and then run the play on a larger number of hosts in subsequent runs.

A possible use case would be managing a large logical cluster of independent hosts; for example, 30 hosts of a content delivery network CDN. Since version 2.

The list of serial items can be either a number or a percentage, as shown in Example This means that the last serial will be kept and applied to each batch run as long as there are hosts left in the play. Running Only Once Sometimes you might want a task to run only once, even if there are multiple hosts. The default behavior we are already familiar with is the linear strategy.

This is the strategy in which Ansible executes one task on all hosts and waits until the task has completed of failed on all hosts before it executes the next task on all hosts.

As a result, a task takes as much time as the slowest host takes to complete the task. Note the identical order of task results, as host one is always the quickest as it sleeps the least amount of time and host three is the slowest as it sleeps the greatest amount of time.

Free Another strategy available in Ansible is the free strategy. As a result, some hosts will already be configured, while others are still in the middle of the play. If we change the playbook to the free strategy, the output changes as shown in Example As we see in the output in Example , host one is already finished before host three has even finished its first task.

Under certain conditions, a play in strategy free may take less time to finish. Like many core parts in Ansible, strategy is implemented as a new type of plugin.

This subsection describes how you can gain tighter control over when your handlers fire. Handlers in Pre and Post Tasks When we covered handlers, you learned that they are usually executed after all tasks, once, and only when they get notified.

Usually, because this is the default. We do this for two reasons: 1. We would like to clean up some old Nginx vhost data, which we can remove only if no process is using it anymore e. We want to run some smoke tests and validate a health check URL returning OK if the application is in a healthy state. But validating the healthy state before the restart of the services would not make that much sense. Example shows the configuration of the nginx role: the host and port of the health check, a list of vhosts with a name and a template, and some deprecated vhosts that we want to ensure have been removed: Example Clean up and validate health checks after the service restart - name: install nginx yum: pkg: nginx notify: restart nginx - name: configure nginx vhosts template: src: conf.

Note this could be a dynamic page validating that an application has access to a database. Handlers Listen Before Ansible 2. This is simple and works well for most use cases. To notify more handlers to the same event, we just let these additional handlers listen on the same event, and they will also get notified. We cannot notify across plays, with or without handlers listen.

Handlers listen: The SSL case The real benefit of handlers listen is related to role and role dependencies. One of the most obvious use cases I have come across is managing SSL certificates for different services.

It is a simple role whose only purpose is to copy our SSL certificates and keys to the remote host. We have options for overwriting these defaults to make the role copy the files. Every role dependency will run before the parent role. This means in our case that the SSL role tasks will be executed before the nginx role tasks. The nginx role depends on SSL dependencies: - role: ssl Logically, the dependency would be one way: the nginx role depends on the ssl role, as shown in Figure One-way dependency Our nginx role would, of course, handle all aspects of the web server nginx.

Tasks in the nginx role - name: configure nginx template: src: nginx. Handlers in the nginx role - name: restart nginx service: name: nginx state: restarted Restart nginx restarts the Nginx service. Not quite. The SSL certificates need to be replaced once in a while. And when they get replaced, every service consuming an SSL certificate must be restarted to make use of the new certificate. So how should we do that? Notify to restart nginx in the SSL role, I hear you say?

Great, that works! But wait, we just added a new dependency to our SSL role: the nginx role, as shown in Figure Ansible in version 1. This behavior was reimplemented in Ansible version 2. Because we already have an appropriate handler that does the job, we simply append the listen clause to the corresponding handler, as in Example When we look back to our dependency graph, things looks a bit different, as shown in Figure We restored the one-way dependency and are able to reuse the ssl role in other roles just as we use it in the nginx role.

Ansible retrieves the IP address of each host and stores it as a fact. Each network interface has an associated Ansible fact.

The eth0 interface is a private interface whose IP address You can use a callback plugin to do things such as send a Slack message or write an entry to a remote logging server.

Stdout Plugins A stdout plugin controls the format of the output displayed to the terminal. Only a single stdout plugin can be active at a time. Stdout plugins Name Description actionable Show only changed or failed debug Human-readable stderr and stdout default Show default output dense Overwrite output instead of scrolling json JSON output minimal Show task results with minimal formatting oneline Like minimal, but on a single line selective Show only output for tagged tasks skippy Suppress output for skipped hosts actionable The actionable plugin shows output when a task runs against a host only if the task changes the state of the host or fails.

This makes the output less noisy. Permission denied publickey. Please make sure you have the correct access rights and the repository exists. This is useful if you want to process the Ansible output by using a script. Note that this callback will not generate output until the entire playbook has finished executing.

It always shows output for failed tasks. Whereas the default plugin shows skipping: [hostname] when a host is skipped for a task, the skippy plugin suppresses that output. Other Plugins The other plugins perform a variety of actions, such as recording execution time or sending a Slack notification. Table lists these other plugins. Unlike with stdout plugins, you can have multiple other plugins enabled at the same time. Enable the other plugins you want in ansible.

Table lists the environment variables used to configure this plugin. Set to 0 to disable certificate checking. Note that there are no default values for any of the configuration options for the jabber plugin.

These options are listed in Table It is configured by using the environment variables listed in Table The plugin uses the conventions in Table for generating the XML report. The path is not configurable. It is configured with the environment variables listed in Table Table lists the environment variables for this plugin. It has no configuration options. Table lists the environmental variables used for configuration.

This chapter presents strategies for reducing the time it takes Ansible to execute playbooks. In particular, Ansible uses the system SSH program by default. The client and server have to negotiate this connection before you can actually start doing useful work. The negotiation takes a small amount of time.

When Ansible runs a playbook, it makes many SSH connections, in order to do things such as copy over files and run commands. Each time Ansible makes a new SSH connection to a host, it has to pay this negotiation penalty. The master connection stays open for a user-configurable amount of time, and then the SSH client will terminate the connection.

Ansible uses a default of 60 seconds. Ss The first time I ran it, the timing part of the output looked like this:1 0. This tells us it took 0. The second time, the output looked like this: 0. However, I have needed to change the value for the ControlPath option. The workaround is to configure Ansible to use a shorter ControlPath.

The official documentation recommends setting this option in your ansible. Pipelining Recall how Ansible executes a task: 1. It generates a Python script based on the module being invoked. It copies the Python script to the host. It executes the Python script. Ansible supports an optimization called pipelining, whereby it will execute the Python script by piping it to the SSH session instead of copying it.

This saves time because it tells Ansible to use one SSH session instead of two. Enabling Pipelining Pipelining is off by default because it can require some configuration on your remote hosts, but I like to enable it because it speeds up execution.

To enable it, modify your ansible. If fact caching is enabled, Ansible will store facts in a cache the first time it connects to hosts. For subsequent playbook runs, Ansible will look up the facts in the cache instead of fetching them from the remote host, until the cache expires. Example shows the lines you must add to your ansible. If you decide to enable fact caching, make sure you know how quickly the facts used in your playbook are likely to change, and set an appropriate fact-caching timeout value.

If you want to clear the fact cache before running a playbook, pass the --flush-cache flag to ansible-playbook. Setting the gathering configuration option to smart in ansible. This means that Ansible will gather facts only if they are not present in the cache or if the cache has expired. With smart gathering enabled in the configuration file, Ansible will gather facts only if they are not present in the cache.

If the files are present on your system, it will use those files instead of connecting to the host and gathering facts. If the directory does not exist, Ansible will create it.

Redis Fact-Caching Backend Redis is a popular key-value data store that is often used as a cache. To enable fact caching by using the Redis backend, you need to do the following: 1. Install Redis on your control machine. Ensure that the Redis service is running on the control machine. Install the Python Redis package. Modify ansible. Example shows how to configure ansible. If you are using macOS, you can install Redis by using Homebrew.

If you are using Linux, install Redis by using your native package manager. To enable fact caching by using the Memcached backend, you need to do the following: 1. Install Memcached on your control machine. Ensure that the Memcached service is running on the control machine. Install the Python Memcached Python package. You might need to sudo or activate a virtualenv, depending on how you installed Ansible on your control machine.

If you are using macOS, you can install Memcached by using Homebrew. If you are using Linux, install Memcached by using your native package manager.

For more information on fact caching, check out the official documentation. Parallelism For each task, Ansible will connect to the hosts in parallel to execute the tasks. Instead, the level of parallelism is controlled by a parameter, which defaults to 5. You can change this default parameter in one of two ways. While every developer organizes his or her ad hoc scripts in a Later in this chapter, we will learn how to install Ansible on Ubuntu, which will be running inside our guest Vagrant machine.

You can also set up manually using their bundle installation. Run the following commands to This means that you can run the playbook when the VM is started. The Nginx container will automatically start. By the end you will create an entire cluster of virtualized machines, all of which have your applications and all their dependencies installed automatically. Finally, you'll test your Ansible playbooks.

Ansible can do as much or as little as you want it to. Ansible: From Beginner to Pro will teach you the key skills you need to be an Ansible professional. What You Will Learn Learn why Ansible is so popular and how to download and install it Create a playbook that automatically downloads and installs a popular open source project Use open source roles to complete common tasks, and write your own specific to your business Extend Ansible by writing your own modules Test your infrastructure using Test Kitchen and ServerSpec Who This Book Is For Developers that currently create development and production environments by hand.

If you find yourself running apt-get install regularly, this book is for you. Ansible adds reproducibility and saves you time all at once. Ansible: From Beginner to Pro is great for any developer wanting to enhance their skillset and learn new tools. The book covers all aspects of information system design, computer science and technology, general sciences, and educational research.

Upon a double blind review process, a number of high quality papers are selected and collected in the book, which is composed of three different volumes, and covers a variety of topics, including natural language processing, artificial intelligence, security and privacy, communications, wireless and sensor networks, microelectronics, circuit and systems, machine learning, soft computing, mobile computing and applications, cloud computing, software engineering, graphics and image processing, rural engineering, e-commerce, e-governance, business computing, molecular computing, nano-computing, chemical computing, intelligent computing for GIS and remote sensing, bio-informatics and bio-computing.

These fields are not only limited to computer researchers but also include mathematics, chemistry, biology, bio-chemistry, engineering, statistics, and all others in which computer techniques may assist.

This is one of those cases. Updated for new distributions and cloud environments, this comprehensive guide covers best practices for every facet of system administration, including storage management, network design and administration, security, web hosting, automation, configuration management, performance analysis, virtualization, DNS, security, and the management of IT service organizations. The authors—world-class, hands-on technologists—offer indispensable new coverage of cloud platforms, the DevOps philosophy, continuous deployment, containerization, monitoring, and many other essential topics.

Popular Books. Twelve Days of Christmas by Debbie Macomber. Pandemia by Alex Berenson. The Judge's List by John Grisham. In order to use the paramiko connection plugin or modules that require paramiko , install the required module 1 :.

Running pip with sudo will make global changes to the system. Since pip does not coordinate with system package managers, it could make changes to your system that leaves it in an inconsistent or non-functioning state. This is particularly true for macOS. Installing with --user is recommended unless you understand fully the implications of modifying global files on the system. Please make sure you have the latest version of pip before installing Ansible.

Ansible can also be installed inside a new or existing virtualenv :. Starting in version 2. When you upgrade from version 2. If you do not uninstall the older version of Ansible, you will see the following message, and no change will be performed:. As explained by the message, to upgrade you must first remove the version of Ansible installed and then install it to the latest version.

Before installing ansible-core or Ansible 4, you must uninstall ansible-base if you have installed Ansible 3 or ansible-base 2. To upgrade to ansible-core :. Follow these instructions to install the Ansible community package on a variety of operating systems. Ubuntu builds are available in a PPA here.

You may want to use apt-get instead of apt in older versions. Also, be aware that only newer distributions in other words, As of Ansible 4. So to install you can use:. You can also choose a specific version, for example ansible Older versions of FreeBSD worked with something like this substitute for your choice of package manager :. The preferred way to install Ansible on a Mac is with pip. The instructions can be found in Installing and upgrading Ansible with pip. If you are running macOS version It should be noted that pip must be run as a module on macOS, and the linked pip instructions will show you how to do that.

If you are installing on macOS Mavericks A workaround is to do the following:. Also see the Ansible page on the ArchWiki. Ansible build script is available in the SlackBuilds.

Can be built and installed using sbopkg. Build and install packages from a created queuefile answer Q for question if sbopkg should use queue or package :. See Can Ansible run on Windows? In Ansible 2. This code is also known as ansible-core. New features are added to ansible-core on a branch called devel. If you are testing new features, fixing bugs, or otherwise working with the development team on changes to the core code, you can install and run devel.

You should only install and run the devel branch if you are modifying ansible-core or trying out features under development. If you want to use Ansible AWX as the control node, do not install or run the devel branch of Ansible. Use an OS package manager like apt or yum or pip to install a stable version. If you are running Ansible from source, you may also wish to follow the Ansible GitHub project.



0コメント

  • 1000 / 1000