ansible的执行状态

绿色:执行成功且不需要做改变的操作
黄色:执行成功且对目标主机做变更
红色:执行失败
ansible -l #查看所有的模块
官方文档:https://docs.ansible.com
https://docs.ansible.com/ansible/latest/index.html

ping模块:主机连通性测试

[root@node1 ~]# ansible -m ping nodes

user模块

[root@node1 ~]# ansible-doc -s user
comment # 用户的描述信息
createhom # 是否创建家目录
force # 在使用’state-absent’时,行为与’userdel —force’一致
group # 指定基本组
groups # 指定附加组
home # 指定用户家目录
name # 指定用户名
password # 指定用户密码
shell # 指定用户的默认shell
remove # 在使用’state-absent’时,行为与’userdel —force’一致
state # 设置账号状态,不指定为创建,指定值为absent表示删除
system # 当创建该用户时,设置该用户为系统用户
uid # 指定用户的UID
update_password # 更新用户密码
expires # 指明密码的过期时间
……
示例:

  1. 添加系统用户,指定UID,家目录,主组及注释

image.png
到192.168.220.103验证:
image.png

  1. 删除用户及家目录

image.png

image.png

group模块

[root@node1 ~]# ansible-doc group
name # 定义组名称
gid # 定义组的GID
state # 指定组状态,默认为创建,设置值为absent为删除
system # 设置值为yes,表示创建为系统组
示例:
创建组:[root@node1 ~]# ansible -m group -a “name=eagles gid=1111 system=yes” nodes
image.png
image.png
删除组:[root@node1 ~]# ansible -m group -a “name=eagles state=absent” nodes
image.png
image.png

command模块:执行命令

  • 默认使用
    - 不支持管道、变量及重定向等操作

    示例:
    [root@node1 ~]# ansible [-m command] -a “ss -tanl” nodes
    image.png

    shell模块:执行shell命令

    • 调用bash执行命令

    • 但是某些复杂的操作即使使用shell模块也可能会失败
      解决方法:将复杂操作写到脚本中,通过script模块调用

示例:
[root@node1 ~]# ansible -m shell -a “ss -tanl | grep 22” nodes
image.png

script模块:执行shell脚本

示例:
[root@node1 ~]# ansible nodes -m script -a “echo.sh”
image.png

copy模块

参数:
backup: 在覆盖前,将源文件备份,备份文件包含时间信息
content:用于替代”src”,可以直接设定指定文件的值
dest: 必选项;要将源文件复制到远程主机的绝对路径
directory_mode: 递归设置目录的权限,默认为系统默认权限
force: 强制覆盖目的文件内容,默认为yes
others: 所有的file模块里的选项在这里都可以使用
src: 被复制到远程主机的本地文件,可以是绝对路径,也可以相对路径,如果路径是一个目录,它将递归复制

file模块

参数:
force: 强制创建软链接,一种是源文件不存在,但之后会建立的情况下;另一种是目标
软链接已经存在,需要先取消之前的软链接,然后创建新的软链接;选项 : yes | no
group:定义文件的属组
owner:定义文件的属主
mode:定义文件的权限
path: 定义文件的路径(必选项)
recurse: 递归设置文件的属性(只对目录生效)
在state=llink的情况下:
src:被链接的源文件路径
dest: 被链接到的路径
state:
directory: 创建目录文件
file: 创建普通文件
link: 创建链接文件
hard: 创建硬链接文件
touch: 创建文件不存在,会创建一个新的文件;如果存在,更新其最后修改时间
absent: 删除文件(目录)或取消链接文件
示例:
[root@node1 ~]# ansible -m file -a “path=/tmp/ansible_test.txt owner=root group=root mode=777 state=touch”
image.png
image.png

cron模块:定时任务

常见参数:
cron_file: 定时任务文件
evn: 环境变量

yum模块

常见参数:
name # 指定软件包名称
conf_file # 设定远程yum安装时所依赖的配置文件(比如:配置文件没有默认的位置)
disable_gpg_check # 安装软件包的时候 不去检查gpg
state # present 安装 | latest 安装最新 | absent 卸载
disablerepo # 临时禁止使用的yum仓库
enablerepo # 临时使用饿yum仓库
update_cache # 强制更新yum的缓存

示例:[root@node1 ~]# ansible -m yum -a “name=httpd state=latest” node2
image.png

service模块:服务模块

常见参数:
arguments # 命令行提供的额外参数
enabled # 设置开启启动
name # 服务名称
runlevel # 开机启动的级别
sleep # 在重启服务的过程中,是否等待
state # started:启动服务 | stopped:停止服务 | restarted:重启服务 | reloaded: 重载服务
示例:
ansible -m service -a “name=httpd state=restarted” node2
image.png

selinux模块

常见参数:
state # 设置 selinux模式

setup模块: 获取远程主机的详细信息