ansible入门_Ansible入门

ansible入门

The software development industry has grown over the years, from simple software running in one machine to complex systems running on multiple servers in the cloud. Provisioning and managing complex server architecture across different environments can be a challenge. This in most cases is the major cause of product releases and iterations.

从一台机器上运行的简单软件到云中多台服务器上运行的复杂系统,软件开发行业已经发展了多年。 在不同环境中配置和管理复杂的服务器体系结构可能是一个挑战。 在大多数情况下,这是产品发布和迭代的主要原因。

The traditionally we would manually provision servers, install all the dependencies, then launch software in them. This approach has its flaws. Assuming that your infrastructure gets corrupted or fails, to spin new servers you will have to go through the same painful process all over again. Frustrating right? Introducing IaC infrastructure as Code.

传统上,我们将手动设置服务器,安装所有依赖项,然后在其中启动软件。 这种方法有其缺陷。 假设您的基础架构已损坏或发生故障,要旋转新服务器,您将不得不再次经历相同的痛苦过程。 令人沮丧吧? 将IaC基础架构引入Code。

基础架构即代码。 ( Infrastructure As Code. )

Infrastructure as Code (IaC) is the process of managing and provisioning computing and networking infrastructure and their configuration through machine-processable definition files (Code), rather than physical hardware configuration or the use of interactive configuration tools. Such files can be kept in source control to allow audibility and reproducible builds, subject to testing practices, and the full discipline of continuous delivery.

基础架构即代码(IaC)是通过计算机可处理的定义文件(代码)而不是物理硬件配置或使用交互式配置工具来管理和配置计算和网络基础架构及其配置的过程。 此类文件可以保留在源代码控制中,以允许可听性和可复制性,并取决于测试实践和连续交付的全部准则。

There are many tools that are used to achieve this such as terraform, Puppet, Chef, Ansible etc. However, in this article, we will be looking into Ansible.

有许多工具可用于实现此目的,例如terraformPuppetChefAnsible等。但是,在本文中,我们将研究Ansible。

什么是Ansible? ( What Is Ansible? )

Ansible is an open source automation platform that is used for configuration management, application deployment, task automation e.t.c. It can also do IT orchestration to run tasks in sequence and create a chain of events which must happen on several different servers or devices. In simple terms, Ansible enables you to define your infrastructure as code in a simple declarative manner.

Ansible是一个开源自动化平台,用于配置管理,应用程序部署,任务自动化等。它还可以进行IT编排,以按顺序运行任务并创建必须在多个不同服务器或设备上发生的事件链。 简单来说,Ansible使您能够以简单的声明方式将基础架构定义为代码。

为什么使用Ansible? ( Why Use Ansible? )

When it comes to choosing any tool, there is always the question, Why should I use it? What is the deal breaker? There are many reasons why you would choose Ansible as you configuration management tools. Here are some of them.

在选择任何工具时,总会有一个问题,为什么要使用它? 什么是交易破坏者? 选择Ansible作为配置管理工具的原因有很多。 这里是其中的一些。

它是无代理的。 (It is agentless.)

As compared to Chef or Puppet, Ansible does not make use of the agent in the remote host rather it makes use of ssh to manage and provision systems. This a good news since you don't have to configure anything on the host before you can use it. This approach makes it easier to set up and to use.

ChefPuppet相比,Ansible不使用远程主机中的代理,而是使用ssh来管理和配置系统。 这是个好消息,因为您无需在主机上进行任何配置即可使用它。 这种方法使设置和使用更加容易。

并行执行。 (Parallel execution.)

Ansible makes use the ad-hoc mode to run shell commands across multiple machines. This can come in handy if you are provisioning many servers. This reduces provision time make it easier and faster to replicate your infrastructure.

Ansible使用ad-hoc模式在多台机器上运行shell命令。 如果要配置许多服务器,这可能会派上用场。 这减少了配置时间,使复制基础架构变得更加轻松快捷。

自动报告。 (Automatic reporting.)

It is recommended to name all the Ansible tasks in a very descriptive manner in your provisioning script. When the script is executed, Ansible will provide descriptive reports whether or not the task succeeded with or without changes. The messages are also coloured providing nice tidy reports.

建议在配置脚本中以描述性的方式命名所有Ansible任务。 执行脚本后,Ansible将提供描述性报告,无论任务是否成功更改(无论是否更改)。 消息也被涂成彩色,以提供整洁的报告。

易于使用。 (Easy to use.)

Ansible uses YAML as its configuration syntax. This makes it easier to the user as compared to using a bash script. Taking into consideration that YAML is easy to learn, therefore reduces the learn curve.

Ansible使用YAML作为其配置语法。 与使用bash脚本相比,这使用户更容易。 考虑到YAML易于学习,因此减少了学习曲线。

关注点分离 (Separation of concern)

Ansible has been designed to be modular in nature. With the use of roles, we can build components to accomplish specific tasks. This approach makes it easy to modify playbooks without affecting the general execution of the playbooks. Besides we can easily reuse this component in other setups thus reducing duplication.

Ansible已被设计为本质上是模块化的。 通过使用角色,我们可以构建组件来完成特定任务。 这种方法使修改剧本变得容易,而又不影响剧本的一般执行。 此外,我们可以轻松地在其他设置中重用此组件,从而减少重复。

可测试 (It is Testable)

Did I just mention tests? Yes, Ansible playbooks can be tested. We have adopted TDD in many of our software development workflows, but with Ansible, we can introduce TDD to develops. Apart from checking for syntax, you can write tests to check if the servers are being provisioned and-and have all the required dependencies.

我刚才提到测试吗? 是的,可以测试Ansible剧本。 我们在许多软件开发工作流程中都采用了TDD,但是借助Ansible,我们可以将TDD引入开发中。 除了检查语法外,您还可以编写测试来检查服务器是否已配置和-是否具有所有必需的依赖关系。

What we have mentioned above are few among many reasons why Ansible is awesome and why you should start using it right away. If you are reading this article there is a chance you have already decided to use it or you are looking to learn to use it. Worry not by the end of this article you should have enough information to get you started.

我们上面提到的是Ansible令人赞叹的诸多原因中的少数,以及为什么您应该立即开始使用它。 如果您正在阅读本文,则有可能您已经决定使用它,或者正在寻找学习使用它的机会。 不用担心,在本文结尾处,您应该没有足够的信息来入门。

Ansible基本概念 ( Ansible Basic Concepts )

In this article, we are looking to cover the key concepts that you should know to get started with Ansible. I will not be diving deeper into these concepts rather I will be providing guidelines and to get you going. This means it will be up to you to take the extra step to practice and research in these concepts. Nothing beats practice!

在本文中,我们希望涵盖开始使用Ansible时应了解的关键概念。 我不会更深入地研究这些概念,而是会提供指导并帮助您前进。 这意味着您将需要采取额外的步骤来实践和研究这些概念。 没有什么比练习更重要的了!

Here are the concepts we will be looking into. It is important that you get to understand them, how they are used and why. If you need more information, you can reference Ansible documentation - Which is awesome by the way.

这是我们将要研究的概念。 重要的是要了解它们,如何使用它们以及为什么。 如果需要更多信息,可以参考Ansible文档 - 太好了。

库存 ( Inventory )

Ansible works against multiple systems in your infrastructure at the same time. It does this by selecting portions of systems listed in Ansible’s inventory file, which defaults to being saved in the location /etc/ansible/hosts.

Ansible可同时针对基础架构中的多个系统工作。 它通过选择Ansible清单文件中列出的系统部分来完成此操作,该文件默认保存在/etc/ansible/hosts

Through inventory files, you can specify meaningful groups of hosts that Ansible will provision. You also can specify group variables or host variables that will help to control how Ansible interacts with remote hosts and they will be available later in playbooks.

通过清单文件,您可以指定Ansible将提供的有意义的主机组。 您还可以指定组变量或主机变量,这将有助于控制Ansible与远程主机的交互方式,它们将在以后的剧本中提供。

Below is an example of an inventory file specify a group of hosts that Ansible will provision.

以下是清单文件的示例,该文件指定了Ansible将提供的一组主机。

[webservers]
web.one.com
web.two.com

[dbservers]
db.one.com
db.two.com
db.three.com

The headings in brackets [] are group names, which are used in classifying systems and deciding what systems you are controlling at what time and for what purpose. It is ok to put systems in more than one group, for instance, a server could be both a web server and a DB server, as showcased in the example above.

括号[]中的标题是组名,用于对系统进行分类并确定您在什么时候,什么目的控制什么系统。 可以将系统放在多个组中,例如,服务器可以既是Web服务器又是DB服务器,如上例所示。

模组 ( Modules )

Ansible ships with a number of modules (called the ‘module library’) that can be executed directly on remote hosts or through playbooks. These modules can control system resources, like services, packages, or files (anything really), or handle executing system commands.

Ansible附带了许多模块(称为“模块库”),可以直接在远程主机上或通过剧本执行。 这些模块可以控制系统资源,例如服务,程序包或文件(实际上是任何东西),或处理执行系统命令。

Modules use available context ("Facts") to determine what actions to execute, based on the state of the host machine. As we mentioned earlier, Ansible is idempotent, by using existing context, Ansible modules can determine if a task is to be executed or not. This ensures that not matter how many times you run Ansible scripts they will always remain in the same state. A good example is an apt module.

模块根据主机的状态使用可用的上下文(“事实”)来确定要执行的操作。 如前所述,Ansible是幂等的,通过使用现有上下文,Ansible模块可以确定是否要执行任务。 这样可以确保无论您运行Ansible脚本多少次,它们都将始终保持相同状态。 apt模块就是一个很好的例子。

Let us look at an example for installing Nginx and updating system cache.

让我们看一个安装Nginx和更新系统缓存的示例。

sudo apt-get install nginx
sudo apt-get update

The above commands through the use of apt module can be translated to:

上面的命令通过使用apt模块可以翻译为:

...
- name: Update repositories cache and install "nginx" package
  apt:
    name: nginx
    update_cache: yes
...

The above task will only install Nginx once as compared to the actual command that will install it even though it exists.

与安装Nginx的实际命令相比,以上任务仅会安装一次,即使该命令存在也是如此。

Can I create my own modules? Yeah, why not! Ansible allows accommodates the creation of custom modules, in case you don't find what you are looking for don't despair you can create your own package and use it to your discretion. For more details refer to Ansible modules docs.

我可以创建自己的模块吗? 是的,为什么不呢! Ansible allow可以容纳自定义模块的创建,以防万一您没有找到想要的东西或者不感到失望,可以创建自己的包并酌情使用。 有关更多详细信息,请参阅Ansible模块文档

任务 ( Tasks )

These are actions or steps that define the expected state of the host machine at a particular time. Ansible uses tasks as a way to order actions to be executed when a play is run. They are run sequentially this means that a task will only run when the previous task has been completed. It is recommended to name this tasks in a descriptive manner. As we mentioned above this comes I handy when it comes to reports.

这些是定义主机在特定时间的预期状态的操作或步骤。 Ansible使用任务作为命令,在播放播放时命令要执行的动作。 它们按顺序运行,这意味着仅在上一个任务完成时才运行任务。 建议以描述性方式命名此任务。 正如我们上面提到的,这在报告方面非常方便。

Tasks are mostly used together with modules to accomplish a particular outcome. It is important to note a task can only do one operation at a time. This means one task for one operation. Sometimes a task can do more that one operation through the use of loops.

任务通常与模块一起使用以完成特定的结果。 请务必注意,一项任务一次只能执行一项操作。 这意味着一项操作只能完成一项任务。 有时,通过使用循环,一项任务可以完成一项以上的操作。

The example above in the module section is a good example of a task.

上面模块部分中的示例是一个很好的任务示例。

剧本 ( Playbooks )

Playbooks are Ansible’s configuration, deployment, and orchestration language. They can describe a policy you want your remote systems to enforce or a set of steps in a general IT process. They basically are YAML files that describe the desired state of the host or a group of hosts declared in the inventory file. They are designed to be human-readable and are developed in a basic text language (YAML).

剧本是Ansible的配置,部署和编排语言。 它们可以描述您希望远程系统执行的策略,或者描述一般IT流程中的一组步骤。 它们基本上是YAML文件,用于描述清单文件中声明的主机或一组主机的所需状态。 它们被设计为易于阅读,并以基本文本语言(YAML)开发。

If Ansible modules are the tools in your workshop, playbooks are your instruction manuals, and your inventory of hosts are your raw material. - Ansible docs.

如果Ansible模块是您车间中的工具,则剧本是您的说明手册,主机清单是您的原材料。 -Ansible文档。

At a basic level, playbooks can be used to manage configurations of and deployments to remote machines. However, they can sequence multi-tier rollouts involving rolling updates, delegate actions to other hosts, interacting with monitoring servers and load balancers.

从根本上讲,剧本可用于管理远程计算机的配置和部署。 但是,它们可以按顺序排列多层部署,包括滚动更新,将操作委派给其他主机,与监视服务器和负载平衡器进行交互。

# sample playbook.
---
- hosts: dbservers
  roles:
    - mysql

The playbook above targets hosts under dbservers group and uses the role mysql to provision them. I know you are asking what are roles? We will look into roles in later sections in this article.

上面的剧本以dbservers组下的主机为目标,并使用mysql角色进行配置。 我知道您在问什么角色? 我们将在本文的后续部分中研究角色。

的角色 ( Roles )

While it is possible to write a playbook in one very large file eventually you’ll want to reuse files and start to organise things. Roles in Ansible build on the idea of including files and combining them to form clean, reusable abstractions. This allows you to focus more on the big picture and only dive down into the details when needed.

尽管最终可以在一个非常大的文件中编写一个剧本,但是您将想要重用文件并开始组织事情。 Ansible中的角色基于包含文件并将其组合以形成干净,可重用的抽象的思想。 这样,您可以将更多精力放在全局上,仅在需要时才深入细节。

With this approach, we can build Ansible playbooks that are modular and reusable. It also enables developers to share solutions. If you don't like to reinvent the wheel you can refer to the Ansible-galaxy and explore community roles.

通过这种方法,我们可以构建模块化且可重用的Ansible剧本。 它还使开发人员可以共享解决方案。 如果您不想重新发明轮子,可以参考Ansible星系并探索社区角色。

变数 ( Variables )

Variables is not a new name to you, they are like containers that hold values that can be reused during program execution. While automation exists to make it easier to do repetitive tasks, it is not an excuse for you to repeat yourself.

变量对您来说不是一个新名称,它们就像容器,其中包含可在程序执行期间重用的值。 尽管存在自动化可以使执行重复性任务变得更加容易,但是这并不是您重复自己的借口。

Taking into consideration that all of your systems are not alike, it is also likely that you want to set some behaviour or configuration slightly different from others. In some cases, the state of the system might need to influence how they are configured.

考虑到您的所有系统都不尽相同,因此您可能还希望设置某些行为或配置,使其与其他系统稍有不同。 在某些情况下,系统的状态可能需要影响它们的配置方式。

At times you may want to generate configuration files e.g. Nginx to different servers which vary slightly. Situations like these require variables that can be used to handle these differences.

有时,您可能想生成配置文件(例如Nginx)到不同的服务器上,这些文件会略有不同。 这些情况需要使用变量来处理这些差异。

In Ansible variables are used to deal with differences between systems and to ensure that each system is provisioned based on its state and purpose. You can reference Ansible docs for more details.

在Ansible中,变量用于处理系统之间的差异,并确保根据其状态和目的来配置每个系统。 您可以参考Ansible文档以获取更多详细信息。

Variables can be defined in host_vars/, group_vars/ or vars/ folders under your roles directory. These variables can be used to override existing defaults where necessary.

可以在您的角色目录下的host_vars/group_vars/vars/文件夹中定义vars/ 。 必要时,这些变量可用于覆盖现有默认值。

# group_vars/all.yml
host_name: db.one.com
databases: 4

database_names:
    - cia
    - airforce
    - marine
    - navy

These variables can be used in tasks or templates through the use of curly brackets {{ variable_name }} expressions.

通过使用大括号{{ variable_name }}表达式,可以在任务或模板中使用这些变量。

范本 ( Templates )

Ansible uses Jinja templating to enable dynamic expressions and access to variables. This makes templates a powerful resource that Ansible uses to generate files on the host machines. Ansible has also extended Jinja filters and tests as well as adding new plugins that can be used to dynamically resolve variables while generating files.

Ansible使用Jinja模板来启用动态表达式和访问变量。 这使模板成为Ansible用来在主机上生成文件的强大资源。 Ansible还扩展了Jinja过滤器和测试,并添加了可用于在生成文件时动态解析变量的新插件。

All the templates are placed in templatesfolder and have an extension of .j2 an indication that they are templates, Ansible can process to get a required output. Below is an example of an Ansible template for Nginx.

所有模板都放置在templates文件夹中,扩展名为.j2 ,表示它们是模板,Ansible可以处理以获取所需的输出。 以下是Nginx的Ansible模板的示例。

server {
  listen {{ listen_port }};

  location / {
    return 302 https://$host$request_uri;
  }
}

server {
  listen 443 ssl spdy;
  ssl_certificate    {{ ssl_certificate_path }};
  ssl_certificate_key    {{ ssl_key_path }};
  server_name {{ server_name }} {{ Ansible_eth0.ipv4.address }};
  location / {
    root   {{ web_root }};
    index  index.html index.htm;
  }
}

If we had a Nginx role we can use the above template to generate configuration file as follows:

如果我们具有Nginx角色,则可以使用上面的模板来生成配置文件,如下所示:

- hosts: webservers
  gather_facts: yes
  remote_user: ubuntu
  sudo: yes
  vars:
    ssl_certificate_path: "/etc/ssl/certs/mysite.crt"
    ssl_key_path: "/etc/ssl/private/mysite.key"
    server_name: "www.mysite.com"
    web_root: "/var/www/public"
    listen_port: 443
  roles:
    - nginx

These variables are passed down to the Nginx role tasks which will, in turn, us the template, compile it and copy these file to its appropriate location on the host machine.

这些变量传递给Nginx角色任务,这些任务将依次使用模板,对其进行编译,并将这些文件复制到主机上的适当位置。

有条件的 ( Conditionals )

Often the result of a play may depend on a value of a variable, facts or previous task result. In some cases, the values of variables may depend on other variables. This means that we have to run this tasks only when specific conditions are met. Let take a scenario where we are installing the MySQL database and later creating databases and users. We can only do this once and only when MySQL has been installed and the service is running.

通常,比赛的结果可能取决于变量的值,事实或先前的任务结果。 在某些情况下,变量的值可能取决于其他变量。 这意味着我们仅在满足特定条件时才必须运行此任务。 让我们假设一个场景,我们要安装MySQL数据库,然后再创建数据库和用户。 只有在安装了MySQL并且服务正在运行时,我们才能这样做一次。

Based on the above scenario, first, check if MySQL service is running, register the result and only create users and database when the result returned is Truthy. This is done by using when clause.

根据上述情况,首先,检查MySQL服务是否正在运行,注册结果,并仅在返回的结果为Truthy时创建用户和数据库。 这是通过使用when子句完成的。

When语句。 (The When statement.)

As we have stated above, you might to skip or run tasks only when the certain condition is fulfilled. This could be as simple as installing packages, clean up or database configuration. With when clause in Ansible we can achieve this functionality very easily.

如上所述,您可能仅在满足特定条件时才跳过或运行任务。 这可以像安装软件包,清理或数据库配置一样简单。 使用Ansible中的when子句,我们可以非常轻松地实现此功能。

...

# Create database user
tasks:
    - name: check if MySql is running
    - command: bash -c 'service mysql start'
      register: mysql

    - name: Add user and credentials to the database
      mysql_user:
        name: bob
        password: '*EE0D72C1085C46C5278932678FBE2C6A782821B4'
        encrypted: yes
        priv: '*.*:ALL'
        state: present
     when: mysql|success

In the above example, the mysql_user task will only run if the check for MySQL database returns a zero output. In other words when the task succeeds.

在上面的示例中,仅当MySQL数据库检查返回零输出时,mysql_user任务才会运行。 换句话说,任务成功时。

循环 ( Loops )

In some instances, you’ll want to do many things in one task, install a lot of packages, or repeat a polling step until a certain result is reached. You can do this by doing one task per operation, but this does not scale. So What to we do?

在某些情况下,您可能想在一项任务中做很多事情,安装很多软件包,或重复轮询步骤,直到达到特定结果为止。 您可以通过每个操作执行一项任务来执行此操作,但这不会扩展。 那么我们该怎么办?

Ansible provides us with a way to handle this kind of situation by implementing loops. Through loops, we can install packages or run operations passed to a task as a list.

Ansible通过实施循环为我们提供了一种处理这种情况的方法。 通过循环,我们可以安装软件包或运行作为列表传递给任务的操作。

- name: add several users
  user: name={{ item }} state=present groups=wheel
  with_items:
     - testuser1
     - testuser2

With the example above, Ansible will repeat this task pass until all the two users have been added. The user's names are passed as item to the task.

在上面的示例中,Ansible将重复此任务,直到添加了两个用户为止。 用户名作为item传递给任务。

There are many complex loops you can achieve depending on the situation. Refer to ansible loops docs for more details.

您可以根据情况实现许多复杂的循环。 有关更多详细信息,请参阅ansible循环文档

结论 ( Conclusion )

Ansible is an open-source automation engine that automates cloud provisioning, configuration management, and application deployment. It provides an easy way for us to manage our infrastructure through easy human readable syntax. The concepts we have looked at in the above sections is a mere drop in the ocean, they are only guidelines to get you started. So it is up to you to take the step further and explore what Ansible has to offer.

Ansible是一个开源自动化引擎,可自动执行云配置,配置管理和应用程序部署。 它为我们提供了一种简单的方法,使我们可以通过易于理解的语法来管理基础结构。 我们在以上各节中讨论的概念只是沧海一粟,它们只是使您入门的指南。 因此,您需要进一步采取措施,并探索Ansible提供的服务。

Now that we have understood what Ansible is all about, it is a good time to have some practice. So prepare yourself for hands-on experience in my next article.

现在我们已经了解了Ansible的全部含义,现在是进行一些练习的好时机。 因此,在我的下一篇文章中为实践经验做准备。

翻译自: https://scotch.io/tutorials/getting-started-with-ansible

ansible入门

Run Ansible playbooks to launch complex multi-tier applications hosted in public clouds Key Features Build your learning curve using Ansible Automate cloud, network, and security infrastructures with ease Gain hands-on exposure on Ansible Book Description Ansible has grown from a small, open source orchestration tool to a full-blown orchestration and configuration management tool owned by Red Hat. Its powerful core modules cover a wide range of infrastructures, including on-premises systems and public clouds, operating systems, devices, and services?meaning it can be used to manage pretty much your entire end-to-end environment. Trends and surveys say that Ansible is the first choice of tool among system administrators as it is so easy to use. This end-to-end, practical guide will take you on a learning curve from beginner to pro. You'll start by installing and configuring the Ansible to perform various automation tasks. Then, we'll dive deep into the various facets of infrastructure, such as cloud, compute and network infrastructure along with security. By the end of this book, you'll have an end-to-end understanding of Ansible and how you can apply it to your own environments. What you will learn Write your own playbooks to configure servers running CentOS, Ubuntu, and Windows Identify repeatable tasks and write playbooks to automate them Define a highly available public cloud infrastructure in code, making it easy to distribute your infrastructure configuration Deploy and configure Ansible Tower and Ansible AWX Learn to use community contributed roles Use Ansible in your day-to-day role and projects Who This Book Is For Learn Ansible is perfect for system administrators and developers who want to take their current workflows and transform them into repeatable playbooks using Ansible. No prior knowledge of Ansible is required. Table of Contents An Introduction to Ansible Installing and Running Ansible The Ansible Commands Deploying a LAMP stack Deploying WordPress Targeting Multiple Distributions The core network modules Moving to the Cloud Building out a cloud network Highly Available Cloud Deployments Building out a VMware deployment Ansible Windows Modules Hardening Your Servers Using Ansible and OpenSCAP Deploying WPScan and OWASP ZAP Introducing Ansible Tower and Ansible AWX Ansible Galaxy Next Steps with Ansible Assessments
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值