Ansible 学习笔记(三)使用Playbook脚本管理主机

作者:Guangran 日期:2023-12-15

前言

在很多情况下,执行单个命令或调用某一个模块,无法满足复杂工作的需要。Ansible 服务允许用户根据需求,在类似于 Shell 脚本的模式下编写自动化运维脚本,然后由程序自动、重复地执行,从而提高工作效率。Playbook 就是 Ansible 的脚本语言,使用的是 YAML 格式。

脚本文件格式

组成

脚本文件由四部分组成,分别是target、variable、task、handler,其各自的作用如下:

target:用于定义要执行剧本的主机范围。

variable:用于定义剧本执行时要用到的变量。

task:用于定义将在远程主机上执行的任务列表。

handler:用于定义执行完成后需要调用的后续任务。

格式

文件开始符

YAML 文件的开头需要先写3个减号(---)

CODEyaml
---

数组list

数组中的每个元素都是以 - 开始的

CODEyaml
- list1- list2- list3

字典

key和value之间用冒号和空格分隔

CODEyaml
key: value

字典嵌套

CODEyaml
martion:name: testjob: Developerskill: Elite

字典和数组嵌套

CODEyaml
- martion:name: testjob: Developer- tabitha:name: test2job: Developer

执行 Playbook 命令

执行 Playbook 的基本方法

TERMINALbash
ansible-playbook deploy.yml

查看输出的细节

TERMINALbash
ansible-playbook deploy.yml --verbose

查看受该脚本影响的主机

TERMINALbash
ansible-playbook deploy.yml --list-hosts

并行执行脚本

TERMINALbash
ansible-playbook deploy.yul -f 10

编写简易的 Playbook 脚本

安装软件

查看 yum 模块文档

TERMINALbash
[root@control ~]# ansible-doc yum> YUM    (/usr/lib/python3.8/site-packages/ansible/modules/packaging/os/yum.py)      Installs, upgrade, downgrades, removes, and lists packages and groups with the      `yum' package manager. This module only works on Python 2. If you require Python 3      support see the [dnf] module.* This module is maintained by The Ansible Core Team* note: This module has a corresponding action plugin.OPTIONS (= is mandatory):……中间输出省略……EXAMPLES:- name: install the latest version of Apacheyum:  name: httpd  state: latest- name: ensure a list of packages installedyum:  name: "{{ packages }}"vars:  packages:  - httpd  - httpd-tools……其他输出省略……

编写脚本

TERMINALbash
[root@control ~]# vim installpackages.yml
CONFIG/root/installpackages.yml
---- name: 安装软件包hosts: dbtasks:  - name: one    yum:	    name: mariadb-server	    state: latest
备注
  • name:描述
  • hosts:执行的主机
  • tasks:执行的任务
  • name:描述
  • yum:执行的模块

执行脚本

TERMINALbash
[root@control ~]# ansible-playbook installpackages.ymlPLAY [安装软件包] **************************************************************************************************TASK [Gathering Facts] *******************************************************************************************ok: [node3]TASK [one] *******************************************************************************************************changed: [node3]PLAY RECAP *******************************************************************************************************node3                      : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

验证 mariadb-server 是否安装

TERMINALbash
[root@node3 ~]# rpm -qi mariadb-serverName        : mariadb-serverEpoch       : 4Version     : 10.5.10Release     : 3.oe1Architecture: x86_64Install Date: Fri 11 Nov 2022 05:50:42 PM CSTGroup       : UnspecifiedSize        : 97514943License     : GPLv2 and LGPLv2Signature   : RSA/SHA1, Thu 30 Sep 2021 05:33:33 AM CST, Key ID d557065eb25e7f66Source RPM  : mariadb-10.5.10-3.oe1.src.rpmBuild Date  : Thu 30 Sep 2021 05:23:12 AM CSTBuild Host  : ecs-obsworker-0001Packager    : http://openeuler.orgVendor      : http://openeuler.orgURL         : http://mariadb.orgSummary     : The MariaDB server and related filesDescription :MariaDB is a multi-user, multi-threaded SQL database server. It is aclient/server implementation consisting of a server daemon (mariadbd)and many different client programs and libraries. This package containsthe MariaDB server and some accompanying files and directories.MariaDB is a community developed fork from MySQL.

启动服务

查看 service 模块文档

TERMINALbash
[root@control ~]# ansible-doc service> SERVICE    (/usr/lib/python3.8/site-packages/ansible/modules/system/service.py)      Controls services on remote hosts. Supported init systems include BSD init, OpenRC,      SysV, Solaris SMF, systemd, upstart. For Windows targets, use the [win_service]      module instead.* This module is maintained by The Ansible Core Team* note: This module has a corresponding action plugin.OPTIONS (= is mandatory):……中间输出省略……EXAMPLES:- name: Start service httpd, if not startedservice:  name: httpd  state: started- name: Stop service httpd, if startedservice:  name: httpd  state: stopped……其他输出省略……

编写脚本

TERMINALbash
[root@control ~]# vim startservice.yml
CONFIG/root/startservice.yml
---- name: 启动服务hosts: dbtasks:  - name: one    service:	      name: mariadb	      state: started	      enabled: yes

执行脚本

TERMINALbash
[root@control ~]# ansible-playbook startservice.ymlPLAY [启动服务] ***************************************************************************************************TASK [Gathering Facts] *******************************************************************************************ok: [node3]TASK [one] *******************************************************************************************************changed: [node3]PLAY RECAP *******************************************************************************************************node3                      : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

查看服务是否启动

TERMINALbash
[root@node3 ~]# systemctl status mariadb mariadb.service - MariaDB 10.5 database server   Loaded: loaded (8;;file://node3/usr/lib/systemd/system/mariadb.service^G/usr/lib/systemd/system/mariadb.serv>   Active: active (running) since Fri 2022-11-11 18:00:02 CST; 1min 43s ago     Docs: 8;;man:mariadbd(8)^Gman:mariadbd(8)8;;^G           8;;https://mariadb.com/kb/en/library/systemd/^Ghttps://mariadb.com/kb/en/library/systemd/8;;^G  Process: 4953 ExecStartPre=/usr/libexec/mariadb-check-socket (code=exited, status=0/SUCCESS)  Process: 4977 ExecStartPre=/usr/libexec/mariadb-prepare-db-dir mariadb.service (code=exited, status=0/SUCCESS)  Process: 5084 ExecStartPost=/usr/libexec/mariadb-check-upgrade (code=exited, status=0/SUCCESS) Main PID: 5070 (mariadbd)   Status: "Taking your SQL requests now..."    Tasks: 8 (limit: 21456)   Memory: 76.6M   CGroup: /system.slice/mariadb.service           └─5070 /usr/libexec/mariadbd --basedir=/usr

最后

Playbook 的基础操作,简单记录一下。