更新时间:2023 年 5 月

Ansible 相关文件

  • /etc/ansible/ansible.cfg :主配置文件

    配置 ansible 工作特性,也可以在项目的目录中创建此文件,当前目录下如果也有 ansible.cfg,则此文件优先生效,建议每个项目目录下,创建独有的 ansible.cfg 文件

  • /etc/ansible/hosts :主机清单

  • /etc/ansible/roles/ :存放角色的目录

Ansible 配置文件

参考:Ansible Configuration Settings — Ansible Documentation

Ansible 的配置文件可以放在多个不同地方,优先级从高到低顺序如下

  • ANSIBLE_CONFIG:环境变量指定的配置文件,注意此项用 ansible --version 看不到,但可以生效
  • ./ansible.cfg: 当前目录下的 ansible.cfg
  • ~/.ansible.cfg:当前用户家目录下的 .ansible.cfg
  • /etc/ansible/ansible.cfg:系统默认配置文件

注:生产环境建议每个项目目录下,创建项目独有的 ansible.cfg 文件

生成默认配置

在 Ansible 2.12 (core) 以上的版本,默认不提供 /etc/ansible/ansible.cfg,但是可以使用命令来生成配置文件,如下所示

# 生成配置
$ ansible-config init > ./ansible.cfg

# disable 选项用于注释所生成的所有配置
$ ansible-config init --disabled > ./ansible.cfg

# -t 指定只生成指定插件的配置,默认 all,表示所有配置
$ ansible-config init --disabled -t all > ./ansible.cfg

常见的配置选项

ansible.cfg 常见的配置选项

# 基础设置
[defaults]
# 主机清单文件位置
;inventory=/etc/ansible/hosts

# 本机临时命令执行目录
;local_tmp={{ ANSIBLE_HOME ~ "/tmp" }}

# 过滤插件设置,默认 /etc/ansible/plugin_filters.yml
;plugin_filters_cfg=

# 执行 task 的默认并发数
;forks=5

# 异步执行 task 时,轮训 task 状态的频率,默认 15 秒
;poll_interval=15

# 执行 ansible playbook 时,是否提示输入密码;使用 SSH keys 认证时可以关闭
;ask_pass=False

# 要使用的默认连接插件,smart 选项可以自动在 ssh 和 paramiko 进行选择
;transport=smart


# 远程连接端口
;remote_port=

# 远程连接用户
;remote_user=

# 默认模块,默认为 command,建议改成 shell
;module_name=command

# 检查对应服务器的 host_key,建议 False,第一次连接自动信任目标主机
;host_key_checking=True

# 普通用户提升权限设置
[privilege_escalation]
# 权限提升开关
;become=False
# 登录后,权限提升方法
;become_method=sudo
# 登录后,权限提升至哪个用户
;become_user=root
# 切换权限提示输入密码
;become_ask_pass=False

Inventory 主机清单文件

参考:How to build your inventory — Ansible Documentation

ansible 的主要功用在于批量主机操作,为了方便地使用其中的部分主机,可以在 inventory 主机清单文件中将主机进行分组管理,默认的 inventory file 为 /etc/ansible/hosts

inventory file 可以有多个,且也可以通过 Dynamic Inventory 来动态生成

注:生产环境建议每个项目目录下,创建项目独立的 hosts文件

主机清单文件格式

inventory 文件遵循 INI 文件风格(注解使用分号 ;),中括号中的字符为组名(可以使用下划线 _,不可以使用中划线 - 或者空格)。可以将同一个主机同时归并到多个不同的组中

此外,当如若目标主机使用了非默认的 SSH 端口,还可以在主机名称之后使用冒号加端口号来标明

如果主机名称遵循相似的命名模式,还可以使用列表的方式标识各主机

Inventory 常用参数说明

  • ansible_ssh_host:将要连接的远程主机名。与你想要设定的主机的别名不同的话,可通过此变量设置

  • ansible_ssh_port:SSH 端口号。非默认端口可以通过此变量设置,也可以直接使用 ip:端口,例:192.168.1.100:2222

  • ansible_ssh_user:SSH 连接时使用的用户名

  • ansible_ssh_pass:SSH 连接时使用的密码(不安全,建议使用 --ask-pass 或 SSH 密钥)

  • ansible_sudo_pass:sudo 提权密码(不安全,建议使用 --ask-sudo-pass

  • ansible_sudo_exe:sudo 命令路径

  • ansible_connection:连接类型和插件,默认 smart,本地主机可以使用 local

  • ansible_ssh_private_key_file:SSH 使用的私钥文件。适用于有多个密钥,而不想使用 SSH 代理的情况

  • ansible_shell_type:目标系统的 shell 类型,默认为 sh

  • ansible_python_interpreter:指定目标主机的 python 路径,适用于以下情况:

    • 目标系统中有多个 Python,想要指定某个 Python

    • Python 命令路径不是 /usr/bin/python

    • Python 命令路径 /usr/bin/python 版本不支持

    之所以不使用 /usr/bin/env 机制,因为这要求远程用户的路径设置正确,要求 Python 可执行程序名不可以是 python 以外的名字(实际有可能名为 python26python37 等)

    同理,可以应用到 ansible_ruby_interpreter 等其他参数

示例

示例一

[webservers]
www[1:100].example.com
[dbservers]
db-[a:f].example.com
[appservers]
10.0.0.[1:100]

# 定义testsrvs组中包括两个其它分组,实现组嵌套
[testsrvs:children] 
webservers
dbservers

示例二

[test]
10.0.0.8  ansible_connection=local   # 指定本地连接,无需ssh配置
#ansible_connection=ssh 需要StrictHostKeyChecking no
10.0.0.7  ansible_connection=ssh  ansible_ssh_port=2222 ansible_ssh_user=aiden ansible_ssh_password=520123  
10.0.0.6  ansible_connection=ssh  ansible_ssh_user=root ansible_ssh_password=123456

#执行ansible命令时显示别名,如web01
[websrvs]
web01 ansible_ssh_host=10.0.0.101
web02 ansible_ssh_host=10.0.0.102

[websrvs:vars]
ansible_ssh_password=qwert123.。
some_host         ansible_ssh_port=2222  ansible_ssh_user=manager
aws_host          ansible_ssh_private_key_file=/home/example/.ssh/aws.pem
freebsd_host      ansible_python_interpreter=/usr/local/bin/python
ruby_module_host  ansible_ruby_interpreter=/usr/bin/ruby.1.9.3

Ansible 相关命令

  • /usr/bin/ansible :主程序,临时命令执行工具
  • /usr/bin/ansible-doc :用于查看配置文档,模块功能查看工具,相当于 man
  • /usr/bin/ansible-playbook:定制自动化任务,编排剧本工具,相当于脚本
  • /usr/bin/ansible-pull:远程执行命令的工具
  • /usr/bin/ansible-vault:文件加密工具
  • /usr/bin/ansible-console:基于 Console 界面与用户交互的执行工具
  • /usr/bin/ansible-galaxy:下载和上传优秀的 CollectionRoles 官网平台

实现 ansible 管理的主要方式

  • Ansible Ad-Hoc:利用 ansible 命令,主要用于临时命令使用场景
  • Ansible playbook:主要用于长期规划好的,大型项目的场景,需要有前期的规划过程

Ansible 使用准备

Ansible 相关工具大多数是通过 SSH 协议,实现对远程主机的配置管理、应用部署、任务执行等功能

建议:使用 ansible 前,先配置 ansible 主控端能基于密钥认证的方式联系各个被管理节点

实现 SSH 密钥认证

在 ansible 主控端生成密钥,并分发到各个被控端

# 修改全局的 host key 校验,
$ vim /etc/ssh/ssh_config
# 修改下面一行
StrictHostKeyChecking no


# 被控端主机列表
$ cat > hosts.list << EOF
192.168.111.192
192.168.111.193
192.168.111.194
192.168.111.195
EOF

# ssh 密钥认证脚本,利用 sshpass 批量实现基于 key 验证脚本
$ cat > ssh_key_auth.sh << EOF
#!/bin/bash
rpm -q sshpass &> /dev/null || yum -y install sshpass  
[ -f /root/.ssh/id_rsa ] || ssh-keygen -f /root/.ssh/id_rsa  -P ''
export SSHPASS=520123

while read IP;do
   sshpass -e ssh-copy-id  -o StrictHostKeyChecking=no \$IP
done < hosts.list
EOF


# 运行脚本
$ bash ./ssh_key_auth.sh 

创建 Ansible 配置

# 创建一个项目目录
$ mkdir ansible-test
$ cd ansible-test/

# 生成项目的 ansible 配置
$ ansible-config init --disabled > ./ansible.cfg


# 修改配置
$ vim ./ansible.cfg
# 修改引用 inventory 路径为当前路径
inventory=./hosts

# 默认模块修改为 shell
module_name=shell

# 第一次连接自动信任目标主机
host_key_checking=False

创建 inventory

# 创建 inventory 文件
$ vim ./hosts 
[webservers]
192.168.111.194
192.168.111.195

[dbservers]
192.168.111.192
192.168.111.193

当前的项目目录

$ tree /root/ansible-test/
/root/ansible-test/
├── ansible.cfg
└── hosts

ansible

Ansible Ad-Hoc 的执行方式的主要命令就是 ansible 格式

ansible <host-pattern> [-m module_name] [-a args]

选项说明

--version									# 显示版本
-m MODULE_NAME, --module-name MODULE_NAME	# 指定模块,默认为 command
-v, --verbose								# 详细过程 -vv -vvv 更详细
--list-hosts								# 显示主机列表,可简写 --list
-C, --check									# 检查,并不执行
-T TIMEOUT, --timeout TIMEOUT				# 执行命令的超时时间,默认 10s
-k, --ask-pass								# 提示输入 ssh 连接密码
-K, --ask-become-pass						# 提示提权的口令
-u REMOTE_USER, --user REMOTE_USER			# 执行远程执行的用户,默认 root
-b, --become    							# 代替旧版的 sudo 切换
--become-user BECOME_USER					# 指定提权后用户,默认为 root
--become-method BECOME_METHOD				# 提权方式,默认 sudo
-f FORKS, --forks FORKS						# 指定并发同时执行 ansible 任务的主机数

ansible 的 host-pattern

  • all:表示所有 inventory 主机

    例:ansible all -m ping

  • 星号 * : 通配符

  • 冒号 : :逻辑或

  • 冒号+与符号 :&: 逻辑与

  • 感叹号 ! :逻辑非,使用到逻辑非时,不要用双引号,而使用单引号

    例:ansible 'websrvs:dbsrvs:&appsrvs:!ftpsrvs' -m ping

  • 支持正则

    例:ansible "~(web|db).*\.skynemo\.cn" -m ping

示例

# 通配符匹配,列出远程主机
$ ansible web* --list-hosts
  hosts (2):
    192.168.111.194
    192.168.111.195

    
$ ansible all --list-hosts
  hosts (4):
    192.168.111.193
    192.168.111.194
    192.168.111.195
    192.168.111.192

ansible 命令执行过程

  • 加载配置文件 ansible.cfg
  • 加载对应的模块文件,如:commandshell
  • 通过 ansible 将模块或命令生成临时的 py 文件,并将该文件传输至远程服务器的对应执行用户的家目录下:$HOME/.ansible/tmp/ansible-tmp-数字/XXX.py
  • 给文件增加执行权限 +x 并执行
  • 删除临时的 py 文件,退出

ansible 的执行状态

  • 绿色:执行成功并且不需要做改变的操作
  • 黄色:执行成功井且对目标主机做变更
  • 红色:执行失败
# 颜色可以在配置文件中修改
$ sed -rn '/\[colors\]/,+43p' ./ansible.cfg | sed '/^$/d'


[colors]
# (string) Defines the color to use on 'Changed' task status
;changed=yellow
# (string) Defines the default color to use for ansible-console
;console_prompt=white
# (string) Defines the color to use when emitting debug messages
;debug=dark gray
# (string) Defines the color to use when emitting deprecation messages
;deprecate=purple
# (string) Defines the color to use when showing added lines in diffs
;diff_add=green
# (string) Defines the color to use when showing diffs
;diff_lines=cyan
# (string) Defines the color to use when showing removed lines in diffs
;diff_remove=red
# (string) Defines the color to use when emitting error messages
;error=red
# (string) Defines the color to use for highlighting
;highlight=white
# (string) Defines the color to use when showing 'OK' task status
;ok=green
# (string) Defines the color to use when showing 'Skipped' task status
;skip=cyan
# (string) Defines the color to use on 'Unreachable' status
;unreachable=bright red
# (string) Defines the color to use when emitting verbose messages. i.e those that show with '-v's.
;verbose=blue
# (string) Defines the color to use when emitting warning messages
;warn=bright purple

使用示例

# 状态检测
$ ansible db* -m shell -a 'echo $HOSTNAME'
192.168.111.192 | CHANGED | rc=0 >>
db-mysql-2
192.168.111.193 | CHANGED | rc=0 >>
db-mysql-3


# 以 nginx 用户 su 至 root 执行状态检测
ansible web* -m ping -u nginx -k -K -b --become-method su
SSH password: 
BECOME password[defaults to SSH password]: 
192.168.111.194 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": false,
    "ping": "pong"
}
192.168.111.195 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": false,
    "ping": "pong"
}

ansible-doc

ansible-doc 用于显示模块帮助,相当于 man

格式

ansible-doc [options] [module...]

# 选项
-l,--list			# 列出可用模块
-s,--snippet		# 显示指定模块的playbook片段

使用示例

# 列出所有模块
$ ansible-doc -l

# 查看指定模块帮助,若模块没有指定完整名称,默认为:ansible.builtin.模块名
$ ansible-doc ping

# 查看指定模块 playbook 片段
$ ansible-doc -s ping

ansible-playbook

ansible-playbook 用于执行编写好的 playbook 任务

使用示例

$ vim hello.yml
- hosts: webservers
  remote_user: root
  gather_facts: no


  tasks:
    - name: hello world
      command: /usr/bin/wall helloworld


$ ansible-playbook hello.yml

PLAY [webservers] ************************************************************************************

TASK [hello world] ***********************************************************************************
changed: [192.168.111.194]
changed: [192.168.111.195]

PLAY RECAP *******************************************************************************************
192.168.111.194              : ok=1    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
192.168.111.195              : ok=1    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

ansible-vault

ansible-vault 用于加解密 yml 文件

格式

ansible-vault [create|decrypt|edit|encrypt|rekey|view]

使用示例

ansible-vault encrypt hello.yml			# 加密 yml 文件
ansible-vault decrypt hello.yml			# 解密 yml 文件
ansible-vault view hello.yml			# 查看 yml 文件
ansible-vault edit hello.yml			# 编辑 yml 文件
ansible-vault rekey hello.yml			# 修改密码
ansible-vault create new.yml			# 创建新文件

ansible-console

ansible-console 用于交互执行命令,支持 tab 键,Ansible 2.0+ 新增

提示符格式

执行用户@当前操作的主机组(当前主机数量)[f:并发数]$

常用子命令

  • forks n:设置并发数,例如:forks 10
  • cd 主机组:切换组,例如:cd webservers
  • lsit:列出当前组主机列表
  • ?|help:列出所有的内置命令

使用示例

$ ansible-console
Welcome to the ansible console. Type help or ? to list commands.

root@all (2)[f:5]$ cd webservers
root@webservers (2)[f:5]$ forks 1
root@webservers (2)[f:1]$ ping
192.168.111.194 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": false,
    "ping": "pong"
}
192.168.111.195 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": false,
    "ping": "pong"
}

root@webservers (2)[f:3]$ yum name=nginx state=present

ansible-galaxy

ansible-galaxy 可以连接 Ansible Galaxy 下载相应的 collectionroles

下载 collecton

$ ansible-galaxy collection download community.mysql

Process download dependency map
Starting collection download process to '/root/ansible-test/collections'
Downloading https://galaxy.ansible.com/download/community-mysql-3.7.2.tar.gz to /root/.ansible/tmp/ansible-local-14960zbk62vgs/tmp8izulj54/community-mysql-3.7.2-lcrp0vlu
Downloading collection 'community.mysql:3.7.2' to '/root/ansible-test/collections'
Collection 'community.mysql:3.7.2' was downloaded successfully
Writing requirements.yml file of downloaded collections to '/root/ansible-test/collections/requirements.yml'

安装 collection

$ ansible-galaxy collection install --offline /root/ansible-test/collections/community-mysql-3.7.2.tar.gz

Starting galaxy collection install process
Process install dependency map
Starting collection install process
Installing 'community.mysql:3.7.0' to '/root/.ansible/collections/ansible_collections/community/mysql'
community.mysql:3.7.0 was installed successfully

查看安装情况

# 一个是默认自带的,一个是新安装的
$ ansible-galaxy collection list | grep mysql
community.mysql 3.7.2  
community.mysql               3.7.1

使用 collection

community.mysql 3.7.2 是 Ansible 官方提供的 Ansible Collection 中的 MySQL 模块,它提供了各种 MySQL 相关的 Ansible 操作,如设置密码、配置管理等。以下是 community.mysql 模块的一个常规用法:

注:此处仅作为演示,具体 collection 的使用参考官网:Using Ansible collections — Ansible Documentation

注:MySQL 服务器上需要安装 PyMySQL

# 编写 playbook
$ vim collection-mysql-test.yaml
---
- name: 查询 MySQL 主从状态
  hosts: dbservers
  become: true
  collections:
    - community.mysql
  vars:
    mysql_user: root
    mysql_password: Qwert123..
    mysql_socket: /var/lib/mysql/mysql.sock

  tasks:
  - name: 查询 MySQL 主从状态
    community.mysql.mysql_replication:
      login_unix_socket: "{{ mysql_socket }}"
      login_user: "{{ mysql_user }}"
      login_password: "{{ mysql_password }}"
    register: mysql_replication_status

  - debug:
      var: mysql_replication_status

运行 playbook

$ ansible-playbook collection-mysql-test.yaml

Ansible 常用模块

支持的模块列表:Index of all Modules — Ansible Documentation

command 模块

功能:在远程主机执行命令。command 模块是默认模块,可以忽略 -m 选项

注:该模块不支持 $VAR><|;& 等 shell 常用符号,需要用到符号请使用 shell 模块

示例

# 查看centos发行版
$ ansible dbservers -m command -a 'chdir=/etc cat redhat-release'
192.168.111.192 | CHANGED | rc=0 >>
AlmaLinux release 9.2 (Turquoise Kodkod)
192.168.111.193 | CHANGED | rc=0 >>
AlmaLinux release 9.2 (Turquoise Kodkod)



#  添加用户
$ ansible all -m command -a 'useradd test'

shell 模块

功能:与 command 模块类似,用shell执行命令,支持各种符号,例如:*,$,>

注:调用 bash 执行命令,类似 cat /etc/passwd | awk -F':' '{print $1}' > /tmp/example 负责命令,即使使用 shell 也可能会失败。解决方法:写到脚本,copy 到远程主机,执行后再把需要的结果拉取回管理端

关联配置

将 shell 模块代替 command 模块成为默认模块

$ vim ansible.cfg 
module_name = shell  

修改默认 shell

$ vim ansible.cfg 
executable = /bin/bash 

示例

# 使用系统变量,查看远程主机名
$ ansible dbservers -m shell -a 'echo $HOSTNAME'
192.168.111.192 | CHANGED | rc=0 >>
db-mysql-2
192.168.111.193 | CHANGED | rc=0 >>
db-mysql-3


# 使用重定向符号
$ ansible dbservers -m shell -a 'df -h > /root/space.info'
192.168.111.193 | CHANGED | rc=0 >>

192.168.111.192 | CHANGED | rc=0 >>


$ ansible dbservers -m shell -a 'ls /root/space.info'
192.168.111.192 | CHANGED | rc=0 >>
/root/space.info
192.168.111.193 | CHANGED | rc=0 >>
/root/space.info

script 模块

功能:在远程主机上运行 ansible 管理端的脚本(无需执行权限)

示例

# 测试脚本,安装 mailx 并发送邮件
$ cat test.sh 
#!/bin/bash

rpm -q s-nail &> /dev/null && rpm -q sendmail &> /dev/null 

if [ $? -ne 0 ]; then
    dnf -y install s-nail sendmail &> /dev/null

    cat >> /etc/s-nail.rc << EOF
set v15-compat=on
set from=linux_notify@163.com
# @ 符号用 %40 替代 
set mta=smtp://linux_notify%40163.com:KVUVSNBCHHLUFGFV@smtp.163.com
set smtp-auth=login
EOF


fi

echo "测试邮件主机--$HOSTNAME" | s-nail -s "测试邮件" sky.nemo@outlook.com



# 远程主机运行脚本
$ ansible dbservers -m script -a '/root/ansible-test/test.sh'

copy 模块

功能:从 ansible 管理端复制文件到远程主机,如果目标已存在,默认覆盖

注:copy 模块复制目录效率较低,建议压缩后传输

# 指定目标存在时进行备份
$ ansible dbservers -m copy -a 'src=./test.sh dest=/tmp/test.sh mode=600 owner=test group=test backup=yes'

# 查看备份的文件
$ ansible dbservers -m shell -a 'ls -l  /tmp/test.sh*'
192.168.111.192 | CHANGED | rc=0 >>
-rw-------. 1 test test 435 May 28 23:18 /tmp/test.sh
192.168.111.193 | CHANGED | rc=0 >>
-rw-------. 1 test test 435 May 28 23:18 /tmp/test.sh


# 指定内容,直接生成目标文件
ansible dbservers -m copy -a "content=' line1 \n line2' dest=/tmp/test.txt"

# 复制 /etc 目录自身,注意 /etc 后面没有 /
ansible webservers -m copy -a 'src=/etc dest=/tmp'

# 复制 /etc 目录下的文件,不包括 /etc/ 目录本身,注意 /etc/ 后面有 /
ansible webservers -m copy -a 'src=/etc/ dest=/tmp'

fetch 模块

功能:从远处主机提取文件到 ansible 的管理端,不支持目录

示例

$ ansible dbservers -m fetch -a 'src=/etc/redhat-release dest=/data/os'

$ tree /data/os
/data/os
├── 192.168.111.192
│   └── etc
│       └── redhat-release
└── 192.168.111.193
    └── etc
        └── redhat-release

file 模块

file 模块文档:file – Manage files and file properties — Ansible Documentation

功能:设置文件属性,创建软连接等

示例

# 创建空文件
ansible all -m file -a 'path=/root/test.txt state=touch'
# 修改文件属性
ansible all -m file -a 'path=/root/test.txt owner=test group=test mode=777'
# 删除文件
ansible all -m file -a 'path=/root/test.txt state=absent'

# 创建目录
ansible dbservers -m file -a 'path=/data/mysql state=directory owner=test'

# 递归修改目录属性
ansible dbservers -m file -a 'path=/data/mysql state=directory owner=test group=test recurse=yes'

#创建软链接
ansible all -m file -a 'src=/etc dest|path|name=/root/etc state=link'

unarchive 模块

功能:解压压缩包,或者上传并解压

用法

  • 将 ansible 管理端上的压缩包传到远程主机,并解压到特定目录,需设置 copy=yes
  • 将远程主机上的某个压缩包解压到指定路径下,需要设置 copy=no

常见参数

  • copy:默认为 yes,当 copy=yes 时,拷贝 ansible 管理端的源文件,当 copy=no 时,解压在远程主机上的源文件
  • remote_src:和 copy 功能一样且互斥,yes 表示源文件在远程主机,no 表示源文件在 ansible 管理端
  • src:源路径,copy=yes 时,可以是 ansible 管理端上的路径;copy=no 时,可以是远程主机,甚至是 http 的路径
  • dest:远程主机上的目标路径
  • mode:设置解压后的文件权限

示例

# 源文件为 ansible 控制端
ansible all -m unarchive -a 'src=/root/foo.tar.gz dest=/tmp/foo owner=test group=test'

# 源文件为远程主机
ansible all -m unarchive -a 'src=/root/tmp.tgz dest=/tmp copy=no mode=0777'

# 源文件为 http 路径
ansible webservers -m unarchive -a 'src=https://releases.ansible.com/ansible/ansible-2.9.9.tar.gz dest=/usr/local owner=test remote_src=yes|copy=no'

archive 模块

功能:打包压缩远程主机的文件、目录,保存在远程主机上

示例

ansible all -m archive -a 'path=/etc dest=/root/tmp.tgz owner=test mode=600'

hostname 模块

功能:管理主机名

示例

ansible 192.168.111.191 -m hostname -a 'name=mysql-01'

cron 模块

功能:计划任务

支持时间设置:minute、hour、day、month、weekday

示例

# 备份数据库脚本
$ cat mysql_backup.sh 
#!/bin/bash

mysql_user=root
mysql_pass=520123
datetime=$( date +"%F_%T" )                                      

[ -f /data ] && rm -rf /data
[ -d /data ] || mkdir -p /data

mysqldump -u${mysql_user} -p${mysql_pass} -A -F -E -R --triggers --single-transaction --master-data=1 --flush-privileges --default-character-set=utf8mb4 --hex-blob | gzip > /data/mysql_${datetime}.sql.gz

# 上传脚本到远程主机
$ ansible dbservers -m copy -a 'src=/root/ansible-test/mysql_backup.sh dest=/root/ backup=yes mode=755'

# 创建定时任务
$ ansible dbservers -m cron -a 'minute=30 hour=2 day=* month=* weekday=1-5 name=backup_db job=/root/mysql_backup.sh'




# 禁用定时任务
ansible dbservers -m cron -a 'minute=30 hour=2 weekday=1-5 name=backup_db job=/root/mysql_backup.sh disabled=yes'

# 启动计划任务
ansible dbservers -m cron -a 'minute=30 hour=2 weekday=1-5 name=backup_db job=/root/mysql_backup.sh disabled=no'

# 删除计划任务
ansible dbservers -m cron -a 'name=backup_db state=absent'

dnf、yum 和 apt 模块

功能:管理软件包,dnf 模块和 yum 模块对应 RHEL、CentOS、fedora 相关版本,apt 对应 Debian 相关版本

示例

# 安装
ansible webservers -m yum -a 'name=httpd state=present'
# 删除
ansible webservers -m yum -a 'name=httpd state=absent'

service 模块

功能:管理服务

示例

# 启动服务,并设置开机自启动
ansible webservers -m service -a 'name=httpd state=started enabled=yes'


# 停止服务
ansible webservers -m service -a 'name=httpd state=stopped'

# 重启服务
ansible webservers -m service -a 'name=httpd state=restarted'

# 重新加载服务
ansible webservers -m service -a 'name=httpd state=reloaded'

group 模块

功能:管理用户组

示例

# 创建组
ansible all -m group -a 'name=nginx gid=88 system=yes'

# 删除组
ansible all -m group -a 'name=nginx state=absent'

user 模块

功能:管理用户

示例

# 创建用户
ansible all -m user -a 'name=user1 comment="test user" uid=2048 home=/data/user1 group=root'
ansible all -m user -a 'name=nginx comment=nginx uid=88 group=nginx groups="root,daemon" shell=/sbin/nologin system=yes create_home=no home=/data/nginx non_unique=yes'


# 删除用户以及家目录等数据:remove=yes
ansible all -m user -a 'name=nginx state=absent remove=yes'

# 删除用户,但不删除家目录等数据:remove=no
ansible all -m user -a 'name=user1 state=absent remove=no'

# 生成加密密码
ansible localhost -m debug -a "msg={{ '123456' | password_hash('sha512'),'salt'}}"
localhost | SUCCESS => {
    "msg": "('$6$wVjhOZejXmIr3x.b$T96xVslA5.gms66uOCrA17htOv9kd3bUQW5QLTdI9kCDiWhQ.poF32LTs31LXo2.Y12NjGLkype/dSJTLkRni.', 'salt')"
}

# 用生成的密码创建用户
ansible webservers -m user -a 'name=web1 password="$6$wVjhOZejXmIr3x.b$T96xVslA5.gms66uOCrA17htOv9kd3bUQW5QLTdI9kCDiWhQ.poF32LTs31LXo2.Y12NjGLkype/dSJTLkRni."'

lineinfile 模块

ansible 在使用 sed 进行替换时,经常会遇到需要转义的问题,而且 ansible 在遇到特殊符号进行替换时, 存在问题,无法正常进行替换

为此 ansible 提供了两个模块:lineinfile 和 replcae 模块;其中单行匹配替换使用 lineinfile 模块多行匹配替换使用 repllcae 模块

功能:相当于 sed,可以修改文件内容

regexp 参数:使用正则表达式匹配对应的行,当替换文本时,如果有多行文本都能被匹配,则只有最后面被匹配到的那行文本才会被替换,当删除文本时,如果有多行文本都能被匹配,这么这些行都会被删除

注意:如果没有匹配行,会在最后一行插入line的内容

示例

# 替换行
ansible webservers -m lineinfile -a "path=/etc/httpd/conf/httpd.conf regexp='^Listen' line='Listen 8080' "
ansible all -m   lineinfile -a "path=/etc/selinux/config regexp='^SELINUX=' 
line='SELINUX=disabled'"

# 删除行
ansible all -m lineinfile  -a 'dest=/etc/fstab state=absent regexp="^#"'

replcae 模块

功能:类似于sed,可基于正则表达式进行匹配和替换,建议使用

示例

ansible all -m replace -a "path=/etc/fstab regexp='^(UUID.*)' replace='#\1'"  
ansible all -m replace -a "path=/etc/fstab regexp='^#(UUID.*)' replace='\1'"

selinux 模块

功能:管理 SELinux 策略

示例

# 关闭 selinux
ansible all -m selinux -a 'state=disabled'

reboot 模块

功能:重启主机

示例

# 60S 定时重启
ansible webservers -m reboot -a 'reboot_timeout=60'

mount 模块

功能:挂载和卸载文件系统

示例

# 临时挂载
ansible webservers mount websrvs -m mount -a 'src="UUID=b3e48f45-f933-4c8e-a700-22a159ec9077" 
path=/home fstype=xfs opts=noatime state=present'

# 临时取消挂载
ansible webservers mount websrvs -m mount -a 'path=/home fstype=xfs opts=noatime state=unmounted'



# 永久挂载
ansible webservers -m mount -a 'src=10.0.0.8:/data/wordpress path=/var/www/html/wpcontent/uploads opts="_netdev" state=mounted'

# 永久卸载
ansible webservers -m mount -a 'src=10.0.0.8:/data/wordpress path=/var/www/html/wpcontent/uploads state=absent'

setup 模块

功能:setup 模块用于收集远程主机的系统信息,称为 facts信息。这些 facts 信息可以直接以变量的形式使用,但是如果主机 较多,会影响执行速度。playbook 中可以使用 gather_facts: no 来禁止 Ansible收集 facts 信息

示例

ansible all -m setup
ansible all -m setup -a "filter=ansible_nodename"
ansible all -m setup -a "filter=ansible_hostname"
ansible all -m setup -a "filter=ansible_domain"
ansible all -m setup -a "filter=ansible_memtotal_mb"
ansible all -m setup -a "filter=ansible_memory_mb"
ansible all -m setup -a "filter=ansible_memfree_mb"
ansible all -m setup -a "filter=ansible_os_family"
ansible all -m setup -a "filter=ansible_distribution_major_version"
ansible all -m setup -a "filter=ansible_distribution_version"
ansible all -m setup -a "filter=ansible_processor_vcpus"
ansible all -m setup -a "filter=ansible_all_ipv4_addresses"
ansible all -m setup -a "filter=ansible_architecture"
ansible all -m setup -a "filter=ansible_uptime_seconds"
ansible all -m setup -a "filter=ansible_processor*"
ansible all -m setup -a 'filter=ansible_env'

debug 模块

功能:用于输出信息,自定义输出内容或通过msg输出内容

注意:msg 后面的变量需要用双引号" " 或者单引号 ' ' 包含,建议双引号

示例 - 使用 msg 自定义输出变量格式

$ vim debug.yml
---
- hosts: dbservers
  tasks:
    - name: output var
      debug:
        msg: "HOST : {{ ansible_nodename }} - IP : {{  ansible_default_ipv4.address }}"
        

ansible-playbook debug.yml

PLAY [dbservers] *************************************************************************************************

TASK [Gathering Facts] *******************************************************************************************
ok: [192.168.111.192]
ok: [192.168.111.193]

TASK [output var] ************************************************************************************************
ok: [192.168.111.192] => {
    "msg": "HOST : db-mysql-2 - IP : 192.168.111.192"
}
ok: [192.168.111.193] => {
    "msg": "HOST : db-mysql-3 - IP : 192.168.111.193"
}
......