成功最有效的方法就是向有经验的人学习!

ansible常用模块使用

1. 查看支持的模块

[root@localhost ~]# ansible-doc -l

这里我们看下ansible的支持的模块个数

[root@localhost ~]# ansible-doc -l |wc -l   #查看支持的模块个数
1039
[root@localhost ~]# ansible --version        #查看我们的ansible版本号
ansible 2.3.1.0
  config file = /etc/ansible/ansible.cfg
  configured module search path = Default w/o overrides
  python version = 2.6.6 (r266:84292, Aug 18 2016, 14:53:48) [GCC 4.4.7 20120313 (Red Hat 4.4.7-17)]

2.获取模块的帮助

这里我们使用ansible-doc获取下command模块的使用方式。
记住这个命令就没有不会用的模块,ansible是一个非常容易上手的工具

[root@localhost ~]# ansible-doc command

3 command模块

command :作为ansible的默认模块,可以允许远程主机范围内的所有shell命令。

注意: 在command的命令中含有变量或特殊符号将无法正常工作(如果需要这些功能,请使用[shell]模块)

[root@localhost ~]# ansible 192.168.168.11* -m command -a 'ip addr show dev eth0'
192.168.168.115 | SUCCESS | rc=0 >>
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 00:50:56:29:8d:e2 brd ff:ff:ff:ff:ff:ff
    inet 192.168.168.115/24 brd 192.168.168.255 scope global eth0
    inet6 fe80::250:56ff:fe29:8de2/64 scope link 
       valid_lft forever preferred_lft forever

192.168.168.111 | SUCCESS | rc=0 >>
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 00:0c:29:77:77:91 brd ff:ff:ff:ff:ff:ff
    inet 192.168.168.111/24 brd 192.168.168.255 scope global eth0
    inet6 fe80::20c:29ff:fe77:7791/64 scope link 
       valid_lft forever preferred_lft forever

4. script模块

功能:在远程主机上执行主控端的脚本,相当于scp+shell组合。

[root@localhost ~]# ansible all -m script -a "/home/test.sh 12 34"

5. shell模块

功能:执行远程主机的shell脚本文件

[root@localhost ~]# ansible all -m shell -a "/home/test.sh"

shell替代command执行

[root@localhost ~]# ansible 192.168.168.11* -m shell -a 'ip addr show dev eth0'
192.168.168.111 | SUCCESS | rc=0 >>
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 00:0c:29:77:77:91 brd ff:ff:ff:ff:ff:ff
    inet 192.168.168.111/24 brd 192.168.168.255 scope global eth0
    inet6 fe80::20c:29ff:fe77:7791/64 scope link 
       valid_lft forever preferred_lft forever

192.168.168.115 | SUCCESS | rc=0 >>
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 00:50:56:29:8d:e2 brd ff:ff:ff:ff:ff:ff
    inet 192.168.168.115/24 brd 192.168.168.255 scope global eth0
    inet6 fe80::250:56ff:fe29:8de2/64 scope link 
       valid_lft forever preferred_lft forever

6. copy模块

功能: 实现主控端向目标主机copy文件。

[root@localhost ~]# ansible all -m copy -a "src=/home/test.sh dest=/tmp/ owner=root group=root mode=0755"    
#src 主控端文件位置
#dest 被控端目标位置
#owner 文件复制过去后的所有者
#group 文件复制过去后的所属组
#mode  文件的权限设定,执行a+x这种方式

7. stat模块

功能: 获取远程文件的状态信息,包括atime,ctime,mtime,md5,uid,gid等信息。

[root@localhost ~]# ansible all -m stat -a "path=/etc/sysctl.conf"

8. yum模块

功能: 安装软件包。

[root@localhost ~]# ansible all -m yum -a "name=httpd state=latest disable_gpg_check=yes enablerepo=epel"
#name 包名
#state (Choices: present, installed, latest, absent, removed)[Default: present]
#disable_gpg_check:禁止gpg检查
#enablerepo:只启动指定的repo

9. cron模块

功能:远程主机crontab配置

[root@localhost ~]# ansible all -m cron -a "name='test' hour='2-5' minute='*/5' day='1' month='3,4' weekday='1' job='ls -l' user=tom"
192.168.168.115 | SUCCESS => {
    "changed": true, 
    "envs": [], 
    "jobs": [
        "test"
    ]
}
192.168.168.111 | SUCCESS => {
    "changed": true, 
    "envs": [], 
    "jobs": [
        "test"
    ]
}

我们去被控主机看下生成的crontab作业

[root@localhost ~]# crontab  -l -u tom
#Ansible: test
*/5 2-5 1 3,4 1 ls -l

删除指定crontab

[root@localhost ~]# ansible all -m cron -a "name=test state=absent"

10. mount模块

功能: 挂载文件系统

[root@localhost ~]# ansible 192.168.168.111 -m mount -a "path=/mnt/data src=/dev/sd0 fstype=ext3 ots=ro state=present"

注:mount已经使用path代替了原来的name参数,但是name参数还是可以使用的。

11. service模块

功能: 服务管理

[root@localhost ~]# ansible all -m service -a "name=httpd state=restarted"    #启动服务
[root@localhost ~]# ansible all -m service -a "name=httpd state=running"      #查看服务状态
[root@localhost ~]# ansible all -m service -a "name=httpd state=stoped"       #停止服务

12. user模块

功能: 远程主机的用户管理

[root@localhost ~]# ansible all -m user -a "name=jerry comment=' doubi jerry'"   #添加用户 详细参数参考ansible-doc user
[root@localhost ~]# ansible all -m user -a "name=jerry state=absent remove=yes"  #删除用户

# 创建用户指定uid和gid,不创建家目录也不允许登陆
ansible dbsrvs -m user -a "name=ayunw uid=888 group=888 shell=/sbin/nologin create_home=no"
[root@ayunw ansible-example]# ansible dbsrvs -m user -a 'name=martin group=hr groups=root uid=500  shell=/bin/bash home=/home/martin comment="martin user"'

# 给新创建的用户生成ssh密钥对
ansible dbsrvs -m user -a "name=oo uid=6677 group=adm generate_ssh_key=yes ssh_key_bits=2048 ssh_key_file=.ssh/id_rsa" -i ./hosts

# 将明文密码进行hash加密,然后进行用户创建
ansible dbsrvs -m debug -a "msg={{ '123456' | password_hash('sha512', 'salt') }}"

13. fetch模块

从远程主机获取文件到ansible管理节点,但是不支持目录操作

[root@ayunw ansible-example]# ansible dbsrvs -m fetch -a "src=/etc/yum.repos.d/epel.repo dest=/usr/local/src"
10.10.10.30 | CHANGED => {
    "changed": true,
    "checksum": "2feedd589b72617f03d75c4b8a6e328cc1aad918",
    "dest": "/usr/local/src/10.10.10.30/etc/yum.repos.d/epel.repo",
    "md5sum": "bddf35db56cf6be9190fdabeae71c801",
    "remote_checksum": "2feedd589b72617f03d75c4b8a6e328cc1aad918",
    "remote_md5sum": null
}

[root@ayunw ansible-example]# ls -al /usr/local/src/10.10.10.30/etc/yum.repos.d/
total 4
drwxr-xr-x. 2 root root  23 Aug 11 15:05 .
drwxr-xr-x. 3 root root  25 Aug 11 15:05 ..
-rw-r--r--. 1 root root 664 Aug 11 15:05 epel.repo

14. file 模块

file模块
  对文件或者文件夹的操作
file的参数
    group # file的属组
    mode #file的权限
    owner #file的属主
    path #路径(必填)
        state =link   #软连接
        state =hard  #硬连接
    state #状态
        directory #目录  state=directory 创建目录
        file  无操作  state=file  时无操作
        touch 空文件  state=touch时在path路径下创建空文件
        absent 删除  #state=absent时   删除path路径的文件或者文件夹
        link 软连接 创建软连接,需要由src属性来做软连接的路由
        hard 硬链接   创建硬连接,需要由src属性来做软连接的路由
ansible web -m file -a "path=/libai state=directory owner=libai " #创建目录,并制定属主
ansible web -m file -a "path=/tmp/libai .txt state=touch mode=777" #创建文件,并指定权限
ansible web -m file -a "path=/tmp/cron src=/var/log/cron state=link" #创建软链接,链接的是自己的文件
ansible web -m file -a "path=/tmp/cron state=absent" # 删除软连接
ansible web -m file -a "path=/alex5 state=absent" #删除文件夹

# 创建软连接
[root@ayunw ansible-example]# ansible test -m file -a 'src=/etc/passwd path=/tmp/passwd.link state=link'

# 查看刚创建的/tmp下的软连接
[root@ayunw ansible-example]# ansible all -m shell -a 'ls -l /tmp/passwd.link'

# 创建文件。如果文件已经存在,则会更新文件的时间戳
[root@ayunw ansible-example]# ansible all -m file -a 'name=d.txt state=touch'

# 删除文件
[root@ayunw ansible-example]# ansible test -m file -a 'path=/tmp/cc.txt state=absent'

# 创建目录(可以递归创建,直接加上文件名即可)
# 如果state=directory,那么如果目录不存在,那么所有的子目录将被创建(而且提供权限的创建),如果目录# 已经存在,则不进行任何操作。如果state=file,文件将不会被创建
[root@ayunw ansible-example]# ansible test -m file -a 'path=/tmp/bj state=directory'

# 删除目录(可以递归删除,无需任何参数,直接加上)
[root@ayunw ansible-example]# ansible test -m file -a 'path=/tmp/bj state=absent'

# 修改文件权限等属性
[root@ayunw ansible-example]# ansible test -m file -a 'path=/tmp/bb.txt mode=700 owner=root group=root'

# 递归授权目录权限 
ansible dbsrvs -m file -a "path=/data owner=bgx group=bgx recurse=yes"

15. hostname 模块

管理远程主机上的主机名

# 查看主机名
[root@ayunw ansible-example]# ansible test -m shell -a 'hostname'

# 更改主机名
[root@ayunw ansible-example]# ansible test -m hostname -a 'name=master'

16. group 模块

用于添加远程主机上的组

[root@ayunw ansible-example]# ansible test -m group -a 'name=hr gid=2000 state=present'

17. setup 模块

可收集远程主机的facts变量的信息,相当于收集了目标主机的相关信息(如内核版本、操作系统信息、cpu、…),保存在ansible的内置变量中,之后我们有需要用到时,直接调用变量即可.这在ansible-playbook 中很有用。

[root@ayunw ansible-example]# ansible dbsrvs -m setup

# 使用setup获取ip地址以及主机名使用filter过滤
ansible dbsrvs -m setup -a 'filter=ansible_default_ipv4'
# 获取内存信息
ansible dbsrvs -m setup -a 'filter=ansible_memory_mb'

# 获取主机名
ansible dbsrvs -m setup -a 'filter=ansible_nodename'

# 仅显示与ansible相关的内存信息
ansible dbsrvs -m setup -a 'filter=ansible_*_mb'

ansible web -m setup | more:可以查看的远程主机信息:

ansible_all_ipv4_addresses #所有的ipv4地址
ansible_all_ipv6_addresses #所有的ipv6地址
ansible_architecture #系统的架构
ansible_date_time #系统时间
ansible_default_ipv4 #默认的ipv4地址
    address ip地址
    alias 网卡名称
    broadcast 广播地址
    gateway 网关
    netmask 子网掩码
    network 网段
ansible_default_ipv6 #默认的ipv6地址
ansible_device_links #系统的磁盘信息
ansible_distribution #系统名称
ansible_distribution_file_variety #系统的基于公司
ansible_distribution_major_version #系统的主版本
ansible_distribution_version #系统的全部版本
ansible_dns #系统的dns 默认udp 端口53
ansible_domain #系统的域 ldap
ipv4 #ipv4地址
ansible_env #系统的环境
ansible_fqdn #系统的完整主机名
ansible_hostname #系统的简写主机名
ansible_kernel #系统的内核版本
ansible_machine #系统的架构
ansible_memtotal_mb #系统的内存
ansible_memory_mb #系统的内存使用情况
ansible_mounts #系统的挂载信息
ansible_os_family #系统家族
ansible_pkg_mgr #系统的包管理工具
ansible_processor #系统的cpu
ansible_processor_cores #每颗cpu的核数
ansible_processor_count #cpu的颗数
ansible_processor_vcpus #cpu的个数=cpu的颗数*每颗cpu的核数
ansible_python #系统python信息
ansible_python_version #系统python的版本
ansible_system #系统名字   

18. authorized_key模块

为特定的用户账号添加或删除 SSH authorized keys

# 方法一
ansible web -m authorized_key -a "user=root key='{{lookup('file','/root/.ssh/id_rsa.pub')}}' path=/root/.ssh/authorized_keys manage_dir=no"

# 方法二、
 vim pub_ssh_key.yml
---
- hosts: webs
  remote_user: osmgr
  become: yes
  become_user: root
  become_method: sudo
  tasks:
    - name: deliver authorized_keys
      authorized_key: 
        user: osmgr
        key: "{{ lookup('file', '/home/osmgr/.ssh/id_rsa.pub') }}"
        state: present

ansible-playbook pub_ssh_key.yml

19. synchronize 模块

使用rsync 模块,系统必须安装rsync 包,否则无法使用这个模块

ansible dbsrvs -m shell -a 'yum -y install rsync'

ansible web -m synchronize -a 'src=time.sh dest=/tmp/'

20. lineinfile 模块

正则匹配,更改某个关键参数值。比如这里修改SELINUX的值

ansible dbsrvs -m shell -a 'cat /etc/selinux/config|grep "^SELINUX="'
10.10.108.30 | CHANGED | rc=0 >>
SELINUX=enforcing

# 通过lineinfifle模块修改SELinux的配置信息,改为disable
ansible dbsrvs -m lineinfile -a "path=/etc/selinux/config regexp='^SELINUX=' line='SELINUX=disabled'"

# 或者是使用ansible-playbook
vim set_selinux_disable.yml
---
- hosts: dbsrvs
  tasks:
  - name: seline modify enforcing
    lineinfile:
      dest: /etc/selinux/config
      regexp: '^SELINUX='
      line: 'SELINUX=enforcing'

# 删除/etc/fstab文件中以#号开头的行
ansible dbsrvs -m lineinfile -a "dest=/etc/fstab state=absent regexp='^#'"

21. replace 模块

和 sed 命令比较类似,用于正则匹配和替换

# 查看远端节点的 /etc/fstab 源文件
[root@ayunw ansible-example]# ansible dbsrvs -m shell -a "cat /etc/fstab"
10.10.108.30 | CHANGED | rc=0 >>

#
# /etc/fstab
# Created by anaconda on Tue Jul  5 14:09:37 2022
#
# 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
#
/dev/mapper/centos-root /                       xfs     defaults        0 0
UUID=c47c20e8-8ed5-4d86-9209-f0e8876bb9e6 /boot                   xfs     defaults        0 0
/dev/mapper/centos-swap swap                    swap    defaults        0 0

# 使用replace模块
[root@ayunw ansible-example]# ansible dbsrvs -m replace -a "path=/etc/fstab regexp=^(UUID.*) replace='#\1'"
10.10.108.30 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "msg": "1 replacements made"
}

# 查看结果
[root@ayunw ansible-example]# ansible dbsrvs -m shell -a "cat /etc/fstab"
10.10.108.30 | CHANGED | rc=0 >>

#
# /etc/fstab
# Created by anaconda on Tue Jul  5 14:09:37 2022
#
# 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
#
/dev/mapper/centos-root /                       xfs     defaults        0 0
#UUID=c47c20e8-8ed5-4d86-9209-f0e8876bb9e6 /boot                   xfs     defaults        0 0
/dev/mapper/centos-swap swap                    swap    defaults        0 0

# 将注释的UUID信息恢复
ansible dbsrvs -m replace -a "path=/etc/fstab regexp='^#(.*)' replace='\1'"

[root@ayunw ansible-example]# ansible dbsrvs -m shell -a "cat /etc/fstab"
10.10.108.30 | CHANGED | rc=0 >>

 /etc/fstab
 Created by anaconda on Tue Jul  5 14:09:37 2022

 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

/dev/mapper/centos-root /                       xfs     defaults        0 0
UUID=c47c20e8-8ed5-4d86-9209-f0e8876bb9e6 /boot                   xfs     defaults        0 0
/dev/mapper/centos-swap swap                    swap    defaults        0 0

参数说明:

\1:表示引用前面的小括号内容

22. unarchive 解压模块

1)帮助语法

- name: Unarchive a file that is already on the remote machine
  unarchive:
    src: /tmp/foo.zip            #要解压的包
    dest: /usr/local/bin        #解压到目标位置
    remote_src: 
        yes                        #要解压的包在受控端
        no                        #要解压的包在控制端

2)实例

#1.解压控制端的包到受控端
[root@m01 /package]# ansible web01 -m unarchive -a 'src=/package/php.tar.gz dest=/tmp/'

#2.解压受控端的包到受控端
[root@m01 /package]# ansible web03 -m unarchive -a 'src=/package/php.tar.gz dest=/tmp/ remote_src=yes'

23. archive 压缩模块

1)帮助语法

EXAMPLES:
- name: Compress directory /path/to/foo/ into /path/to/foo.tgz
  archive:
    path: /path/to/foo            #要压缩的文件或目录
    dest: /path/to/foo.tgz        #压缩后的文件
    format:bz2, gz, tar, xz, zip    #指定打包的类型

2)实例

#1.打包站点目录
[root@m01 /package]# ansible web01 -m archive -a 'path=/code dest=/tmp/code.tar.gz'

24. handlers

handlers
notify:handlers的name名字
notify用来触发handlers

- hosts: web
  tasks:
  - name: install
    yum: name=redis
  - name: copyfile
    copy: dest=/etc/redis.conf src=/etc/redis.conf
    tags: copy
    notify: restart
  - name: start
    service: name=redis state=started
  handlers:
  - name: restart
    service: name=redis state=restarted
    启动ansible-playbook p7.yml  #启动任务后会有handlers操作,可以配合tags来操作

可以把handlers理解成另一种tasks,handlers是另一种’任务列表’,handlers中的任务会被tasks中的任务进行”调用”,

  但是,被”调用”并不意味着一定会执行,只有当tasks中的任务”真正执行”以后(真正的进行实际操作,造成了实际的改变),

  handlers中被调用的任务才会执行,如果tasks中的任务并没有做出任何实际的操作,那么handlers中的任务即使被’调用’,也并不会执行。

赞(0) 打赏
未经允许不得转载:陈桂林博客 » ansible常用模块使用
分享到

大佬们的评论 抢沙发

全新“一站式”建站,高质量、高售后的一条龙服务

微信 抖音 支付宝 百度 头条 快手全平台打通信息流

橙子建站.极速智能建站8折购买虚拟主机

觉得文章有用就打赏一下文章作者

非常感谢你的打赏,我们将继续给力更多优质内容,让我们一起创建更加美好的网络世界!

支付宝扫一扫打赏

微信扫一扫打赏

登录

找回密码

注册