ansible自动化运维 ad-hoc

Ansible ad-hoc

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

2 ad-hoc模式的使用场景

比如在多台机器上查看某个进程是否启动,或拷贝指定文件到本地,等等

3 ad-hoc模式的使用场景

[root@m01 ~]# ansible 'web01' -m shell -a 'free -m'
web01 | CHANGED | rc=0 >>
              total        used        free      shared  buff/cache   available
Mem:            972         110         461          19         400         667
Swap:          2047           0        2047

4.ad-hoc返回结果颜色含义

绿色: 代表被管理端主机没有被修改
黄色: 代表被管理端主机发现变更
红色: 代表出现了故障,注意查看提示
紫色:警告

5.ad-hoc常用模块

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

6.ad-hoc帮助

#查看所有模块
[root@m01 ~]# ansible-doc -l

#常看指定模块使用方法
[root@m01 ~]# ansible-doc command
EXAMPLES:

#查看模块可以使用的参数
[root@m01 ~]# ansible-doc -s file

二、Ansible命令模块

1.command模块

[root@m01 ~]# ansible 'web01' -m command -a 'free -m'
web01 | CHANGED | rc=0 >>
              total        used        free      shared  buff/cache   available
Mem:            972         110         460          19         401         667
Swap:          2047           0        2047

#command命令不支持特殊符号
[root@m01 ~]# ansible 'web01' -m command -a "ifconfig eth0 | awk 'NR==2 {print $2}'"
web01 | FAILED | rc=1 >>
|: Unknown host
ifconfig: `--help' gives usage information.non-zero return code

#当ansible命令没指定模块时,默认使用command模块

2.shell模块

#shell模块识别特殊符号,但是不支持 $符
[root@m01 ~]# ansible 'web01' -m shell -a "ifconfig eth0 | awk 'NR==2 {print $2}'"
web01 | CHANGED | rc=0 >>
        inet 10.0.0.7  netmask 255.255.255.0  broadcast 10.0.0.255

#可以使用 撬棍 \ 转义 $符,就可以识别了
[root@m01 ~]# ansible 'web01' -m shell -a "ifconfig eth0 | awk 'NR==2 {print \$2}'"
web01 | CHANGED | rc=0 >>
10.0.0.7

3.script模块

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

#验证文件
[root@m01 ~]# ansible 'web_group' -m shell -a 'ls -ld /123'
web01 | CHANGED | rc=0 >>
drwxr-xr-x 2 root root 6 Sep 17 17:26 /123
web03 | CHANGED | rc=0 >>
drwxr-xr-x 2 root root 6 Sep 17 17:26 /123

三、Ansible软件管理模块

yum_repository      # 配置yum仓库
yum                 # 安装软件

1. yum_repository 模块

[root@m01 ~]# ansible-doc yum_repository
EXAMPLES:
  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
    
[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true

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

#添加源:不修改 file,只要name不相同就是添加源
[root@m01 ~]# ansible 'web_group' -m yum_repository -a 'name="nginx-mainline" description="nginx mainline repo" baseurl=http://nginx.org/packages/mainline/centos/7/$basearch/ gpgcheck=no enabled=yes file=nginx'

#修改源:不修改 file 和 name,改其他的内容都会修改源
[root@m01 ~]# ansible 'web_group' -m yum_repository -a 'name="nginx-mainline" description="nginx mainline repo" baseurl=http://nginx.org/packages/mainline/centos/7/$basearch/ gpgcheck=no enabled=yes file=nginx'

    name: 			#yum源 []里面的内容
    description: 	#yum源 name的值
    baseurl: 		#yum源 中的仓库地址
    file: 			#yum源的名字
    gpgcheck: 		#yum源是否检查
    mirrorlist: 	#源的列表
    enabled: no		#源是否启动
    state: 
    	absent		#删除
    	present		#添加

2.yum模块

1)语法帮助

[root@m01 ~]# ansible-doc yum
EXAMPLES:
- name: install the latest version of Apache
  yum:
    name: httpd
    state: latest

name:
	httpd						#服务的名字
	http://				 		#软件包网上的地址
	/usr/local/src/nginx-release-centos-6-0.el6.ngx.noarch.rpm		#本地的rpm包
state:
	latest						#安装最新的版本
	present						#安装
	absent						#卸载

2)yum实例

#名字安装httpd
[root@m01 ~]# ansible 'web_group' -m yum -a 'name=httpd state=present'
#类似于在远程机器上执行 yum install -y httpd

#使用网上软件包安装
1.找到网上的包
https://mirrors.aliyun.com/zabbix/zabbix/4.0/rhel/7/x86_64/zabbix-agent-4.0.1-1.el7.x86_64.rpm
2.安装
[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.1-1.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.1-1.el7.x86_64.rpm

#使用本地包安装
1.上传包(上传到web端)
2.安装
[root@m01 ~]# ansible 'web_group' -m yum -a 'name=/tmp/nginx-1.16.1-1.el7.ngx.x86_64.rpm state=present'
#类似于在远程机器上执行 yum localinstall -y /tmp/nginx-1.16.1-1.el7.ngx.x86_64.rpm

四、文件管理模块

copy                # 变更配置文件
file                # 建立目录或文件
get_url             # 下载软件

1.copy模块

1)帮助语法

[root@m01 ~]# ansible-doc copy
EXAMPLES:
- name: Copy file with owner and permissions
  copy:
    src: /srv/myfiles/foo.conf
    dest: /etc/foo.conf
    owner: foo
    group: foo
    mode: '0644'
    backup: yes
    follow: yes
    content: '# This file was moved to /etc/other.conf'
    
src: 			#源路径(要进行copy的文件,文件在控制端)
dest: 			#目标路径(在受控端)
owner: 			#文件推过去之后的属主
group: 			#文件推过去之后的属组
mode:			#文件推过去之后的权限
backup:			#文件件是否备份
	yes			#备份
	no			#不备份
follow:			#是否识别软链接
	yes
	no
content:		#直接写入内容到文件

2)模块实例

#推送nginx官方源
[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/test.conf dest=/etc/nginx/conf.d/ owner=root group=root mode=777'

#推送文件并备份
[root@m01 ~]# ansible 'web_group' -m copy -a 'src=/code/index.html dest=/code owner=nginx group=nginx mode=0644 backup=yes'

#识别软链接
[root@m01 ~]# ansible 'web_group' -m copy -a 'src=/root/test dest=/tmp owner=nginx group=nginx mode=0644 follow=yes'
[root@m01 ~]# ansible 'web_group' -m copy -a 'src=/root/test dest=/tmp owner=nginx group=nginx mode=0644 follow=no'

#直接写入内容到文件
[root@m01 ~]# ansible 'web_group' -m copy -a 'content="123456" dest=/etc/rsync_password mode=0600'

2.file模块

1)帮助语法

[root@m01 ~]# ansible-doc file
EXAMPLES:
- name: Change file ownership, group and permissions
  file:
    path: /etc/foo.conf
    owner: foo
    group: foo
    mode: '0644'
    state: link,hard,touch,directory,absent
    recurse: yes

src:			#源文件(如果做软链接就是远程机器上的文件)
dest:			#目标文件(如果做软链接就是远程机器上的链接文件)
path:			#路径/文件
owner:			#文件或目录的属主
group:			#文件或目录的属组
mode:			#文件或目录的权限
state:
	link		#软链接
	touch		#创建文件
	directory	#创建目录
	absent		#删除
recurse:		#递归操作
	yes

2)file模块实践

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

2.创建目录并授权
[root@m01 ~]# ansible 'web01' -m file -a 'path=/code state=directory owner=nginx group=nginx mode=755'
#相当于执行 mkdir /code && chown -R nginx.nginx /code && chmod 755 /code

3.递归创建目录
[root@m01 ~]# ansible 'web01' -m file -a 'path=/code/wordpress/wp-content/uploads state=directory owner=nginx group=nginx mode=755'
	1)如果目录不存在则创建并递归授权
	2)如果目录上级存在,则只授权新创建的目录

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

5.创建文件
[root@m01 ~]# ansible 'web01' -m file -a 'path=/code/1.txt state=touch owner=nginx group=nginx mode=666'

6.删除文件
[root@m01 ~]# ansible 'web01' -m file -a 'path=/code/index.html state=absent'

7.做软连接
[root@m01 ~]# ansible 'web01' -m file -a 'src=/code/wordpress dest=/code/link state=link'

#注意:
	1.创建文件时,上层目录必须存在

3. get_url 模块

1)帮助语法

[root@m01 ~]# ansible-doc get_url
EXAMPLES:
- name: Download foo.conf
  get_url:
    url: http://example.com/path/file.conf
    dest: /etc/foo.conf
    mode: '0440'
    checksum: 
    	sha256:http://example.com/path/sha256sum.txt
    	
url: 				#下载文件的地址
dest: 				#下载保存的路径
mode:				#下载之后的权限
checksum: 			#下载时进行验证
	sha256:http://example.com/path/sha256sum.txt
	md5

2)模块实例

#下载包
[root@m01 ~]# ansible 'web_group' -m get_url -a 'url=https://mirrors.aliyun.com/zabbix/zabbix/4.0/rhel/7/x86_64/zabbix-release-4.0-2.el7.noarch.rpm dest=/tmp/'

#下载包并授权
[root@m01 ~]# ansible 'web_group' -m get_url -a 'url=https://mirrors.aliyun.com/zabbix/zabbix/4.0/rhel/7/x86_64/zabbix-release-4.0-2.el7.noarch.rpm dest=/tmp/ mode=777'

#下载包时验证
[root@linux /code]# md5sum index.html 
ba1f2511fc30423bdbb183fe33f3dd0f  index.html

[root@m01 ~]# ansible 'web03' -m get_url -a 'url=http://10.0.0.7/index.html dest=/tmp mode=777 checksum=md5:ba1f2511fc30423bdbb183fe33f3dd0f'

1.service模块

1)帮助语法

[root@m01 ~]# ansible-doc service
EXAMPLES:
- name: Start service httpd, if not started
  service:
    name: httpd
    state: started
    enabled: yes
    
name: httpd			#服务的名字
state:
	started			#启动服务
	stopped			#停止服务
	restarted		#重启服务
	reloaded		#重载服务
enabled:			#开机自启
	yes
	no

2)实例

#1.停止nginx服务
[root@m01 ~]# ansible web03 -m service -a 'name=nginx state=stopped'

#2.启动httpd服务,并加入开机自启
[root@m01 ~]# ansible web03 -m service -a 'name=httpd state=started enabled=yes'

2.systemd模块

1)帮助语法

[root@m01 ~]# ansible-doc systemd
EXAMPLES:
- name: Start service httpd, if not started
  systemd:
    name: httpd
    state: started
    enabled: yes
    daemon_reload: yes
    
name: httpd			#服务的名字
state:
	started			#启动服务
	stopped			#停止服务
	restarted		#重启服务
	reloaded		#重载服务
enabled:			#开机自启
	yes
	no
daemon_reload:		        #后台启动

2)实例

#1.停止nginx服务
[root@m01 ~]# ansible web03 -m systemd -a 'name=nginx state=stopped'

#2.启动httpd服务,并加入开机自启
[root@m01 ~]# ansible web03 -m systemd -a 'name=httpd state=started enabled=yes'

3.group模块

1)帮助语法

EXAMPLES:
- name: Ensure group "somegroup" exists
  group:
    name: somegroup				#组名字
    state: 
    	present					#创建用户组
    	absent					#删除用户组
    gid: 666					#用户组ID

2)实例

#创建用户组
[root@m01 ~]# ansible web_group -m group -a 'name=www state=present gid=666'

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

4.user模块

1)帮助语法

- name: Add the user 'johnd' with a specific uid and a primary group of 'admin'
  user:
    name: johnd						#用户名
    comment: John Doe					#用户的注释
    uid: 1040						#用户id
    group: admin					#用户的组
    groups: admins,developers			        #指定附加组
    shell: /bin/bash					#指定登录脚本
    append: yes						#添加附加组时使用
    remove: yes						#移除家目录
    generate_ssh_key: yes				#是否生成密钥对
    ssh_key_bits: 2048					#秘钥加密的位数
    ssh_key_file: .ssh/id_rsa			        #秘钥文件
    expires: 1422403387					#用户的有效时间
    state:
    	present						#添加用户
    	absent						#删除用户
    create_home:yes/no     				#是否创建家目录
    password        					#给用户添加密码(单引号)

2)实践

#1.创建用户
[root@m01 ~]# ansible web_group -m user -a 'name=www uid=666 group=www shell=/sbin/nologin state=present'

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

#3.删除用户及用户组
[root@m01 ~]# ansible web_group -m user -a 'name=www state=absent remove=yes'

#注意:
	1.如果用户名字跟组名字相同,删除用户是会将组也删除
	2.当组下面有多个用户,删除的与组同名的用户也不会删除组

5.cron模块

1)帮助语法

EXAMPLES:
- name: Ensure a job that runs at 2 and 5 exists. Creates an entry like "0 5,2 * * ls -alh > /d
  cron:
    name: "check dirs"			#定时任务的注释
    minute: "0"				#分钟
    hour: "5,2"				#小时
    day: "2"				#日
    month: "2"				#月
    weekday: "2"			#周
    job: "ls -alh > /dev/null"		#定时任务的内容
    state: 
    	absent				#删除定时任务
    	present				#添加定时任务

2)实践

#1.添加定时任务
[root@m01 ~]# ansible web01 -m cron -a 'name="时间同步" minute=*/10 job="/usr/sbin/ntpdate time1.aliyun.com &> /dev/null"'

#2.修改定时任务(不修改名字,只修改内容)
[root@m01 ~]# ansible web01 -m cron -a 'name="时间同步" job="/usr/sbin/ntpdate time1.aliyun.com &> /dev/null"'

#3.删除定时任务(一定要用name参数)
[root@m01 ~]# ansible web01 -m cron -a 'name="时间同步" state=absent'

#4.注释定时任务
[root@m01 ~]# ansible web01 -m cron -a 'name="时间同步" job="/usr/sbin/ntpdate time1.aliyun.com &> /dev/null" disabled=yes'

6.磁盘挂载mount模块

1)帮助语法

EXAMPLES:
# Before 2.3, option 'name' was used instead of 'path'
- name: Mount DVD read-only
  mount:
    path: /mnt/dvd			#挂载的目录(nfs客户端)
    src: /dev/sr0			#远端被挂载的目录 (nfs服务端)
    fstype: nfs				#挂在类型
    opts: ro,noauto			#自动挂载的参数
    state: 
    	present				#写入自动挂载,但实际没有挂咋,需要重启服务器
    	unmounted			#取消临时挂载,但是没有清理自动挂载
    	mounted				#写入自动挂载,并且直接挂载了(常用)
    	absent				#取消临时挂载,并且清理自动挂载(常用)

2)准备挂载的服务端

1.安装nfs
[root@m01 ~]# ansible nfs -m yum -a 'name=nfs-utils state=present'
2.配置nfs
[root@m01 ~]# ansible nfs -m copy -a 'content="/data 172.16.1.0/24(rw,sync,all_squash,anonuid=666,anongid=666)" dest=/etc/exports'
3.创建用户
[root@m01 ~]# ansible nfs -m group -a 'name=www gid=666'
[root@m01 ~]# ansible nfs -m user -a 'name=www uid=666 group=www shell=/sbin/nologin create_home=no'
4.创建目录并授权
[root@m01 ~]# ansible nfs -m file -a 'path=/data state=directory owner=www group=www'
5.启动
[root@m01 ~]# ansible nfs -m systemd -a 'name=nfs state=started'

3)客户端使用模块挂载

#挂载目录,并加入开机自动挂载
[root@m01 ~]# ansible web01 -m mount -a 'src=172.16.1.31:/data path=/code/wordpress fstype=nfs state=mounted'

#取消挂载,并取消开机自动挂载
[root@m01 ~]# ansible web01 -m mount -a 'src=172.16.1.31:/data path=/code/wordpress fstype=nfs state=absent'

7.selinux模块

1)帮助语法

EXAMPLES:
- name: Enable SELinux
  selinux:
    policy: targeted		
    state: 
    	enforcing			#开启
    	disabled			#关闭

2)关闭selinux

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

8.firewalld模块

1)帮助语法

EXAMPLES:
- firewalld:
    service: https				#防火墙开启的服务
    permanent: 
    	yes				        #永久生效
    	no					#临时生效
    state: 
    	enabled					#开启
    	disable					#关闭
    port: 8081/tcp  161-162/udp		        #防火墙配置的端口
    zone: dmz					#指定配置空间
    rich_rule:					#富规则
    source: 192.0.2.0/24			#防火墙配置的源ip
    masquerade: 
    	yes					#开启ip伪装
    	no					#关闭ip伪装
    interface: eth2				#绑定网卡

2)防火墙配置实践

#1.允许访问http,永久生效
[root@m01 ~]# ansible web01 -m firewalld -a 'service=http permanent=yes state=enabled'

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

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

#4.允许10.0.0.0/24网段访问所有服务
[root@m01 ~]# ansible web01 -m firewalld -a 'source=10.0.0.0/24 zone=trusted state=enabled permanent=yes'

9.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'

10.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'

11.Ansible主机信息模块 setup

为什么要讲这个模块?
这个模块非常实用,在公司中总会有一些需求

比如:
1.根据不同主机不同IP创建对应IP的目录
2.根据不同主机不同主机名创建对应主机名的目录
3.自动化运维平台需要自动获取到主机的IP地址,内存信息,磁盘信息,主机名...等
4.如果安装数据库,分配内存为物理内存的80%,此时有3台不同物理内存的机器2G、4G、16G
写一个playbook的情况下,我需要获取到对应主机的内存并作出计算,写判断。

1)使用

1.获取所有主机信息
[root@m01 ~]# ansible web01 -m setup

2.获取主机名(使用setup获取的信息,指定对应的小标题获取指定的信息)
[root@m01 ~]# ansible web01 -m setup -a 'filter=ansible_fqdn'

2)常用的参数

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_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个数(只显示总的个数)。
posted @ 2020-09-17 14:45  nick_xm  阅读(285)  评论(0编辑  收藏  举报