Bootstrap

Ansible 自动化运维工具

一、Ansible 的介绍

  • Ansible是一个基于Python开发的配置管理和应用部署工具,现在也在自动化管理领域大放异彩。它融合了众多老牌运维工具的优点,Pubbet和Saltstack能实现的功能,Ansible基本上都可以实现

  • Ansible能批量配置、部署、管理上千台主机。比如以前需要切换到每个主机上执行的一或多个操作,使用Ansible只需在固定的一台Ansible控制节点上去完成所有主机的操作

  • Ansible是基于模块工作的,它只是提供了一种运行框架,它本身没有完成任务的能力,真正执行操作的是Ansible的模块, 比如copy模块用于拷贝文件到远程主机上,service模块用于管理服务的启动、停止、重启等

  • Ansible其中一个比较鲜明的特性是Agentless,即无Agent的存在,它就像普通命令一样,并非C/S软件,也只需在某个作为控制节点的主机上安装一次Ansible即可,通常它基于ssh连接来控制远程主机,远程主机上不需要安装Ansible或其它额外的服务

  • 使用者在使用时,在服务器终端输入命令或者playbooks,会通过预定好的规则将playbook拆解为play,再组织成ansible可以识别的任务,调用模块和插件,根据主机清单通过SSH将临时文件发给远程的客户端执行并返回结果,执行结束后自动删除

  • Ansible的另一个比较鲜明的特性是它的绝大多数模块都具备幂等性(idempotence)。所谓幂等性,指的是无论执行多少次同样的运算,结果都是相同的,即一条命令,任意多次执行所产生的影响均与一次执行的影响相同。比如执行 systemctl stop xxx 命令来停止服务,当发现要停止的目标服务已经处于停止状态,它什么也不会做, 所以多次停止的结果仍然是停止,不会改变结果,它是幂等的,而 systemctl restart xxx 是非幂等的

  • Ansible的很多模块在执行时都会先判断目标节点是否要执行任务,所以,可以放心大胆地让Ansible去执行任务,重复执行某个任务绝大多数时候不会产生任何副作用

二、ansible 环境安装部署

1、实验前准备

管理端:192.168.247.131			ansible
被管理端:192.168.247.132
被管理端:192.168.247.133

2、管理端安装 ansible

[root@lion ansible]# syum install -y epel-release			//先安装 epel 源
[root@lion ansible]# syum install -y ansible

3、ansible 目录结构

/etc/ansible/
├── ansible.cfg			#ansible的配置文件,一般无需修改
├── hosts				#ansible的主机清单,用于存储需要管理的远程主机的相关信息
└── roles/				#公共角色目录

4、配置主机清单

[root@lion ansible]# scd /etc/ansible
[root@lion ansible]# svim hosts       
  [webservers]			#配置组名
  192.168.247.132			#组里包含的被管理的主机IP地址或主机名(主机名需要先修改/etc/hosts文件)

  [dbservers]
  192.168.247.133

5、配置密钥对验证

[root@lion ansible]# ssh-keygen -t rsa -P '' -f ~/.ssh/id_rsa
Generating public/private rsa key pair.
Created directory '/root/.ssh'.
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:Y3qezYTjIh06AuWeZZIoVkhSbiylVVXWx2f1gNcqP/k root@lion
The key's randomart image is:
+---[RSA 2048]----+
| .+.....o. . ..o.|
|.B     .  . + +.o|
|= =        . + ..|
| +..        . .  |
| +..    S    o . |
|+.+ o .o o    +  |
|oo = o..+ .    o |
|  + + o+ *      E|
|   . o .+ o      |
+----[SHA256]-----+
[root@lion ansible]# yum install -y sshpass
[root@lion ansible]# sshpass -p 'xw523716' ssh-copy-id -o StrictHostKeyChecking=no root@192.168.247.132
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed

/usr/bin/ssh-copy-id: WARNING: All keys were skipped because they already exist on the remote system.
                (if you think this is a mistake, you may want to use -f option)
[root@lion ansible]# sshpass -p 'xw523716' ssh-copy-id -o StrictHostKeyChecking=no root@192.168.247.133
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed

/usr/bin/ssh-copy-id: WARNING: All keys were skipped because they already exist on the remote system.
                (if you think this is a mistake, you may want to use -f option)

三、ansible 命令行模块

命令格式:ansible <组名> -m <模块> -a <参数列表>
ansible-doc -l				#列出所有已安装的模块,按q退出

1、command 模块

(1)在远程主机执行命令,不支持管道,重定向等shell的特性

[root@lion ansible]# ansible-doc -s command     #-s 列出指定模块的描述信息和操作动作
- name: Execute commands on targets
  command:
      argv:                  # Passes the command as a list rather than a string. Use `argv' to avoid quoting values that would otherwise be interpreted incorrectly
                               (for example "user name"). Only the string or the list form can be provided, not both.  One or the
                               other must be provided.
      chdir:                 # Change into this directory before running the command.
      cmd:                   # The command to run.
      creates:               # A filename or (since 2.0) glob pattern. If it already exists, this step *won't* be run.
      free_form:             # The command module takes a free form command to run. There is no actual parameter named 'free form'.
      removes:               # A filename or (since 2.0) glob pattern. If it already exists, this step *will* be run.
      stdin:                 # Set the stdin of the command directly to the specified value.
      stdin_add_newline:     # If set to `yes', append a newline to stdin data.
      strip_empty_ends:      # Strip empty lines from the end of stdout/stderr in result.
      warn:                  # Enable or disable task warnings.
[root@lion ansible]# ansible 192.168.247.132 -m command -a 'date'    #指定 ip 执行 date
192.168.247.132 | CHANGED | rc=0 >>
20230727日 星期四 15:51:11 CST
[root@lion ansible]# ansible webservers -m command -a 'date'     #指定组执行 date
192.168.247.132 | CHANGED | rc=0 >>
20230727日 星期四 15:51:26 CST
[root@lion ansible]# ansible dbservers -m command -a 'date'
192.168.247.133 | CHANGED | rc=0 >>
20230727日 星期四 15:51:37 CST
[root@lion ansible]# ansible all -m command -a 'date'     	#all 代表所有 hosts 主机
192.168.247.132 | CHANGED | rc=0 >>
20230727日 星期四 15:51:52 CST
192.168.247.133 | CHANGED | rc=0 >>
20230727日 星期四 15:51:52 CST
[root@lion ansible]# ansible all -a 'ls /'     #如省略 -m 模块,则默认运行 command 模块
192.168.247.133 | CHANGED | rc=0 >>
bin
boot

(2)常用的参数

名称作用
chdir在远程主机上运行命令前提前进入目录
creates判断指定文件是否存在,如果存在,不执行后面的操作
removes判断指定文件是否存在,如果存在,执行后面的操作
[root@lion ansible]# ansible all -m command -a "chdir=/home  ls ./"
192.168.247.133 | CHANGED | rc=0 >>
test
192.168.247.132 | CHANGED | rc=0 >>
test

2、shell 模块

(1)在远程主机执行命令,相当于调用远程主机的shell进程,然后在该shell下打开一个子shell运行命令(支持管道符号等功能)

[root@lion ansible]# ansible-doc -s shell
[root@lion ansible]# ansible dbservers -m shell -a 'echo 123456 | passwd --stdin test'
192.168.247.133 | CHANGED | rc=0 >>
更改用户 test 的密码 。
passwd:所有的身份验证令牌已经成功更新。
[root@lion ansible]# ansible dbservers -m shell -a 'echo $(ifconfig ens33 | awk "NR==2 {print $2}") | cut -d " " -f2'
192.168.247.133 | CHANGED | rc=0 >>
ens33: error fetching interface information: Device not found
[root@lion ansible]# ansible dbservers -m shell -a 'echo $(ifconfig ens33 | awk "NR==2 {print \$2}")'
192.168.247.133 | CHANGED | rc=0 >>
ens33: error fetching interface information: Device not found

3、cron 模块

(1)在远程主机定义任务计划,有两种状态

  • present表示添加(可以省略)
  • absent表示移除。
[root@lion ansible]# ansible-doc -s cron     #按 q 退出

(2)常用的参数

minute/hour/day/month/weekday:分////周
job:任务计划要执行的命令
name:任务计划的名称
user:指定计划任务属于哪个用户,默认是root用户
  • 示例
[root@lion ansible]# ansible webservers -m cron -a 'minute="*/1" job="/bin/echo helloworld" name="test crontab"'
192.168.247.132 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "envs": [],
    "jobs": [
        "test crontab"
    ]
}
[root@lion ansible]# ansible webservers -a 'crontab -l'
192.168.247.132 | CHANGED | rc=0 >>
#Ansible: test crontab
*/1 * * * * /bin/echo helloworld
[root@lion ansible]# ansible webservers -m cron -a 'name="test crontab" state=absent'
192.168.247.132 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "envs": [],
    "jobs": []
}

4、user 模块

(1)用户管理的模块

[root@lion ansible]# ansible-doc -s user

(2)常用的参数

name:用户名,必选参数
state=present|absent:创建账号或者删除账号,present表示创建,absent表示删除
system=yes|no:是否为系统账号
uid:用户uid
group:用户基本组
groups: 用户所属附加组
shell:默认使用的shell
create_home=yse|no: 是否创建家目录
password:用户的密码,建议使用加密后的字符串
remove=yes|no:当state=absent时,是否删除用户的家目录
  • 示例
[root@lion ansible]# ansible dbservers -m user -a 'name="test01"'     #创建用户test01
192.168.247.133 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "comment": "",
    "create_home": true,
    "group": 1001,
    "home": "/home/test01",
    "name": "test01",
    "shell": "/bin/bash",
    "state": "present",
    "system": false,
    "uid": 1001
}
[root@lion ansible]# ansible dbservers -m command -a 'tail /etc/passwd'
192.168.247.133 | CHANGED | rc=0 >>
avahi:x:70:70:Avahi mDNS/DNS-SD Stack:/var/run/avahi-daemon:/sbin/nologin
postfix:x:89:89::/var/spool/postfix:/sbin/nologin
sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin
tcpdump:x:72:72::/:/sbin/nologin
test:x:1000:1000:test:/home/test:/bin/bash
nscd:x:28:28:NSCD Daemon:/:/sbin/nologin
nslcd:x:65:55:LDAP Client User:/:/sbin/nologin
ldap:x:55:55:OpenLDAP server:/var/lib/ldap:/sbin/nologin
ceph:x:167:167:Ceph daemons:/var/lib/ceph:/sbin/nologin
test01:x:1001:1001::/home/test01:/bin/bash
[root@lion ansible]# ansible dbservers -m user -a 'name="test01" state=absent'     #删除用户test01
192.168.247.133 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "force": false,
    "name": "test01",
    "remove": false,
    "state": "absent"
}

5、group 模块

(1)用户组管理的模块

[root@lion ansible]# ansible-doc -s group
[root@lion ansible]# ansible dbservers -m group -a 'name=mysql gid=306 system=yes'     #创建mysql组
192.168.247.133 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "gid": 306,
    "name": "mysql",
    "state": "present",
    "system": true
}
[root@lion ansible]# ansible dbservers -a 'tail /etc/group'
192.168.247.133 | CHANGED | rc=0 >>
postdrop:x:90:
postfix:x:89:
sshd:x:74:
tcpdump:x:72:
test:x:1000:test
nscd:x:28:
ldap:x:55:
screen:x:84:
ceph:x:167:
mysql:x:306:
[root@lion ansible]# ansible dbservers -m user -a 'name=test01 uid=306 system=yes group=mysql'     #将test01用户添加到mysql组中
192.168.247.133 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "comment": "",
    "create_home": true,
    "group": 306,
    "home": "/home/test01",
    "name": "test01",
    "shell": "/bin/bash",
    "state": "present",
    "stderr": "useradd:警告:此主目录已经存在。\n不从 skel 目录里向其中复制任何文件。\n",
    "stderr_lines": [
        "useradd:警告:此主目录已经存在。",
        "不从 skel 目录里向其中复制任何文件。"
    ],
    "system": true,
    "uid": 306
}
[root@lion ansible]# ansible dbservers -a 'tail /etc/passwd'
192.168.247.133 | CHANGED | rc=0 >>
avahi:x:70:70:Avahi mDNS/DNS-SD Stack:/var/run/avahi-daemon:/sbin/nologin
postfix:x:89:89::/var/spool/postfix:/sbin/nologin
sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin
tcpdump:x:72:72::/:/sbin/nologin
test:x:1000:1000:test:/home/test:/bin/bash
nscd:x:28:28:NSCD Daemon:/:/sbin/nologin
nslcd:x:65:55:LDAP Client User:/:/sbin/nologin
ldap:x:55:55:OpenLDAP server:/var/lib/ldap:/sbin/nologin
ceph:x:167:167:Ceph daemons:/var/lib/ceph:/sbin/nologin
test01:x:306:306::/home/test01:/bin/bash
[root@lion ansible]# ansible dbservers -a 'id test01'
192.168.247.133 | CHANGED | rc=0 >>
uid=306(test01) gid=306(mysql)=306(mysql)

6、copy 模块

(1)用于复制指定主机文件到远程主机的

[root@lion ansible]# ansible-doc -s copy

(2)常用的参数

dest:指出复制文件的目标及位置,使用绝对路径,如果源是目录,指目标也要是目录,如果目标文件已经存在会覆盖原有的内容
src:指出源文件的路径,可以使用相对路径或绝对路径,支持直接指定目录,如果源是目录则目标也要是目录
mode:指出复制时,目标文件的权限 
owner:指出复制时,目标文件的属主
group:指出复制时,目标文件的属组
content:指出复制到目标主机上的内容,不能与src一起使用
  • 示例
[root@lion ansible]# ansible dbservers -m copy -a 'src=/etc/fstab dest=/opt/fstab.bak owner=root mode=640'
192.168.247.133 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "checksum": "6d076ec2b1c7267a0fbad3cf6643238c8c998f51",
    "dest": "/opt/fstab.bak",
    "gid": 0,
    "group": "root",
    "md5sum": "3802d6993a7c75f6a8f4ae30bb1a6f66",
    "mode": "0640",
    "owner": "root",
    "size": 407,
    "src": "/root/.ansible/tmp/ansible-tmp-1690446467.46-34584-246531462102810/source",
    "state": "file",
    "uid": 0
}
[root@lion ansible]# ansible dbservers -a 'ls -l /opt'
192.168.247.133 | CHANGED | rc=0 >>
总用量 4
-rw-r-----  1 root root 407 727 16:27 fstab.bak
drwxr-xr-x. 2 root root 222 716 00:37 repos.bak
drwxr-xr-x. 2 root root   6 326 2015 rh
[root@lion ansible]# ansible dbservers -a 'cat /opt/fstab.bak'
192.168.247.133 | CHANGED | rc=0 >>

#
# /etc/fstab
# Created by anaconda on Wed Mar 22 13:21:46 2023
#
# Accessible filesystems, by reference, are maintained under '/dev/disk'
# See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info
#
UUID=64a803df-baa5-4040-872a-b00bf5609a93 /                       xfs     defaults        0 0
UUID=c8adc346-3971-49f6-b00b-8940e5b56852 swap                    swap    defaults        0 0
[root@lion ansible]# ansible dbservers -m copy -a 'content="helloworld" dest=/opt/hello.txt'     #将helloworld写入/opt/hello.txt文件中
192.168.247.133 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "checksum": "6adfb183a4a2c94a2f92dab5ade762a47889a5a1",
    "dest": "/opt/hello.txt",
    "gid": 0,
    "group": "root",
    "md5sum": "fc5e038d38a57032085441e7fe7010b0",
    "mode": "0644",
    "owner": "root",
    "size": 10,
    "src": "/root/.ansible/tmp/ansible-tmp-1690446501.28-34665-159665294872979/source",
    "state": "file",
    "uid": 0
}
[root@lion ansible]# ansible dbservers -a 'cat /opt/hello.txt'
192.168.247.133 | CHANGED | rc=0 >>
helloworld

7、file 模块

(1)设置文件属性

[root@lion ansible]# ansible-doc -s file
[root@lion ansible]# ansible dbservers -m file -a 'owner=test01 group=mysql mode=644 path=/opt/fstab.bak'     	#修改文件的属主属组权限等
192.168.247.133 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "gid": 306,
    "group": "mysql",
    "mode": "0644",
    "owner": "test01",
    "path": "/opt/fstab.bak",
    "size": 407,
    "state": "file",
    "uid": 306
}
[root@lion ansible]# ansible dbservers -m file -a 'path=/opt/fstab.link src=/opt/fstab.bak state=link'
192.168.247.133 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "dest": "/opt/fstab.link",
    "gid": 0,
    "group": "root",
    "mode": "0777",
    "owner": "root",
    "size": 14,
    "src": "/opt/fstab.bak",
    "state": "link",
    "uid": 0
}
[root@lion ansible]# ansible dbservers -m file -a "path=/opt/abc.txt state=touch"     #创建一个文件
192.168.247.133 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "dest": "/opt/abc.txt",
    "gid": 0,
    "group": "root",
    "mode": "0644",
    "owner": "root",
    "size": 0,
    "state": "file",
    "uid": 0
}
[root@lion ansible]# ansible dbservers -m file -a "path=/opt/abc.txt state=absent"     #删除一个文件
192.168.247.133 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "path": "/opt/abc.txt",
    "state": "absent"
}

8、hostname 模块

(1)用于管理远程主机上的主机名

[root@lion ansible]# ansible dbservers -m hostname -a "name=mysql01"
192.168.247.133 | CHANGED => {
    "ansible_facts": {
        "ansible_domain": "",
        "ansible_fqdn": "mysql01",
        "ansible_hostname": "mysql01",
        "ansible_nodename": "mysql01",
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "name": "mysql01"
}

9、ping 模块

(1)检测远程主机的连通性

[root@lion ansible]# ansible all -m ping
192.168.247.132 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}
192.168.247.133 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}

10、yum 模块

(1)在远程主机上安装与卸载软件包

[root@lion ansible]# ansible-doc -s yum
[root@lion ansible]# ansible webservers -m yum -a 'name=httpd'     	#安装服务
192.168.247.132 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "changes": {
        "installed": [
            "httpd"
        ]
    },
    "msg": "",
    "rc": 0,
    "results": [
        "Loaded plugins: fastestmirror, langpacks, priorities\nLoading mirror speeds from cached hostfile\n * base: mirrors.ustc.edu.cn\n * epel: mirrors.bfsu.edu.cn\n * extras: mirrors.163.com\n * updates: mirrors.ustc.edu.cn\nResolving Dependencies\n--> Running transaction check\n---> Package httpd.x86_64 0:2.4.6-99.el7.centos.1 will be installed\n--> Processing Dependency: httpd-tools = 2.4.6-99.el7.centos.1 for package: httpd-2.4.6-99.el7.centos.1.x86_64\n--> Running transaction check\n---> Package httpd-tools.x86_64 0:2.4.6-99.el7.centos.1 will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package           Arch         Version                     Repository     Size\n================================================================================\nInstalling:\n httpd             x86_64       2.4.6-99.el7.centos.1       updates       2.7 M\nInstalling for dependencies:\n httpd-tools       x86_64       2.4.6-99.el7.centos.1       updates        94 k\n\nTransaction Summary\n================================================================================\nInstall  1 Package (+1 Dependent package)\n\nTotal download size: 2.8 M\nInstalled size: 9.5 M\nDownloading packages:\n--------------------------------------------------------------------------------\nTotal                                              2.7 MB/s | 2.8 MB  00:01     \nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n  Installing : httpd-tools-2.4.6-99.el7.centos.1.x86_64                     1/2 \n  Installing : httpd-2.4.6-99.el7.centos.1.x86_64                           2/2 \n  Verifying  : httpd-2.4.6-99.el7.centos.1.x86_64                           1/2 \n  Verifying  : httpd-tools-2.4.6-99.el7.centos.1.x86_64                     2/2 \n\nInstalled:\n  httpd.x86_64 0:2.4.6-99.el7.centos.1                                          \n\nDependency Installed:\n  httpd-tools.x86_64 0:2.4.6-99.el7.centos.1                                    \n\nComplete!\n"
    ]
}
[root@lion ansible]# ansible webservers -m yum -a 'name=httpd state=absent'      #卸载服务
192.168.247.132 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "changes": {
        "removed": [
            "httpd"
        ]
    },
    "msg": "",
    "rc": 0,
    "results": [
        "已加载插件:fastestmirror, langpacks, priorities\n正在解决依赖关系\n--> 正在检查事务\n---> 软件包 httpd.x86_64.0.2.4.6-99.el7.centos.1 将被 删除\n--> 解决依赖关系完成\n\n依赖关系解决\n\n================================================================================\n Package      架构          版本                          源               大小\n================================================================================\n正在删除:\n httpd        x86_64        2.4.6-99.el7.centos.1         @updates        9.4 M\n\n事务概要\n================================================================================\n移除  1 软件包\n\n安装大小:9.4 M\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n  正在删除    : httpd-2.4.6-99.el7.centos.1.x86_64                          1/1 \n  验证中      : httpd-2.4.6-99.el7.centos.1.x86_64                          1/1 \n\n删除:\n  httpd.x86_64 0:2.4.6-99.el7.centos.1                                          \n\n完毕!\n"
    ]
}

11、service/systemd 模块

(1)用于管理远程主机上的管理服务的运行状态

[root@lion ansible]# ansible-doc -s service

(2)常用的参数

name:被管理的服务名称
state=started|stopped|restarted:动作包含启动关闭或者重启
enabled=yes|no:表示是否设置该服务开机自启
runlevel:如果设定了enabled开机自启去,则要定义在哪些运行目标下自启动
  • 示例
[root@lion ansible]# ansible webservers -a 'systemctl status httpd'     #查看web服务器httpd运行状态
192.168.247.132 | FAILED | rc=3 >>
● httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled; vendor preset: disabled)
   Active: inactive (dead)
     Docs: man:httpd(8)
           man:apachectl(8)non-zero return code
[root@lion ansible]# ansible webservers -m service -a 'enabled=true name=httpd state=started'     #启动httpd服务
192.168.247.132 | FAILED! => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "msg": "Unable to start service httpd: Job for httpd.service failed because the control process exited with error code. See \"systemctl status httpd.service\" and \"journalctl -xe\" for details.\n"
}

12、script 模块

(1)实现远程批量运行本地的 shell 脚本

[root@lion ansible]# ansible-doc -s script
[root@lion ansible]# vim test.sh
[root@lion ansible]# chmod +x test.sh
[root@lion ansible]# ansible webservers -m script -a 'test.sh'
192.168.247.132 | CHANGED => {
    "changed": true,
    "rc": 0,
    "stderr": "Shared connection to 192.168.247.132 closed.\r\n",
    "stderr_lines": [
        "Shared connection to 192.168.247.132 closed."
    ],
    "stdout": "",
    "stdout_lines": []
}
[root@lion ansible]# ansible webservers -a 'cat /opt/script.txt'
192.168.247.132 | CHANGED | rc=0 >>
hello ansible from script
[root@lion ansible]# vim test.sh
  echo $1 > /opt/test.txt
  echo s2 >> /opt/test .txt
[root@lion ansible]# ansible dbservers -m script -a 'test.sh abc 123'
192.168.247.133 | CHANGED => {
    "changed": true,
    "rc": 0,
    "stderr": "Shared connection to 192.168.247.133 closed.\r\n",
    "stderr_lines": [
        "Shared connection to 192.168.247.133 closed."
    ],
    "stdout": "",
    "stdout_lines": []
}

13、mount 模块

(1)挂载文件系统

[root@lion ansible]# ansible-doc -s mount

(2)常用的参数

src:定义挂载设备的路径
path:定义挂载到哪个目录,必须指定
fstype:指定挂载文件的系统类型,必须指定,xfs、iso9660、nfs...
opts:定义挂载的参数,defaults、rw、ro...
state:定义挂载的状态,mounted(进行挂载,修改/etc/fstab信息)、absent(永久性卸载,并修改 /etc/fstab信息)、unmounted(临时卸载,不修改/etc/fstab信息)
  • 示例
[root@lion ansible]# ansible dbservers -m mount -a 'src=/dev/sr0 path=/mnt state=mounted fstype=iso9660'
192.168.247.133 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "dump": "0",
    "fstab": "/etc/fstab",
    "fstype": "iso9660",
    "name": "/mnt",
    "opts": "defaults",
    "passno": "0",
    "src": "/dev/sr0"
}

14、archive 模块

(1)打包压缩

[root@lion ansible]# ansible-doc -s archive

(2)常用的参数

path: 必须参数,远程主机上需要被打包压缩的源文件/目录
dest: 打包压缩后的包文件路径(包文件的父目录必须存在);如果包文件已存在,则会被覆盖
format: 指定压缩类型,包括: bz2、gz(默认)、tar、xz、zip
remove=yes|no: 是否删除源文件
  • 示例
[root@lion ansible]# ansible dbservers -m archive -a "path=/etc/yum.repos.d/ dest=/opt/repo.zip format=zip"
192.168.247.133 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "archived": [
        "/etc/yum.repos.d/CentOS-Base.repo",
        "/etc/yum.repos.d/CentOS-CR.repo",
        "/etc/yum.repos.d/CentOS-Debuginfo.repo",
        "/etc/yum.repos.d/CentOS-fasttrack.repo",
        "/etc/yum.repos.d/CentOS-Media.repo",
        "/etc/yum.repos.d/CentOS-Sources.repo",
        "/etc/yum.repos.d/CentOS-Vault.repo",
        "/etc/yum.repos.d/ceph.repo",
        "/etc/yum.repos.d/epel.repo",
        "/etc/yum.repos.d/epel-testing.repo"
    ],
    "arcroot": "/etc/yum.repos.d/",
    "changed": true,
    "dest": "/opt/repo.zip",
    "expanded_exclude_paths": [],
    "expanded_paths": [
        "/etc/yum.repos.d/"
    ],
    "gid": 0,
    "group": "root",
    "missing": [],
    "mode": "0644",
    "owner": "root",
    "size": 5253,
    "state": "file",
    "uid": 0
}
[root@lion ansible]# ansible dbservers -m archive -a "path=/opt/abc.txt,/opt/123.txt dest=/opt/abc123.tar.gz format=gz remove=yes"
192.168.247.133 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "archived": [],
    "arcroot": "/opt/",
    "changed": true,
    "dest": "/opt/abc123.tar.gz",
    "expanded_exclude_paths": [],
    "expanded_paths": [
        "/opt/abc.txt",
        "/opt/123.txt"
    ],
    "gid": 0,
    "group": "root",
    "missing": [
        "/opt/abc.txt",
        "/opt/123.txt"
    ],
    "mode": "0644",
    "owner": "root",
    "size": 61,
    "state": "file",
    "uid": 0
}

15、 unarchive 模块

(1)解包解压缩

[root@lion ansible]# ansible-doc -s unarchive

(2)常用的参数

copy:默认为 copy=yes ,拷贝的文件从 ansible 主机复制到远程主机,copy=no 表示在远程主机上寻找源文件解压
src:tar包源路径,可以是 ansible 主机上的路径,也可以是远程主机上的路径,如果是远程主机上的路径,则需设置 copy=no
dest:解压后文件的目标绝对路径
remote_src: 和 copy 功能一样且互斥,设置 remote_src=yes 表示文件在远程主机上,设置为 remote_src=no 表示文件在 ansible 主机上

(3)将 ansible 主机的压缩文件拷贝到到远程主机并解压,修改文件所属组和用户

[root@lion opt]# ansible dbservers -m unarchive -a "src=/opt/xu.tar.gz dest=/opt copy=yes"
192.168.247.133 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "dest": "/opt",
    "extract_results": {
        "cmd": [
            "/usr/bin/gtar",
            "--extract",
            "-C",
            "/opt",
            "-z",
            "-f",
            "/root/.ansible/tmp/ansible-tmp-1690453044.97-43251-76767844126276/source"
        ],
        "err": "",
        "out": "",
        "rc": 0
    },
    "gid": 0,
    "group": "root",
    "handler": "TgzArchive",
    "mode": "0755",
    "owner": "root",
    "size": 168,
    "src": "/root/.ansible/tmp/ansible-tmp-1690453044.97-43251-76767844126276/source",
    "state": "directory",
    "uid": 0
}

(4)在远程主机解包

ansible dbservers -m unarchive -a "src=/opt/123.tar.gz dest=/root copy=no"
或者
ansible dbservers -m unarchive -a "src=/opt/123.tar.gz dest=/root remote_src=yes"

16、 replace 模块

(1)类似于sed命令,主要也是基于正则进行匹配和替换

[root@lion ansible]# ansible-doc -s replace

(2)常用的参数

path:必须参数,指定要修改的文件
regexp:必须参数,指定一个正则表达式
replace:替换regexp参数匹配到的字符串
backup=yes|no: 修改源文件前创建一个包含时间戳信息的备份文件
before:如果指定,则仅替换/删除此匹配之前的内容,可以和after参数结合使用
after:如果指定,则仅替换/删除此匹配之后的内容,可以和before参数结合使用
owner:修改文件用户名
group:修改文件组名
mode:修改文件权限
vim /opt/test.txt
11 22 33 44 55 66
aa bb cc dd ee ff
1a 2b 3c 4d 5e 6f

(3)匹配 333 并修改为 ccc

ansible dbservers -m replace -a "path=/opt/test.txt regexp='33' replace='cc'"

(4)匹配到任意一个或多个开头的行增加注释

ansible dbservers -m replace -a "path=/opt/test.txt regexp='^(.*)' replace='#\1'"

(5)取消注释

ansible dbservers -m replace -a "path=/opt/test.txt regexp='^#(.*)' replace='\1'"

(6)匹配以 a 开头的后面有一个或者多个字符的行,并在前面添加 # 注释

ansible dbservers -m replace -a "path=/opt/test.txt regexp='^(a.*)' replace='#\1'"
ansible dbservers -m replace -a "path=/opt/test.txt regexp='3' replace='three' before=cc"

17、setup 模块

(1)facts 组件是用来收集被管理节点信息的,使用 setup 模块可以获取这些信息

ansible-doc -s setup
ansible webservers -m setup				#获取mysql组主机的facts信息
ansible dbservers -m setup -a 'filter=*ipv4'    #使用filter可以筛选指定的facts信息

四、inventory 主机清单

1、Inventory支持对主机进行分组,每个组内可以定义多个主机,每个主机都可以定义在任何一个或多个主机组内

2、如果是名称类似的主机,可以使用列表的方式标识各个主机

vim /etc/ansible/hosts
[webservers]
192.168.247.132:2222		#冒号后定义远程连接端口,默认是 ssh 的 22 端口
192.168.80.1[2:5]

[dbservers]
db-[a:f].example.org	#支持匹配 a~f

3、inventory 中的变量

Inventory变量名	              含义
ansible_host                  ansible连接节点时的IP地址
ansible_port                  连接对方的端口号,ssh连接时默认为22
ansible_user                  连接对方主机时使用的用户名。不指定时,将使用执行ansible或ansible-playbook命令的用户
ansible_password              连接时的用户的ssh密码,仅在未使用密钥对验证的情况下有效
ansible_ssh_private_key_file  指定密钥认证ssh连接时的私钥文件
ansible_ssh_common_args       提供给ssh、sftp、scp命令的额外参数
ansible_become                允许进行权限提升
ansible_become_method         指定提升权限的方式,例如可使用sudo/su/runas等方式
ansible_become_user           提升为哪个用户的权限,默认提升为root
ansible_become_password       提升为指定用户权限时的密码

(1)主机变量

[webservers]
192.168.247.132 ansible_port=22 ansible_user=root ansible_password=abc1234

(2)组变量

[webservers:vars]			#表示为 webservers 组内所有主机定义变量
ansible_user=root
ansible_password=abc1234

[all:vars]					#表示为所有组内的所有主机定义变量
ansible_port=22

(3)组嵌套

[nginx]
192.168.80.20
192.168.80.21
192.168.80.22

[apache]
192.168.80.3[0:3]

[webs:children]		#表示为 webs 主机组中包含了 nginx 组和 apache 组内的所有主机
nginx
apache
;