• 欢迎访问显哥博客,本网站纯属学习技术,绝无商业用途,欢迎小伙伴们共同学习!研究技术!QQ:52249909 加我QQ
  • 世界75亿人,这么小的概率,能认识你,是我一生的幸运,不妨加个QQ接触一下:52249909 加我QQ

Ansible自动化模块——ad-hoc

Ansible lixian 4年前 (2020-03-23) 1704次浏览 1个评论 扫描二维码
文章目录[隐藏]

一、ad-hoc概述

1.什么是ad-hoc

ad-hoc简而言之就是“临时命令”,执行完即结束,并不会保存

2.ad-hoc使用场景

可以用作查看远程机器的进程,或者磁盘,或者拷贝文件

3.ad-hoc命令使用

Ansible自动化模块——ad-hoc
实例:批量查看内存信息

[root@m01 ~]# ansible webs -m command -a 'free -m' 
web01 | CHANGED | rc=0 >>
              total        used        free      shared  buff/cache   available
Mem:           1982         143        1688           9         150        1668
Swap:          1023           0        1023

web02 | CHANGED | rc=0 >>
              total        used        free      shared  buff/cache   available
Mem:           1982         142        1684           9         155        1666
Swap:          1023           0        1023

4.ad-hoc结果返回含义

绿色:代表被控端主机内容和控制端内容完全一致
黄色:代表被控端主机发生了内容的改变
粉色:提示、警告信息
红色:代表出现了故障,提示报错

5.ad-hoc常用的模块

command             # 执行shell命令(不支持管道等特殊字符)
shell               # 执行shell命令
scripts             # 执行shell脚本
yum_repository      # 配置yum仓库
yum                 # 安装软件
copy                # 变更配置文件
file                # 建立目录或文件
service             # 启动与停止服务
mount               # 挂载设备
cron                # 定时任务
get_url             # 下载软件
firewalld           # 防火墙
selinux             #selinux

5.ansible帮助

[root@m01 ~]# ansible-doc -l        # 查看所有模块说明
[root@m01 ~]# ansible-doc copy      # 查看指定模块方法
[root@m01 ~]# ansible-doc -s copy   # 查看指定模块参数

二、Ansible命令模块

1.command模块(不识别特殊符号)

默认模块,执行命令,不支持管道符、正则等特殊符号。

[root@m01 ~]# ansible all -m command -a 'free -m'
web01 | CHANGED | rc=0 >>
              total        used        free      shared  buff/cache   available
Mem:            972         114         434          13         423         668
Swap:          1023           0        1023
web02 | CHANGED | rc=0 >>
              total        used        free      shared  buff/cache   available
Mem:            972         116         439           7         416         672
Swap:          1023           0        1023

2.shell模块

支持shell的所有命令,权限较大,不建议使用。

[root@m01 ~]# ansible all -m shell -a 'ps -ef | grep httpd'
web02 | CHANGED | rc=0 >>
root      27226  27221  0 09:22 pts/0    00:00:00 /bin/sh -c ps -ef | grep httpd
root      27228  27226  0 09:22 pts/0    00:00:00 grep httpd
web01 | CHANGED | rc=0 >>
root      28156  28151  0 09:22 pts/0    00:00:00 /bin/sh -c ps -ef | grep httpd
root      28158  28156  0 09:22 pts/0    00:00:00 grep httpd

[root@m01 ~]# ansible all -m shell -a "ifconfig eth0 | awk 'NR==2 {print \$2}'"
web02 | CHANGED | rc=0 >>
10.0.0.8
web01 | CHANGED | rc=0 >>
10.0.0.7

3.script模块(脚本模块)

编写脚本:

[root@m01 ~]# vim mkdir.sh 
#!/bin/bash
mkdir /service

执行script模块ansible命令

[root@m01 ~]# ansible web_group -m script -a '/root/mkdir.sh'
web01 | CHANGED => {
    "changed": true, 
    "rc": 0, 
    "stderr": "Shared connection to web01 closed.\r\n", 
    "stderr_lines": [
        "Shared connection to web01 closed."
    ], 
    "stdout": "", 
    "stdout_lines": []
}
web02 | CHANGED => {
    "changed": true, 
    "rc": 0, 
    "stderr": "Shared connection to web02 closed.\r\n", 
    "stderr_lines": [
        "Shared connection to web02 closed."
    ], 
    "stdout": "", 
    "stdout_lines": []
}

查看验证:

[root@m01 ~]# ansible web_group -m shell -a 'ls -ld /service'
web02 | CHANGED | rc=0 >>
drwxr-xr-x 2 root root 6 Mar 18 09:37 /service
web01 | CHANGED | rc=0 >>
drwxr-xr-x 2 root root 6 Mar 18 09:37 /service

三、Ansible软件管理模块

1.yum模块

yum模块语法:

[root@m01 ~]# ansible-doc yum
  yum:
    name: httpd
    state: latest,absent,present
    
name:
	httpd				#服务名称
	http://				#安装软件的地址
	file				#安装本地的rpm包
state:
	latest				#安装最新版本的包
	present				#安装软件包(默认为安装)
	absent				#卸载软件包

实例:

#安装服务httpd
[root@m01 ~]# ansible web_group -m yum -a 'name=httpd state=present'
相当于在远程机器上:yum install -y httpd

#安装云上的服务
[root@m01 ~]# ansible web_group -m yum -a 'name=https://mirrors.aliyun.com/zabbix/zabbix/4.0/rhel/7/x86_64/zabbix-agent-4.0.0-2.el7.x86_64.rpm state=present'
相当于在远程机器上:yum install -y https://mirrors.aliyun.com/zabbix/zabbix/4.0/rhel/7/x86_64/zabbix-agent-4.0.0-2.el7.x86_64.rpm

#安装本地的rpm包(包一定先传到远程机器上)
[root@m01 ~]# ansible web_group -m yum -a 'name=/tmp/nginx-1.16.1-1.el7.ngx.x86_64.rpm'
相当于在远程机器上:yum localinstall -y /tmp/nginx-1.16.1-1.el7.ngx.x86_64.rpm

2.yum_repository模块(yum仓库模块)

yum_repository模块语法:

[root@m01 ~]# ansible-doc yum_repository
  yum_repository:
    name: epel
    description: EPEL YUM repo
    baseurl: https://download.fedoraproject.org/pub/epel/$releasever/$basearch/
    file: external_repos
    gpgcheck: no
    mirrorlist: http://mirrorlist.repoforge.org/el7/mirrors-rpmforge
    enabled: no
    state: absent

实例:

[root@m01 ~]# ansible web_group -m yum_repository -a "name=nginx description='nginx repo' baseurl=http://nginx.org/packages/centos/7/\$basearch/ gpgcheck=no enabled=yes"

被控制端查看:

[root@web01 yum.repos.d]# vim nginx.repo 
[nginx]
baseurl = http://nginx.org/packages/centos/7/$basearch/
enabled = 1
gpgcheck = 0
name = nginx repo

详解:

name		#yum源里面[]的内容
description	#yum院里面的name
baseurl		#指定yum仓库
gpgcheck	#是否校验
	yes
	no
enabled		#是否启用仓库
	yes
	no
state		
	present	#添加仓库
	absent	#删除仓库
file		#指定yum仓库名字

四、Ansible文件管理模块

1.copy模块(推送、复制、写入文件模块)

copy模块语法:

[root@m01 ~]# ansible-doc copy
  copy:
    src: /srv/myfiles/foo.conf
    dest: /etc/foo.conf
    owner: foo
    group: foo
    mode: '0644'
    backup: yes
    content: '# This file was moved to /etc/other.conf'
    follow: yes

实例:

#推送仓库文件
[root@m01 ~]# ansible web_group -m copy -a 'src=/etc/yum.repos.d/nginx.repo dest=/etc/yum.repos.d/'

#推送一个站点文件,并授权
[root@m01 ~]# ansible web_group -m copy -a 'src=/root/index.html dest=/var/www/html owner=root group=root mode=644'

#推送一个站点文件,把远程服务器的原文件备份(推送的文件必须修改内容)
[root@m01 ~]# ansible web_group -m copy -a 'src=/root/index.html dest=/var/www/html owner=root group=root mode=644 backup=yes'

#将指定内容写入指定文件
[root@m01 ~]# ansible web_group -m copy -a "content='123456' dest=/etc/rsync_password"

详解:

src			#源文件
dest		#目标文件
owner		#文件属主
group		#文件属组
mode		#文件的权限
backup		#文件是否备份
	yes
	no
follow		#是否识别软连接

2.file模块(创建目录、文件模块)

file模块语法:

[root@m01 ~]# ansible-doc file
  file:
    path: /etc/foo.conf
    owner: foo
    group: foo
    mode: '0644'
    state: directory,touch,link
    recurse: yes

实例:

#创建目录
[root@m01 ~]# ansible web_group -m file -a 'path=/code state=directory'
相当于远程机器上:mkdir /code

#创建目录并授权
[root@m01 ~]# ansible web01 -m file -a 'path=/file state=directory owner=root group=root mode=777'
相当于远程机器上:mkdir /file 并且 chmod 777  并且 chonw -R root.root

#递归创建目录,并递归授权
[root@m01 ~]# ansible web01 -m file -a 'path=/code/wordpress/wp-content/uploads state=directory owner=root group=root mode=777'

#递归授权目录
[root@m01 ~]# ansible web01 -m file -a 'path=/file state=directory owner=adm group=adm mode=755 recurse=yes'

#创建文件,并授权(创建文件的时候,必须有文件的上级目录)
[root@m01 ~]# ansible web01 -m file -a 'path=/file/1.txt state=touch owner=adm group=adm mode=755'

#做软连接
[root@m01 ~]# ansible web01 -m file -a 'src=/data/file dest=/data/file.ori state=link'
相当于远程机器上:ln -s /data/file /data/file.ori

#注意:
	1.当创建目录不存在时,递归创建会递归授权
	2.当目录存在时,递归授权只授权指定目录下的内容

详解:

path: 				#创建的文件或者目录	
owner:				#文件或目录的属主
group:				#文件或目录的属组
mode: 				#文件的权限
state:
	directory		#创建目录
	touch			#创建文件
	link			#创建软连接
		src			#链接的源文件
		dest		#软连接名字
recurse:			#是否递归授权
	yes
	no

3.get_url模块(下载模块)

get_url模块语法:

- name: Download foo.conf
  get_url:
    url: http://example.com/path/file.conf
    dest: /etc/foo.conf
    mode: '0440'
    checksum: 
    	sha256:
    	md5:

实例:

#下载文件
[root@m01 ~]# ansible 'web_group' -m get_url -a 'url=https://www.mumusir.com/download/1.txt dest=/tmp/ mode=777'

#验证文件再下载
[root@m01 ~]# ansible 'web_group' -m get_url -a 'url=https://www.mumusir.com/download/1.txt dest=/tmp/ mode=777 checksum=md5:f447b20a7fcbf53a5d5be013ea0b15af'

五、Ansible服务管理模块

1.service/systemd模块

service/systemd模块语法:

- name: Start service httpd, if not started
  service:
    name: httpd			#服务
    state: 				#状态
    	started			#启动
    	stopped			#停止
    	restarted		#重启
    	reloaded		#重载
	enable:				#是否加入开机自启
		yes
		no

实例:

#启动服务
[root@m01 ~]# ansible 'web_group' -m service -a 'name=httpd state=started'

#重启服务
[root@m01 ~]# ansible 'web_group' -m service -a 'name=httpd state=restarted'

六、Ansible用户管理模块

1.group模块

group模块语法:

- name: Ensure group "somegroup" exists
  group:
    name: somegroup				#组名字
    state: 						#状态
    	present					#创建用户组
    	absent					#删除用户组
    gid: 666					#指定gid

实例:

#创建用户组(如果用户已存在,会修改gid)
[root@m01 ~]# ansible 'web_group' -m group -a 'name=wwwww gid=666 state=present'

#删除用户组
[root@m01 ~]# ansible 'web_group' -m group -a 'name=www gid=666 state=absent'

2.user模块

user模块语法:

  user:
    name: johnd						#用户名
    comment: John Doe				#用户备注
    uid: 1040						#指定uid
    group: admin					#指定用户组
    shell: /bin/bash				#指定用户登录脚本
    generate_ssh_key: 				#是否创建秘钥对
    	yes
    	no
    ssh_key_bits: 2048				#秘钥长度
    ssh_key_file: .ssh/id_rsa		#秘钥文件位置
    state: 
    	absent						#删除用户
    	present						#创建用户
    remove: 
    	yes							#删除用户jia目录
    expires:						#用户过期时间
    create_home:
    	false/no					#不创建家目录

实例:

#创建用户,不需要登录,有家目录
[root@m01 ~]# ansible 'web_group' -m user -a 'name=www uid=666 group=www shell=/sbin/nologin state=present'

#删除用户
[root@m01 ~]# ansible 'web_group' -m user -a 'name=www state=absent'

#删除用户和家目录
[root@m01 ~]# ansible 'web_group' -m user -a 'name=www state=absent remove=yes'

注意:
1.当组的名字和用户名相同时,组也被删除
2.当组的下面有多个用户,即使组的名字和用户名相同也不会删除

七、Ansible定时任务模块

cron模块

cron模块语法:

- name: Ensure a job that runs at 2 and 5 exists. Creates an entry like "0 5,2 * * ls -alh > /dev/null"
  cron:
    name: "check dirs"				# 脚本的备注
    minute: "0"						#分钟
    hour: "5,2"						#小时
    day:							#日
    month:							#月
    weekday:						#周	
    job: "ls -alh > /dev/null"		#执行的内容
    disable:
    	yes							#注释定时任务
    	no							#解除注释

实例:

#添加定时任务
[root@m01 ~]# ansible 'web_group' -m cron -a 'name=test minute=* hour=* day=* month=* weekday=* job="/bin/bash /tmp/touch.sh"'
[root@web01 /]# crontab -l
#Ansible: test
* * * * * /bin/bash /tmp/touch.sh

#不配置时间参数,默认是*
[root@m01 ~]# ansible 'web_group' -m cron -a 'name=test job="/bin/bash /tmp/touch.sh"'
[root@web01 /]# crontab -l
#Ansible: test
* * * * * /bin/bash /tmp/touch.sh

#删除定时任务(必须指定name参数)
[root@m01 ~]# ansible 'web_group' -m cron -a 'name=test2 minute=3,15 hour=8-11 day=*/2 job="/bin/bash /tmp/touch.sh" state=absent'

#注释定时任务
[root@m01 ~]# ansible 'web_group' -m cron -a 'name=test2 minute=3,15 hour=8-11 day=*/2 job="/bin/bash /tmp/touch.sh" disabled=yes'

八、Ansible磁盘挂载模块

mount模块

mount模块语法;

- name: Mount DVD read-only
  mount:
    path: /mnt/dvd			#本地要挂在的目录
    src: /dev/sr0			#远端挂在点目录
    fstype: nfs				#挂载类型
    opts: ro,noauto			#/etc/fstab参数
    state: 
    	present				#开机才挂载,将配置写到自动挂载
    	mounted				#直接挂在,并且配置写到自动挂载(常用)
    	unmounted			#取消挂载,但是不清除/etc/fstab自动挂载配置
    	absent				#取消挂载,并清除/etc/fstab自动挂载配置(常用)

实例:

#没直接挂载,需要重启服务器或者mount -a才会挂载
[root@m01 ~]# ansible 'web_group' -m mount -a 'src=172.16.1.31:/data path=/tmp fstype=nfs opts=defaults state=present'

#直接挂在,并且配置写到自动挂载
[root@m01 ~]# ansible 'web_group' -m mount -a 'src=172.16.1.31:/data path=/tmp fstype=nfs opts=defaults state=mounted'

#取消挂载
[root@m01 ~]# ansible 'web_group' -m mount -a 'src=172.16.1.31:/data path=/tmp fstype=nfs opts=defaults state=absent'

九、Ansible防火墙模块

1.selinux模块

selinux模块语法:

- name: Enable SELinux
  selinux:
    policy: targeted
    state: disabled

实例:

#关闭selinux
[root@m01 ~]# ansible 'all' -m selinux -a 'state=disabled'

2.firewalld模块

firewalld模块语法:

- firewalld:
    service: https							#指定服务
    permanent: 								#是否永久生效
    	yes									#永久生效
    	no									#临时生效(默认)
    state: 									#状态
    	enabled								#允许
    	disabled							#禁止
    port: 									 #端口
    	8081/tcp							#指定端口
    	161-162/udp							#端口范围
    rich_rule: 								#富规则
    source: 192.0.2.0/24					#指定网段或IP
    zone: trusted							#指定空间

实例:

#允许访问http服务,永久生效,需要重启防火墙
[root@m01 ~]# ansible 'web_group' -m firewalld -a 'service=http permanent=yes state=enabled'

#允许访问80端口,临时生效
[root@m01 ~]# ansible 'web_group' -m firewalld -a 'port=80/tcp permanent=no state=enabled'

#允许10.0.0.0/24网段访问22端口
[root@m01 ~]# ansible 'web_group' -m firewalld -a 'rich_rule="rule family=ipv4 source address=10.0.0.1 service name=http accept" state=enabled'

#配置网段白名单,永久生效
[root@m01 ~]# ansible 'web_group' -m firewalld -a 'source=10.0.0.0/24 zone=trusted state=enabled permanent=yes'

十、Ansible解压缩模块

1.unarchive模块

unarchive模块语法:

- name: Extract foo.tgz into /var/lib/foo
  unarchive:
    src: foo.tgz				#压缩包的路径及文件
    dest: /var/lib/foo			#压缩到远端服务器的位置
    remote_src:
    	yes						#压缩包在被控端服务器
    	no						#压缩包在控制端

实例:

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

#解压被控端包到被控端自己
[root@m01 ~]# ansible 'web_group' -m unarchive -a 'src=/root/php.tar.gz dest=/tmp/ remote_src=yes'

2.archive模块

archive模块语法:

- name: Compress directory /path/to/foo/ into /path/to/foo.tgz
  archive:
    path: /path/to/foo					#要打包的内容
    dest: /path/to/foo.tgz				#包位置与名字

实例:

#打包被控端的文件
[root@m01 ~]# ansible 'web_group' -m archive -a 'path=/data dest=/tmp/data.tar.gz'

十一、Ansible主机信息模块

1.获取web01主机所有的信息

[root@m01 ~]# ansible web01 -m setup

2.获取Ip

[root@m01 ~]# ansible web01 -m setup -a 'filter=ansible_default_ipv4'
web01 | SUCCESS => {
    "ansible_facts": {
        "ansible_default_ipv4": {
            "address": "10.0.0.7", 
            "alias": "eth0", 
            "broadcast": "10.0.0.255", 
            "gateway": "10.0.0.2", 
            "interface": "eth0", 
            "macaddress": "00:0c:29:c6:7b:51", 
            "mtu": 1500, 
            "netmask": "255.255.255.0", 
            "network": "10.0.0.0", 
            "type": "ether"
        }, 
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false
}

3.获取主机名

[root@m01 ~]# ansible web01 -m setup -a 'filter=ansible_fqdn'
web01 | SUCCESS => {
    "ansible_facts": {
        "ansible_fqdn": "www.baidu.com", 
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false
} 

常用的值

ansible_all_ipv4_addresses:仅显示ipv4的信息。
ansible_devices:仅显示磁盘设备信息。
ansible_distribution:显示是什么系统,例:centos,suse等。
ansible_distribution_major_version:显示是系统主版本。
ansible_distribution_version:仅显示系统版本。
ansible_machine:显示系统类型,例:32位,还是64位。
ansible_eth0:仅显示eth0的信息。
ansible_hostname:仅显示主机名。
ansible_fqdn:仅显示主机名。
ansible_kernel:仅显示内核版本。
ansible_lvm:显示lvm相关信息。
ansible_memtotal_mb:显示系统总内存。
ansible_memfree_mb:显示可用系统内存。
ansible_memory_mb:详细显示内存情况。
ansible_swaptotal_mb:显示总的swap内存。
ansible_swapfree_mb:显示swap内存的可用内存。
ansible_mounts:显示系统磁盘挂载情况。
ansible_processor:显示cpu个数(具体显示每个cpu的型号)。
ansible_processor_vcpus:显示cpu个数(只显示总的个数)。

本站博主 , 版权所有丨如未注明 , 均为原创
转载请注明原文链接:Ansible自动化模块——ad-hoc
喜欢 (0)

您必须 登录 才能发表评论!

(1)个小伙伴在吐槽
  1. Reading your article helped me a lot and I agree with you. But I still have some doubts, can you clarify for me? I'll keep an eye out for your answers.
    gate.io2023-03-25 12:24