ansible剧本编写_配置管理101:编写Ansible剧本

本文介绍了使用Ansible进行服务器配置管理,重点讲解了Ansible剧本的编写,包括任务格式、剧本格式、变量使用、循环、条件、模板和处理程序等关键概念,提供了一个全自动化部署Ubuntu 18.04 Apache服务器的剧本示例。
摘要由CSDN通过智能技术生成

ansible剧本编写

介绍 (Introduction)

In a nutshell, server configuration management (also popularly referred to as IT Automation) is a solution for turning your infrastructure administration into a codebase, describing all processes necessary for deploying a server in a set of provisioning scripts that can be versioned and easily reused. It can greatly improve the integrity of any server infrastructure over time.

简而言之,服务器配置管理(通常也称为IT自动化)是一种将基础架构管理转换为代码库的解决方案,它以一组版本控制且易于重用的配置脚本描述了部署服务器所需的所有过程。 随着时间的推移,它可以大大提高任何服务器基础架构的完整性。

In a previous guide, we talked about the main benefits of implementing a configuration management strategy for your server infrastructure, how configuration management tools work, and what these tools typically have in common.

上一指南中 ,我们讨论了为服务器基础结构实施配置管理策略的主要好处,配置管理工具如何工作以及这些工具通常具有什么共同点。

This part of the series will walk you through the process of automating server provisioning using Ansible, a configuration management tool that provides a complete automation framework and orchestration capabilities, while maintaining a goal of ultimate simplicity and minimalism. We will focus on the language terminology, syntax, and features necessary for creating a simplified example to fully automate the deployment of an Ubuntu 18.04 web server using Apache.

本系列的这一部分将引导您完成使用Ansible自动化服务器配置的过程,Ansible是一种配置管理工具,可提供完整的自动化框架和编排功能,同时保持最终的简便性和简约性。 我们将重点介绍创建简化示例以使用Apache完全自动化Ubuntu 18.04 Web服务器的部署所必需的语言术语,语法和功能。

The following list contains all steps we need to automate in order to reach our goal:

以下列表包含实现目标所需的所有自动化步骤:

  1. Update the apt cache

    更新apt缓存

  2. Install Apache

    安装Apache
  3. Create a custom document root directory

    创建一个自定义文档的根目录
  4. Place an index.html file in the custom document root

    index.html文件放在自定义文档的根目录中

  5. Apply a template to set up our custom virtual host

    应用模板来设置我们的自定义虚拟主机
  6. Restart Apache

    重新启动Apache

We’ll start by having a look at the terminology used by Ansible, followed by an overview of the main language features that can be used to write playbooks. At the end of the guide, you’ll find the contents of a full provisioning example to automate the steps described for setting up Apache on Ubuntu 18.04.

我们首先来看看Ansible所使用的术语,然后概述可用于编写剧本的主要语言功能。 在本指南的最后,您将找到完整配置示例的内容,以使在Ubuntu 18.04上设置Apache所描述的步骤自动化。

Note: this guide is intended to get you introduced to the Ansible language and how to write playbooks to automate your server provisioning. For a more introductory view of Ansible, including the steps necessary for installing and getting started with this tool, as well as how to run Ansible commands and playbooks, check our How to Install and Configure Ansible on Ubuntu 18.04 guide.

注意 :本指南旨在向您介绍Ansible语言以及如何编写剧本来自动执行服务器配置。 有关Ansible的更入门介绍,包括安装和开始使用此工具所需的步骤以及如何运行Ansible命令和剧本,请查看我们的《 如何在Ubuntu 18.04上安装和配置Ansible》指南。

入门 (Getting Started)

Before we can move to a more hands-on view of Ansible, it is important that we get acquainted with important terminology and concepts introduced by this tool.

在我们开始对Ansible进行更实际的了解之前,重要的是我们熟悉此工具引入的重要术语和概念。

术语 (Terminology)

The following list contains a quick overview of the most relevant terms used by Ansible:

以下列表简要概述了Ansible使用的最相关的术语:

  • Control Node: the machine where Ansible is installed, responsible for running the provisioning on the servers you are managing.

    控制节点 :安装Ansible的计算机,负责在您管理的服务器上运行配置。

  • Inventory: an INI file that contains information about the servers you are managing.

    库存 :一个INI文件,其中包含有关您管理的服务器的信息。

  • Playbook: a YAML file containing a series of procedures that should be automated.

    Playbook :一个YAML文件,其中包含应自动执行的一系列过程。

  • Task: a block that defines a single procedure to be executed, e.g.: install a package.

    任务 :定义要执行的单个过程的块,例如:安装软件包。

  • Module: a module typically abstracts a system task, like dealing with packages or creating and changing files. Ansible has a multitude of built-in modules, but you can also create custom ones.

    模块 :模块通常抽象一个系统任务,例如处理软件包或创建和更改文件。 Ansible有许多内置模块,但是您也可以创建自定义模块。

  • Role: a set of related playbooks, templates and other files, organized in a pre-defined way to facilitate reuse and share.

    角色 :一组以预定义方式组织的相关剧本,模板和其他文件,以方便重用和共享。

  • Play: a provisioning executed from start to finish is called a play.

    播放 :从头到尾执行的配置称为播放

  • Facts: global variables containing information about the system, like network interfaces or operating system.

    事实 :包含有关系统信息的全局变量,例如网络接口或操作系统。

  • Handlers: used to trigger service status changes, like restarting or reloading a service.

    处理程序 :用于触发服务状态更改,例如重新启动或重新加载服务。

任务格式 (Task Format)

A task defines a single automated step that should be executed by Ansible. It typically involves the usage of a module or the execution of a raw command. This is how a task looks:

任务定义了一个应由Ansible执行的自动化步骤。 它通常涉及模块的使用或原始命令的执行。 这是任务的外观:

- name: This is a task
  apt: name=vim state=latest

The name part is actually optional, but recommended, as it shows up in the output of the provisioning when the task is executed. The apt part is a built-in Ansible module that abstracts the management of packages on Debian-based distributions. This example task tells Ansible that the package vim should have its state changed to latest, which will cause the package manager to install this package in case it is not installed yet.

name部分实际上是可选的,但建议使用,因为它在执行任务时显示在配置的输出中。 apt部分是一个内置的Ansible模块,它抽象了基于Debian的发行版上软件包的管理。 这个例子告诉任务是Ansible包vim应该有它的状态改变为latest ,这将导致软件包管理器安装这个包的情况下,它尚未安装。

剧本格式 (Playbook Format)

Playbooks are YAML files containing a series of directives to automate the provisioning of a server. The following example is a simple playbook that perform two tasks: updates the apt cache and installs vim afterwards:

剧本是YAML文件,其中包含一系列用于自动配置服务器的指令。 下面的示例是一个简单的剧本,它执行两项任务:更新apt缓存并随后安装vim

---
- hosts: all
  become: true
  tasks:
     - name: Update apt-cache 
       apt: update_cache=yes

     - name: Install Vim
       apt: name=vim state=latest

YAML relies on indentation to serialize data structures. For that reason, when writing playbooks and especially when copying examples, you need to be extra careful to maintain the correct indentation.

YAML依靠缩进来序列化数据结构。 因此,在编写剧本时,尤其是在复制示例时,需要格外小心以保持正确的缩进。

Before the end of this guide we will see a more real-life example of a playbook, explained in detail. The next section will give you an overview of the most important elements and features that can be used to write Ansible playbooks.

在本指南结束之前,我们将看到一个更真实的剧本示例,并进行了详细说明。 下一部分将概述可用于编写Ansible剧本的最重要的元素和功能。

写剧本 (Writing Playbooks)

Now that you are familiar with basic terminology and the overal format of playbooks and tasks in Ansible, we’ll learn about some playbook features that can help us creating more versatile automations.

现在您已经熟悉了Ansible的基本术语以及剧本和任务的总体格式,我们将学习一些剧本功能,这些功能可以帮助我们创建更多的自动化功能。

使用变量 (Working with Variables)

There are different ways in which you can define variables in Ansible. The simplest way is by using the vars section of a playbook. The example below defines a variable package that later is used inside a task:

您可以通过多种方式在Ansible中定义变量。 最简单的方法是使用剧本的vars部分。 下面的示例定义了一个变量package ,以后将在任务内部使用它:

---
- hosts: all
  become: true
  vars:
     package: vim
  tasks:
     - name: Install Package
       apt: name={{ package }} state=latest

The package variable has a global scope, which means it can be accessed from any point of the provisioning, even from included files and templates.

package变量具有全局作用域,这意味着可以从供应的任何位置访问它,甚至可以从包含的文件和模板中访问它。

使用循环 (Using Loops)

Loops are typically used to repeat a task using different input values. For instance, instead of creating 10 tasks for installing 10 different packages, you can create a single task and use a loop to repeat the task with all the different packages you want to install.

循环通常用于使用不同的输入值重复执行任务。 例如,您不必创建10个任务来安装10个不同的软件包,而是可以创建一个任务并使用循环对要安装的所有不同软件包重复执行该任务。

To create a loop within a task, include the option with_items with an array of values. The content can be accessed through the loop variable item, as shown in the example below:

要在任务中创建循环,请在选项with_items包含一个值数组。 可以通过循环变量item来访问内容,如以下示例所示:

- name: Install Packages
  apt: name={{ item }} state=latest
  with_items:
     - vim
     - git
     - curl

You can also use an array variable to define your items:

您还可以使用数组变量来定义项目:

---
- hosts: all
  become: true
  vars:
     packages: [ 'vim', 'git', 'curl' ]
  tasks:
     - name: Install Package
       apt: name={{ item }} state=latest
       with_items: "{{ packages }}"

使用条件 (Using Conditionals)

Conditionals can be used to dynamically decide whether or not a task should be executed, based on a variable or an output from a command, for instance.

例如,条件变量可用于基于变量或命令的输出来动态决定是否应执行任务。

The following example will only shutdown Debian based systems:

以下示例将仅关闭基于Debian的系统:

- name: Shutdown Debian Based Systems
  command: /sbin/shutdown -t now
  when: ansible_os_family == "Debian"

The conditional when receives as argument an expression to be evaluated. The task only gets executed in case the expression is evaluated to true. In our example, we tested a fact to check if the operating system is from the Debian family.

条件when接收要计算的表达式作为参数。 仅在表达式计算为true情况下才执行任务。 在我们的示例中,我们测试了一个事实,以检查操作系统是否来自Debian家族。

A common use case for conditionals in IT automation is when the execution of a task depends on the output of a command. With Ansible, the way we implement this is by registering a variable to hold the results of a command execution, and then testing this variable in a subsequent task. We can test for the command’s exit status (if failed or successful). We can also check for specific contents inside the output, although this might require the usage of regex expressions and string parsing commands.

IT自动化中有条件的一个常见用例是任务的执行取决于命令的输出。 使用Ansible,我们实现此目的的方法是注册一个变量以保存命令执行的结果,然后在后续任务中测试此变量。 我们可以测试命令的退出状态(如果失败或成功)。 我们还可以检查输出中的特定内容,尽管这可能需要使用正则表达式和字符串解析命令。

The next example shows two conditional tasks based on the output from a php -v command. We will test for the exit status of the command, since we know it will fail to execute in case PHP is not installed on this server. The ignore_errors portion of the task is important to make sure the provisioning continues even when the command fails execution.

下一个示例根据php -v命令的输出显示了两个条件任务。 我们将测试命令的退出状态,因为我们知道如果未在该服务器上安装PHP,则该命令将无法执行。 任务的ignore_errors部分对于确保即使命令执行失败也能继续进行配置很重要。

- name: Check if PHP is installed
  register: php_installed
  command: php -v
  ignore_errors: true

- name: This task is only executed if PHP is installed
  debug: var=php_install
  when: php_installed|success

- name: This task is only executed if PHP is NOT installed
  debug: msg='PHP is NOT installed'
  when: php_installed|failed

The debug module used here is a useful module for showing contents of variables or debug messages. It can either print a string (when using the msg argument) or print the contents of a variable (when using the var argument).

此处使用的debug模块是一个有用的模块,用于显示变量或调试消息的内容。 它可以打印字符串(使用msg参数时)或打印变量的内容(使用var参数时)。

使用模板 (Working with Templates)

Templates are typically used to set up configuration files, allowing for the use of variables and other features intended to make these files more versatile and reusable. Ansible uses the Jinja2 template engine.

模板通常用于设置配置文件,从而允许使用变量和其他功能,以使这些文件更加通用和可重复使用。 Ansible使用Jinja2模板引擎。

The following example is a template for setting up an Apache virtual host, using a variable for setting up the document root for this host:

以下示例是用于设置Apache虚拟主机的模板,该模板使用变量来为此主机设置文档根目录:

<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    DocumentRoot {{ doc_root }}

    <Directory {{ doc_root }}>
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

The built-in module template is used to apply the template from a task. If you named the template file above vhost.tpl, and you placed it in the same directory as your playbook, this is how you would apply the template to replace the default Apache virtual host:

内置模块template用于从任务中应用模板。 如果您在vhost.tpl上方命名了模板文件,并将其放置在与剧本相同的目录中,则可以通过以下方法应用模板来替换默认的Apache虚拟主机:

- name: Change default Apache virtual host
  template: 
    src: vhost.tpl
    dest: /etc/apache2/sites-available/000-default.conf

定义和触发处理程序 (Defining and Triggering Handlers)

Handlers are used to trigger a state change in a service, such as a restart or a stop. Even though they might look fairly similar to regular tasks, handlers are only executed when previously triggered from a notify directive in a task. They are typically defined as an array in a handlers section of the playbook, but they can also live in separate files.

处理程序用于触发服务中的状态更改,例如重新启动停止 。 尽管它们看起来与常规任务非常相似,但仅在先前从任务中的notify指令触发时才执行处理程序。 它们通常在剧本的handlers部分中定义为数组,但它们也可以存在于单独的文件中。

Let’s take into consideration our previous template usage example, where we set up an Apache virtual host. If you want to make sure Apache is restarted after a virtual host change, you first need to create a handler for the Apache service. This is how handlers are defined inside a playbook:

让我们考虑之前的模板用法示例,在该示例中,我们设置了Apache虚拟主机。 如果要确保在更改虚拟主机后重新启动Apache,则首先需要为Apache服务创建处理程序。 这是在剧本中定义处理程序的方式:

handlers:
    - name: restart apache
      service: name=apache2 state=restarted

    - name: other handler
      service: name=other state=restarted

The name directive here is important because it will be the unique identifier of this handler. To trigger this handler from a task, you should use the notify option:

这里的name指令很重要,因为它将是此处理程序的唯一标识符。 要从任务触发此处理程序,应使用notify选项:

- name: Change default Apache virtual host
  template: 
    src: vhost.tpl
    dest: /etc/apache2/sites-available/000-default.conf
  notify: restart apache

We’ve seen some of the most important features you can use to begin writing Ansible playbooks. In the next section, we’ll dive into a more real-life example of a playbook that will automate the installation and configuration of Apache on Ubuntu.

我们已经看到了一些最重要的功能,您可以用来开始编写Ansible剧本。 在下一节中,我们将深入探讨一个真实的剧本示例,该示例将在Ubuntu上自动执行Apache的安装和配置。

剧本范例 (Example Playbook)

Now let’s have a look at a playbook that will automate the installation of an Apache web server within an Ubuntu 18.04 system, as discussed in this guide’s introduction.

现在,让我们看一看剧本,该剧本将在Ubuntu 18.04系统中自动安装Apache Web服务器,如本指南的简介中所述。

The complete example, including the template file for setting up Apache and an HTML file to be served by the web server, can be found on Github. The folder also contains a Vagrantfile that lets you test the playbook in a simplified setup, using a virtual machine managed by Vagrant.

可以在Github上找到完整的示例,包括用于设置Apache的模板文件和由Web服务器提供服务HTML文件。 该文件夹还包含一个Vagrantfile,可让您使用Vagrant管理的虚拟机以简化的设置测试剧本。

剧本内容 (Playbook Contents)

The full contents of the playbook are available here for your convenience:

为方便起见,可在此处找到该手册的全部内容:

playbook.yml
playbook.yml
  • ---

    ---
  • - hosts: all

    -主持人:全部
  • become: true

    成为:真实
  • vars:

    vars:
  • doc_root: /var/www/example

    doc_root:/ var / www / example
  • tasks:

    任务:
  • - name: Update apt

    -名称:更新apt
  • apt: update_cache=yes

    apt:update_cache =是
  • - name: Install Apache

    -名称:安装Apache
  • apt: name=apache2 state=latest

    apt:名称= apache2状态=最新
  • - name: Create custom document root

    -名称:创建自定义文档根
  • file: path={{ doc_root }} state=directory owner=www-data group=www-data

    文件:路径= {{doc_root}}状态=目录所有者= www-数据组= www-数据
  • - name: Set up HTML file

    -名称:设置HTML文件
  • copy: src=index.html dest={{ doc_root }}/index.html owner=www-data group=www-data mode=0644

    复制:src = index.html dest = {{doc_root}} / index.html owner = www-data group = www-data mode = 0644
  • - name: Set up Apache virtual host file

    -名称:设置Apache虚拟主机文件
  • template: src=vhost.tpl dest=/etc/apache2/sites-available/000-default.conf

    模板:src = vhost.tpl dest = / etc / apache2 / sites-available / 000-default.conf
  • notify: restart apache

    通知:重新启动Apache
  • handlers:

    处理程序:
  • - name: restart apache

    -名称:重新启动apache
  • service: name=apache2 state=restarted

    服务:名称= apache2状态=重启

Let’s examine each portion of this playbook in more detail:

让我们更详细地研究该剧本的每个部分:

hosts: all The playbook starts by stating that it should be applied to all hosts in your inventory (hosts: all). It is possible to restrict the playbook’s execution to a specific host, or a group of hosts. This option can be overwritten at execution time.

主机:全部剧本首先说明应将其应用于清单中的all主机( hosts: all )。 可以将剧本的执行限制为特定的主机或一组主机。 该选项可以在执行时覆盖。

become: true The become: true portion tells Ansible to use privilege escalation (sudo) for executing all the tasks in this playbook. This option can be overwritten on a task-by-task basis.

成为:true become: true部分告诉Ansible使用特权升级(sudo)来执行此剧本中的所有任务。 可以逐个任务地覆盖此选项。

vars Defines a variable, doc_root, which is later used in a task. This section could contain multiple variables.

vars定义一个变量doc_root ,该变量稍后在任务中使用。 此部分可能包含多个变量。

tasks The section where the actual tasks are defined. The first task updates the apt cache, and the second task installs the package apache2.

任务定义实际任务的部分。 第一个任务更新apt缓存,第二个任务安装软件包apache2

The third task uses the built-in module file to create a directory to serve as our document root. This module can be used to manage files and directories.

第三个任务使用内置的模块文件创建一个目录以用作我们的文档根目录。 该模块可用于管理文件和目录。

The fourth task uses the module copy to copy a local file to the remote server. We’re copying a simple HTML file to be served as our website hosted by Apache.

第四个任务使用模块副本将本地文件复制到远程服务器。 我们正在复制一个简单HTML文件,以作为Apache托管的网站。

handlers Finally, we have the handlers section, where the services are declared. We define the restart apache handler that is notified from the fourth task, where the Apache template is applied.

处理程序最后,我们有handlers部分,其中声明了服务。 我们定义了从第四个任务(应用Apache模板的地方)通知的restart apache处理程序。

运行剧本 (Running a Playbook)

Once you get the contents of this playbook downloaded to your Ansible control node, you can use ansible-playbook to execute it on one or more nodes from your inventory. The following command will execute the playbook on all hosts from your default inventory file, using SSH keypair authentication to connect as the current system user:

一旦将此剧本的内容下载到Ansible控制节点后,就可以使用ansible-playbook在清单中的一个或多个节点上执行它。 以下命令将使用SSH密钥对身份验证以当前系统用户身份连接,从默认清单文件在所有主机上执行剧本:

  • ansible-playbook playbook.yml

    ansible-playbook playbook.yml

You can also use -l to limit execution to a single host or a group of hosts from your inventory:

您还可以使用-l将执行限制为清单中的单个主机或一组主机:

  • ansible-playbook -l host_or_group playbook.yml

    ansible-playbook -l host_or_group playbook.yml

If you need to specify a different SSH user to connect to the remote server, you can include the argument -u user to that command:

如果需要指定其他SSH用户来连接到远程服务器,则可以在该命令中包含参数-u user

  • ansible-playbook -l host_or_group playbook.yml -u remote-user

    ansible-playbook -l host_or_group playbook.yml -u 远程用户

For more information on how to run Ansible commands and playbooks, please refer to our guide on How to Install and Configure Ansible on Ubuntu 18.04.

有关如何运行Ansible命令和剧本的更多信息,请参阅我们的有关如何在Ubuntu 18.04上安装和配置Ansible的指南。

结论 (Conclusion)

Ansible is a minimalist IT automation tool that has a low learning curve, using YAML for its provisioning scripts. It has a great number of built-in modules that can be used to abstract tasks such as installing packages and working with templates. Its simplified infrastructure requirements and simple language can be a good fit for those who are getting started with configuration management. It might, however, lack some advanced features that you can find with more complex tools like Puppet and Chef.

Ansible是一种极简主义的IT自动化工具,其学习曲线很低,使用YAML作为其配置脚本。 它具有大量的内置模块,可用于抽象任务,例如安装软件包和使用模板。 其简化的基础架构要求和简单的语言非常适合那些开始进行配置管理的人员。 但是,它可能缺少一些高级功能,而这些功能可以通过更复杂的工具(如Puppet和Chef)找到。

In the next part of this series, we will see a practical overview of Puppet, a popular and well established configuration management tool that uses an expressive and powerful custom DSL based on Ruby to write provisioning scripts.

本系列下一部分中 ,我们将看到Puppet的实用概述,Puppet是一种流行且完善的配置管理工具,它使用基于Ruby的表达能力强大的自定义DSL来编写配置脚本。

翻译自: https://www.digitalocean.com/community/tutorials/configuration-management-101-writing-ansible-playbooks

ansible剧本编写

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值