如何在Ubuntu 18.04上使用Ansible自动化初始服务器设置

news/2024/7/7 9:39:28

介绍 (Introduction)

Server automation now plays an essential role in systems administration, due to the disposable nature of modern application environments. Configuration management tools such as Ansible are typically used to streamline the process of automating server setup by establishing standard procedures for new servers while also reducing human error associated with manual setups.

由于现代应用程序环境具有可处理性,因此服务器自动化现在在系统管理中起着至关重要的作用。 配置管理工具(例如Ansible)通常用于通过为新服务器建立标准过程来简化服务器设置自动化的过程,同时还减少了与手动设置相关的人为错误。

Ansible offers a simple architecture that doesn’t require special software to be installed on nodes. It also provides a robust set of features and built-in modules which facilitate writing automation scripts.

Ansible提供了一种简单的体系结构,不需要在节点上安装特殊软件。 它还提供了一组功能强大的功能和内置模块,可帮助编写自动化脚本。

This guide explains how to use Ansible to automate the steps contained in our Initial Server Setup Guide for Ubuntu 18.04 servers.

本指南说明了如何使用Ansible自动执行针对Ubuntu 18.04服务器的《初始服务器安装指南》中包含的步骤。

先决条件 (Prerequisites)

In order to execute the automated setup provided by the playbook we’re discussing in this guide, you’ll need:

为了执行我们在本指南中讨论的剧本提供的自动设置,您需要:

  • One Ansible control node: an Ubuntu 18.04 machine with Ansible installed and configured to connect to your Ansible hosts using SSH keys. Make sure the control node has a regular user with sudo permissions and a firewall enabled, as explained in our Initial Server Setup guide. To set up Ansible, please follow our guide on How to Install and Configure Ansible on Ubuntu 18.04.

    一个Ansible控制节点 :安装了Ansible并配置为使用SSH密钥连接到您的Ansible主机的Ubuntu 18.04计算机。 确保控制节点具有sudo权限的常规用户并启用了防火墙,如“ 初始服务器设置”指南中所述。 要设置Ansible,请遵循有关如何在Ubuntu 18.04上安装和配置Ansible的指南。

  • One or more Ansible Hosts: one or more remote Ubuntu 18.04 servers.

    一台或多台Ansible主机 :一台或多台远程Ubuntu 18.04服务器。

Before proceeding, you first need to make sure your Ansible control node is able to connect and execute commands on your Ansible host(s). For a connection test, please check step 3 of How to Install and Configure Ansible on Ubuntu 18.04.

在继续之前,您首先需要确保Ansible控制节点能够在Ansible主机上连接并执行命令。 对于连接测试,请检查如何在Ubuntu 18.04上安装和配置Ansible的步骤3。

这本剧本做什么? (What Does this Playbook Do?)

This Ansible playbook provides an alternative to manually running through the procedure outlined in the Ubuntu 18.04 initial server setup guide and the guide on setting up SSH keys on Ubuntu 18.04.

该Ansible手册提供了一种替代方法,可以手动执行Ubuntu 18.04初始服务器设置指南和在Ubuntu 18.04上设置SSH密钥的指南中概述的过程。

Running this playbook will perform the following actions on your Ansible hosts:

运行此剧本将在您的Ansible主机上执行以下操作:

  1. Install aptitude, which is preferred by Ansible as an alternative to the apt package manager.

    安装aptitude ,这是Ansible首选的替代apt软件包管理器的工具。

  2. Create the administrative group wheels and configure it for passwordless sudo.

    创建管理组滚轮,并将其配置为无密码sudo

  3. Create a new sudo user.

    创建一个新的sudo用户。
  4. Copy a local SSH public key and include it in the authorized_keys file for the new administrative user on the remote host.

    复制本地SSH公共密钥,并将其包含在远程主机上新管理用户的authorized_keys文件中。

  5. Disable password-based authentication for the root user.

    禁用root用户的基于密码的身份验证。

  6. Install system packages.

    安装系统软件包。
  7. Configure the UFW firewall to only allow SSH connections and deny any other requests.

    将UFW防火墙配置为仅允许SSH连接并拒绝其他任何请求。

Once the playbook has finished running, you’ll have a new user which you can use to log in to the server.

剧本运行完毕后,您将拥有一个新用户,可用于登录服务器。

如何使用本手册 (How to Use this Playbook)

The first thing you’ll need to do is obtain the initial server setup playbook and its dependencies from the do-community/ansible-playbooks repository. We’ll clone this repository to a local folder inside the Ansible control node.

您需要做的第一件事是从do-community / ansible-playbooks存储库中获取初始服务器设置手册及其依赖项。 我们将将此存储库克隆到Ansible控制节点内的本地文件夹。

If this is your first time using the do-community/ansible-playbooks repository, you should start by cloning the repository to your controller node with:

如果这是您第一次使用do-community/ansible-playbooks存储库,则应首先使用以下命令将存储库克隆到控制器节点:

  • cd ~

    光盘〜
  • git clone https://github.com/do-community/ansible-playbooks.git

    git clone https://github.com/do-community/ansible-playbooks.git
  • cd ansible-playbooks

    cd ansible-playbooks

In case you have cloned this repository before while following a different guide, access your existing ansible-playbooks copy and run a git pull command to make sure you have updated contents:

如果您在遵循其他指南之前已经克隆了此存储库,请访问现有的ansible-playbooks副本并运行git pull命令以确保已更新内容:

  • cd ~/ansible-playbooks

    cd〜/ ansible-playbooks
  • git pull

    git pull

The files we’re interested in are located inside the setup_ubuntu1804 folder, which has the following structure:

我们感兴趣的文件位于setup_ubuntu1804文件夹中,该文件夹具有以下结构:

setup_ubuntu1804
├── playbook.yml
└── vars
    └── default.yml

Here is what each of these files are:

以下是每个文件的含义:

  • vars/default.yml: Variable file for customizing playbook settings.

    vars/default.yml :用于自定义剧本设置的变量文件。

  • playbook.yml: The playbook file, containing the tasks to be executed on the remote server(s).

    playbook.yml :剧本文件,包含要在远程服务器上执行的任务。

We’ll edit the playbook’s variable file to customize its values. Access the setup_ubuntu1804 directory and open the vars/default.yml file using your command line editor of choice:

我们将编辑剧本的变量文件以自定义其值。 访问setup_ubuntu1804目录,并使用选择的命令行编辑器打开vars/default.yml文件:

  • cd setup_ubuntu1804

    cd setup_ubuntu1804
  • nano vars/default.yml

    纳米vars / default.yml

This file contains a few variables that require your attention:

该文件包含一些需要引起您注意的变量:

vars/default.yml
vars / default.yml
---
create_user: sammy
copy_local_key: "{{ lookup('file', lookup('env','HOME') + '/.ssh/id_rsa.pub') }}"
sys_packages: [ 'curl', 'vim', 'git', 'ufw']

The following list contains a brief explanation of each of these variables and how you might want to change them:

以下列表简要说明了每个变量以及如何更改它们:

  • create_user: The name of the sudo user that will be created. In this example, we will be using sammy.

    create_user :将创建的sudo用户的名称。 在此示例中,我们将使用sammy

  • copy_local_key: The path to a local SSH public key file that should be copied to the remote server and added as authorized_key for the new sudo user. The default value uses the lookup plugin to obtain the full path to the default public key for the current system user at the Ansible control node.

    copy_local_key :本地SSH公共密钥文件的路径,该路径应复制到远程服务器并作为新sudo用户的authorized_key添加。 默认值使用lookup插件为Ansible控制节点上的当前系统用户获取默认公共密钥的完整路径。

  • sys_packages: An array containing the list of packages you wish to install on your hosts as part of your initial server setup. In this example, we are going to make sure the packages curl, vim, git and ufw are present.

    sys_packages :一个数组,其中包含您希望在初始服务器设置中安装在主机上的软件包的列表。 在此示例中,我们将确保存在package curlvimgitufw软件包。

Once you’re done updating the variables inside vars/default.yml, save and close this file. If you used nano, do so by pressing CTRL + X, Y, then ENTER.

更新完vars/default.yml的变量后,保存并关闭此文件。 如果您使用过nano ,请按CTRL + XY ,然后按ENTER

You’re now ready to run this playbook on one or more servers. Most playbooks are configured to be executed on every server in your inventory, by default. We can use the -l flag to make sure that only a subset of servers, or a single server, is affected by the playbook. We can also use the -u flag to specify which user on the remote server we’re using to connect and execute the playbook commands on the remote hosts.

现在,您可以在一个或多个服务器上运行此剧本。 默认情况下,大多数剧本配置为在清单中的每台服务器上执行。 我们可以使用-l标志来确保只有一部分服务器或单个服务器受该剧本的影响。 我们还可以使用-u标志来指定用于连接和执行远程主机上的playbook命令的远程服务器上的哪个用户。

To execute the playbook only on server1, connecting as root, you can use the following command:

要仅在以root身份连接的server1上执行剧本,可以使用以下命令:

  • ansible-playbook playbook.yml -l server1 -u root

    ansible-playbook playbook.yml -l server1 -u root

You will get output similar to this:

您将获得类似于以下的输出:


   
Output
PLAY [all] ***************************************************************************************************************************** TASK [Gathering Facts] ***************************************************************************************************************** ok: [server1] TASK [Install Prerequisites] *********************************************************************************************************** changed: [server1] TASK [Make sure we have a 'wheel' group] *********************************************************************************************** changed: [server1] TASK [Allow 'wheel' group to have passwordless sudo] *********************************************************************************** changed: [server1] TASK [Create a new regular user with sudo privileges] ********************************************************************************** changed: [server1] TASK [Set authorized key for remote user] ********************************************************************************************** changed: [server1] TASK [Disable password authentication for root] **************************************************************************************** changed: [server1] TASK [Update apt] ********************************************************************************************************************** changed: [server1] TASK [Install required system packages] ************************************************************************************************ ok: [server1] TASK [UFW - Allow SSH connections] ***************************************************************************************************** changed: [server1] TASK [UFW - Deny all other incoming traffic by default] ******************************************************************************** changed: [server1] PLAY RECAP ***************************************************************************************************************************** server1 : ok=11 changed=9 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0

Note: For more information on how to run Ansible playbooks, check our Ansible Cheat Sheet Guide.

注意 :有关如何运行Ansible剧本的更多信息,请参阅《 Ansible备忘单指南》 。

Once the playbook execution is finished, you’ll be able to log in to the server with:

剧本执行完成后,您将可以通过以下方式登录服务器:

  • ssh sammy@server_host_or_IP

    ssh sammy @ server_host_or_IP

Remember to replace sammy with the user defined by the create_user variable, and server_host_or_IP with your server’s hostname or IP address.

请记住,将sammy替换为create_user变量定义的用户,并将server_host_or_IP替换为服务器的主机名或IP地址。

In case you have changed the copy_local_key variable to point to a custom SSH key (not your current system user’s one), you’ll need to provide an extra parameter specifying the location of its private key counterpart when connecting via SSH as the new user:

如果您已将copy_local_key变量更改为指向自定义SSH密钥(而不是当前系统用户的密钥),则在通过SSH作为新用户连接时,需要提供一个额外的参数来指定其私钥副本的位置:

  • ssh sammy@server_host_or_IP -i ~/.ssh/ansible_controller_key

    ssh sammy @ server_host_or_IP -i〜 / .ssh / ansible_controller_key

After logging in to the server, you can check the UFW firewall’s active rules to confirm that it’s properly configured:

登录到服务器后,您可以检查UFW防火墙的活动规则以确认其配置正确:

  • sudo ufw status

    sudo ufw状态

You should get output similar to this:

您应该获得类似于以下的输出:


   
Output
Status: active To Action From -- ------ ---- OpenSSH ALLOW Anywhere OpenSSH (v6) ALLOW Anywhere (v6)

This means that the UFW firewall has successfully been enabled. Since this was the last task in the playbook, it confirms that the playbook was fully executed on this server.

这意味着UFW防火墙已成功启用。 由于这是剧本中的最后一项任务,因此它确认剧本已在此服务器上完全执行。

剧本内容 (The Playbook Contents)

You can find the initial server setup playbook featured in this tutorial in the ansible-playbooks repository, within the DigitalOcean Community Playbooks. To copy or download the script contents directly, click the Raw button towards the top of each script.

您可以在DigitalOcean社区手册中的ansible-playbooks资料库中找到本教程中介绍的初始服务器设置手册 。 要直接复制或下载脚本内容,请单击每个脚本顶部的Raw按钮。

The full contents of the playbook as well as its associated files are also included here for your convenience.

为了方便起见,此处也包含了剧本的完整内容及其相关文件。

vars / default.yml (vars/default.yml)

The default.yml variable file contains values that will be used within the playbook tasks, such as the name of the user that will be created and the packages that should be installed as part of the initial server setup.

default.yml变量文件包含将在playbook任务中使用的值,例如将创建的用户名以及应作为初始服务器设置的一部分安装的软件包。

vars/default.yml
vars / default.yml
---
create_user: sammy
copy_local_key: "{{ lookup('file', lookup('env','HOME') + '/.ssh/id_rsa.pub') }}"
sys_packages: [ 'curl', 'vim', 'git', 'ufw']

playbook.yml (playbook.yml)

The playbook.yml file is where all tasks from this setup are defined. It starts by defining the group of servers that should be the target of this setup (all), after which it uses become: true to define that tasks should be executed with privilege escalation (sudo) by default. Then, it includes the vars/default.yml variable file to load configuration options.

playbook.yml文件中,定义了此设置中的所有任务。 它首先定义应作为此设置目标的服务器组( all ),然后使用become: true定义默认情况下应以特权升级( sudo )执行任务。 然后,它包含vars/default.yml变量文件以加载配置选项。

playbook.yml
playbook.yml
---
- hosts: all
  become: true
  vars_files:
    - vars/default.yml

  tasks:
    - name: Install Prerequisites
      apt: name=aptitude update_cache=yes state=latest force_apt_get=yes

  # Sudo Group Setup
    - name: Make sure we have a 'wheel' group
      group:
        name: wheel
        state: present

    - name: Allow 'wheel' group to have passwordless sudo
     lineinfile:
        path: /etc/sudoers
        state: present
        regexp: '^%wheel'
        line: '%wheel ALL=(ALL) NOPASSWD: ALL'
        validate: '/usr/sbin/visudo -cf %s'

  # User + Key Setup
    - name: Create a new regular user with sudo privileges
      user:
        name: "{{ create_user }}"
        state: present
        groups: wheel
        append: true
        create_home: true
        shell: /bin/bash

    - name: Set authorized key for remote user
      authorized_key:
        user: "{{ create_user }}"
        state: present
        key: "{{ copy_local_key }}"

    - name: Disable password authentication for root
      lineinfile:
        path: /etc/ssh/sshd_config
        state: present
        regexp: '^#?PermitRootLogin'
        line: 'PermitRootLogin prohibit-password'

  # Install Packages
    - name: Update apt
      apt: update_cache=yes

    - name: Install required system packages
      apt: name={{ sys_packages }} state=latest

 # UFW Setup
    - name: UFW - Allow SSH connections
      ufw:
        rule: allow
        name: OpenSSH

    - name: UFW - Deny all other incoming traffic by default
      ufw:
        state: enabled
        policy: deny
        direction: incoming

Feel free to modify this playbook or include new tasks to best suit your individual needs within your own workflow.

可以随意修改此剧本或包括新任务,以最适合您自己的工作流程中的个性化需求。

结论 (Conclusion)

Automating the initial server setup can save you time, while also making sure your servers will follow a standard configuration that can be improved and customized to your needs. With the distributed nature of modern applications and the need for more consistency between different staging environments, automation like this becomes a necessity.

自动执行初始服务器设置可以节省您的时间,同时还可以确保服务器遵循标准配置,可以对其进行改进并根据需要进行自定义。 由于现代应用程序具有分布式特性,并且在不同的暂存环境之间需要更高的一致性,因此像这样的自动化成为必要。

In this guide, we demonstrated how to use Ansible for automating the initial tasks that should be executed on a fresh server, such as creating a non-root user with sudo access, enabling UFW and disabling remote password-based root login.

在本指南中,我们演示了如何使用Ansible自动执行应在新服务器上执行的初始任务,例如创建具有sudo访问权限的非root用户,启用UFW以及禁用基于密码的远程root登录。

If you’d like to include new tasks in this playbook to further customize your initial server setup, please refer to our introductory Ansible guide Configuration Management 101: Writing Ansible Playbooks. You can also check our guide on How to Use Ansible Roles to Abstract your Infrastructure Environment.

如果您想在此手册中包括新任务以进一步自定义初始服务器设置,请参阅我们的Ansible入门指南Configuration Management 101:编写Ansible手册 。 您还可以查看有关如何使用Ansible角色抽象基础架构环境的指南 。

翻译自: https://www.digitalocean.com/community/tutorials/how-to-use-ansible-to-automate-initial-server-setup-on-ubuntu-18-04


http://www.niftyadmin.cn/n/3649487.html

相关文章

[C#]服务为何会依赖于WMI Performance Adapter服务

[C#]服务为何会依赖于WMI Performance Adapter服务编写者日期关键词郑昀ultrapower2005-6-13Service C# Cache “WMI Performance Adapter”“Microsoft Enterprise Library”我们的C#编写的Windows Service“CommandListener”在Windows 2000上运行正常,但是在Wind…

android中常用的开源项目

在android开发过程中为了提高开发的效率,我们常需要引用一些第三方jar或者是使用之前项目的一些源码,这里我罗列一些较好的开源资源,方便使用。 1.menudrawer A slide-out menu implementation, which allows users to navigate between view…

什么是SWOT分析?怎样进行SWOT分析?

SWOT 模型含义介绍 优劣势分析主要是着眼于企业自身的实力及其与竞争对手的比较 , 而机会和威胁分析将注意力放在外部环境的变化及对企业的可能影响 上 。在分析时,应把所有的内部因素(即优劣势)集中在一起,然后用外部的力量来对这些因素进行…

如何使用Webpack 4和Babel 7设置React

介绍 (Introduction) A common way to learn React is to use create-react-app, which is a lightweight way to bootstrap any React project. But in order to achieve a particular purpose, it is sometimes necessary to configure your application from scratch. In th…

两种方法为WordPress添加用户自定义头像功能

一般情况下,WordPress默认都是使用Gravatar头像,如果用户没有注册过Gravatar头像,那就使用网站设置的默认头像,这样用户体验不是很好;再则,如果直接调用远程Gravatar头像,还会影响网站的加载速度…

Android 之 Binder与进程间通信

Binder机制是android中实现的进程间通信的架构,它采用的是c/s架构,client通过代理完成对server的调用。 ServiceManager 既然这里提到了server,那么我们有必要先了解下在android中是怎么来管理server的。先来看一个重要的Native进程&#xff…

如何在Ubuntu 18.04上使用Ansible安装和设置Apache

介绍 (Introduction) Server automation now plays an essential role in systems administration, due to the disposable nature of modern application environments. Configuration management tools such as Ansible are typically used to streamline the process of aut…

最新版Microsoft Edge——Chromium内核

2015年4月30日,微软在旧金山举行的Build 2015开发者大会上宣布,其最新操作系统——Windows 10内置代号为“Project Spartan”的新浏览器被正式命名为“Microsoft Edge”,其内置于Windows 10版本中。 2018年3月,微软宣布登陆iPad和…