自动化运维工具 – Ansible 常用模块 ad-hoc

ansible ad-hoc

什么是 ad-hoc?

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

ad-hoc 模式的使用场景

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

ad-hoc 模式的命令使用

img

ad-hoc 结果返回颜色

  • 绿色:执行的任务结果没有改变
  • 黄色:执行的任务结果发生了改变
  • 红色:代表出现了故障,注意查看提示

ad-hoc 常用模块

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

Ansible-doc 帮助手册

[root@m01 ~]# ansible-doc -l        # 查看所有模块说明
[root@m01 ~]# ansible-doc copy      # 查看指定模块方法
----------搜索/EX---------------------

[root@m01 ~]# ansible-doc -s copy   # 查看指定模块参数

string:字符串(str){加引号}
int:整型(整数)
float:浮点型(小数点)
list:列表类型
dic:字典类型
bool:布尔值类型
    - yes/no
    - true/false
['苹果','香蕉','梨']
{'名字':'袁丽','性别':'娘','年龄':'-3'}

Ansible 命令模块

command (不支持复杂命令)

## 可以执行不复杂的系统命令(不支持管道符等特殊符号)
ansible web_group -a "hostname"

shell (支持复杂命令)

# 如果需要一些管道操作,则使用shell
[root@m01 ~]# ansible web_group -m shell -a "ps -ef|grep nginx" 

script (脚本模块)

# 编写脚本
[root@m01 ~]# vim /root/yum.sh
#!/usr/bin/bash
yum install -y vsftpd

#执行在管理机上的脚本
[root@m01 ~]# ansible web_group -m script -a "/root/yum.sh"

Ansible 软件管理模块

yum

[root@m01 ~]# ansible web_group -m yum -a "name=httpd state=present"
name  指定软件名                        
    - httpd                       #指定要安装的软件包名称
    - file://                     #指定本地安装路径(yum localinstall 本地rpm包)
    - http://                     #指定yum源(从远程仓库获取rpm包)

state 指定使用yum的方法
   - installed/present           #安装软件包
   - removed/absent              #移除软件包
   - latest                      #安装最新软件包

yum安装方式:
 - 从yum仓库安装 yum install -y 软件名
 - 从指定网站安装 yum install -y https://mirrors.tuna.tsinghua.edu.cn/gitlab-ce/yum/el7/gitlab-ce-11.2.0-ce.0.el7.x86_64.rpm
 - 本地安装 yum localinstall -y gitlab-ce-11.2.0-ce.0.el7.x86_64.rpm

### yum安装
[root@m01 ~]# ansible lb_group -m yum -a 'name=httpd state=present'

### 网站安装
[root@m01 ~]# ansible lb_group -m yum -a 'name=https://mirrors.tuna.tsinghua.edu.cn/gitlab-ce/yum/el7/gitlab-ce-11.2.0-ce.0.el7.x86_64.rpm state=present'

### 本地安装
[root@m01 ~]# ansible lb_group -m yum -a 'name=/root/gitlab-ce-11.2.0-ce.0.el7.x86_64.rpm state=present'

## 卸载apache
[root@m01 ~]# ansible lb_group -m yum -a 'name=httpd state=absent'

## 只下载不安装apache
[root@m01 ~]# ansible lb_group -m yum -a'name=httpd download_only=true download_dir=/tmp state=present'
[root@m01 ~]# ansible-doc yum
exclude=kernel*,foo*            #排除某些包
list=ansible                    #类似于yum list查看是否可以安装
disablerepo="epel,ol7_latest"   #禁用指定的yum仓库
download_only=true              #只下载不安装 yum install d
    -yes
    -no (默认)
download_dir                    #指定rpm的下载目录

yum_repository

#添加yum仓库
ansible all -m yum_repository -a 'name=hg_epel description="hg test epel" baseurl=http://mirrors.aliyun.com/epel/7/$basearch enabled=yes' 

[root@lb01 ~]# cat /etc/yum.repos.d/hg_epel.repo
[hg_epel]
baseurl = http://mirrors.aliyun.com/epel/7/$basearch
enabled = 1
name = hg test epel

### 使用file动作,往配置文件中追加yum仓库
[root@m01 ~]# ansible all -m yum_repository -a 'file=hg_epel name=hg_base description="base" baseurl=http://www.baidu.com enabled=yes'

[root@lb01 ~]# cat /etc/yum.repos.d/hg_epel.repo
[hg_epel]
baseurl = http://mirrors.aliyun.com/epel/7/$basearch
enabled = 1
name = hg test epel

[hg_base]
baseurl=http://www.baidu.com
enabled=1
name=base

#删除yum仓库及文件
[root@m01 ~]# ansible all -m yum_repository -a 'name=hg_base state=absent'
[root@m01 ~]# ansible all -m yum_repository -a 'file=hg_epel name=hg_base state=absent'

#开启gpgcheck
[root@m01 ~]# ansible web_group -m yum_repository -a 'name=hg_epel description=EPEL file=test_hg baseurl=https://download.fedoraproject.org/pub/base/$releasever/$basearch/ gpgcheck=yes gpgkey=http://mirrors.aliyun.com/centos/RPM-GPG-KEY-CentOS-7' -i ./hosts

[eprl]  //yum仓库名称
name=Extra Packages for Enterprise Linux7 - $basearch  // yum仓库描述
baseurl=http://mirrors.aliyun.com/epel/7/$basearch  // yum仓库地址
enabled=1  // 是否开启yum仓库 开启1 关闭0
gpgcheck=0 // 是否检查秘钥 检查1 不检查0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7 // 秘钥的路径位置

name        #指定仓库名(如果没有file,以name来命名文件名,如果有file,以file来命名文件名)
file        #yum仓库文件名
description #yum仓库描述
baseurl     #指定yum源地址
enabled     # 是否开启yum仓库
    -yes     默认
    -no
gpgcheck    #指定检查秘钥
    -no/false   不检查
    -yes/true   检查

gpgkey      # 密钥路径
enabled     #是否启用仓库
    -no
    -yes

Ansible 文件管理模块

copy

copy={cp scp chmod chown echo} 
# 下发文件
[root@m01 ~]# ansible wd -m copy -a 'src=/root/ssh_key.sh dest=/root/'

# 备份重名文件
[root@m01 ~]# ansible wd -m copy -a 'src=/root/ssh_key.sh dest=/root/ backup=yes'

# cp命令(源文件在远端目录)
[root@m01 ~]# ansible wd -m copy -a 'src=/root/ssh_key.sh dest=/root/ remote_src=yes'

# 修改权限和属主属组
 ansible wd -m copy -a 'src=/root/ssh_key.sh dest=/root/ owner=nginx group=root mode=777'

# content(类似覆盖重定向)
ansible wd -m copy -a 'content="/data 172.16.1.0/24(rw,rsync,all_squash,anonuid=666,anongid=666)" dest=/etc/exports'

src             #指定源文件路径
dest            #指定目标路径
backup          #对推送传输过去的文件,进行备份目标路径已存在的同名文件
    -yes         
    -no(默认)
content         #指定字符串,写入到文件中(相当于echo的覆盖写入)
group           #指定文件属组信息
owner           #指定文件属主信息
mode            #指定文件权限信息
remote_src      #拷贝的文件是否在远端
    -yes
    -no(默认)

file

# 创建文件,创建目录,创建软链接,创建硬链接、
file={touch mkdir ln chomd chown rm}

# 创建目录
[root@m01 ~]# ansible web_group -m file -a "path=/tmp/hg_dir state=directory"

# 创建文件
[root@m01 ~]# ansible web02 -m file -a 'path=/root/123.txt owner=root group=nginx mode=622 state=touch'

# 创建软硬链接
[root@m01 ~]# ansible web02 -m file -a 'src=/etc/passwd dest=/tmp/pass state=link'
[root@m01 ~]# ansible web02 -m file -a 'src=/etc/passwd dest=/opt/pass state=hard'

# 删除文件或目录
[root@m01 ~]# ansible web02 -m file -a 'path=/root/123 state=absent'

# 修改权限(file 前提:该文件必须存在)
[root@m01 ~]# ansible web02 -m file -a 'path=/tmp/passwd owner=nginx group=nginx'

path            #指定远程主机目录或文件信息
recurse         #递归授权
    -yes
    -no
mode        #设置文件或目录权限
owner       #设置文件或目录属主信息
group       #设置文件或目录属组信息
src         #软硬链接的源文件
dest        #软硬链接的目标路径
state 
    directory   #在远端创建目录
    file        #修改文件或目录属性
    touch       #在远端创建文件
    link(软)/hard(硬)        #link或hard表示创建链接文件
    absent      #表示删除文件或目录

get_url

# 软件下载模块 wget curl

url             #指定下载地址
dest            #指定下载的目录
group           #指定属组
owner           #指定属主
mode            #指定权限
checksum        #校验加密算法
    - md5
    - sha256

# 下载
[root@m01 ~]# ansible web02 -m get_url -a 'url=https://downloads.mysql.com/archives/get/p/23/file/mysql-5.6.38.tar.gz dest=/root'

Ansible 服务管理模块

service(常用)

服务启停

#启动crond并加入开机自启
[root@m01 ~]# ansible web_group -m service -a "name=crond state=started enabled=yes"

#停止crond并删除开机自启
[root@m01 ~]# ansible web_group -m service -a "name=crond state=stoped enabled=no"

name        # 定义要启动服务的名称
state       # 指定服务状态
    started     #启动服务 systemctl start nginx
    stopped     #停止服务 systemctl stop nginx
    restarted   #重启服务 systemctl restart nginx
    reloaded    #重载服务 systemctl reload nginx
enabled         #开机自启 systemctl enable nginx
    - yes
    - no (默认)

systemd

服务启停 
name        # 定义要启动服务的名称
state       # 指定服务状态
    started     #启动服务 systemctl start nginx
    stopped     #停止服务 systemctl stop nginx
    restarted   #重启服务 systemctl restart nginx
    reloaded    #重载服务 systemctl reload nginx
enabled         #开机自启 systemctl enable nginx
    - yes
    - no (默认)
daemon_reload:更新systemd启动脚本
    - yes
    - no (默认)
masked:禁止服务启动
    - yes
    - no (默认)

Ansible 用户管理模块

group

groupadd

name:指定组名
gid:指定组id
state:
    - present:创建
    - absent:删除

user

useradd userdel
-u:指定用户uid
-g:指定用户组或组id
-s:指定用户登录的shell
-M:不创建家目录
-m:创建家目录(迁移家目录)
-G:指定用户的附加组
-a:追加附加组
-c:指定用户注释信息
-d:迁移家目录,指定家目录的位置
-r:创建系统uid用户

name:指定用户名
comment:-c 指定用户注释信息
uid:-u 指定用户的uid
group:-g 指定用户组或gid
shell:-s 指定用户登录的shell
groups:-G 指定用户的附加组
append:-a 是否追加附加组
    - yes
    - no
state:
    - present
    - absent
remove: userdel -r 递归删除,将用户的家目录和相关文件一起删除
    - yes
    - no
move_home: -d 迁移家目录
    - yes
    - no
create_home: 是否创建家目录
    - yes :-m
    - no :-M

**6**
0:超级用户
 1-199:系统内置用户
 200-999:系统用户 -r
 1000+:普通用户

**7**
0:超级用户
 1-500:系统内置用户
 501-1000:系统用户
 1000+:普通用户

Ansible 定时任务模块

#注释信息
* * * * * 命令 &>/dev/null
分 时 日 月 周

name:指定定时任务的注释信息
minute:分钟
hour:小时
day:天
month:月
weekday:周
job:定时任务的命令
state:
    - present 启动
    - absent 关闭

# 安装ntpdate
ansible all -m yum -a 'name=ntpdate state=present'

# 创建定时任务
ansible all -m cron -a 'name="sync time" minute=*/5 job="/sbin/ntpdate time1.aliyum.com &>/dev/null" state=present'

# 修改定时任务
ansible all -m cron -a 'name="sync time" minute=*/1 hour=*/2 job="/sbin/ntpdate time1.aliyum.com &>/dev/null" state=present'

# 删除定时任务
ansible all -m cron -a '"name=sync time" state=absent'

Ansible 磁盘挂载模块

mount

path:挂载目录
src:挂载源(挂载点nfs)
fstype:file system type 指定文件系统
state:
    - mounted     // 挂载,挂载磁盘并写入/etc/fstab文件中
    - present    // 挂载,只写入/etc/fstab文件中
    - unmounted // 卸载,仅卸载,不清空/etc/fstab文件
    - absent   // 卸载,卸载并清空/etc/fstab文件

Windows:NTFS FAT32
U盘:FAT32
Linux:xfs ext3 ext4

# 挂载 mounted 对应卸载 absent
[root@m01 ~]# ansible web_group -m mount -a 'path=/var/www/html/user_data src=172.16.1.31:/data fstype=nfs state=mounted'

# 卸载 umount /var/www/html/user_data 
ansible web_group -m mount -a 'path=/var/www/html/user_data state=unmounted'

Ansible 防火墙模块

selinux

state:
    - enfocing
    - diabled
    - permissive

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

firewalld

# 开启防火墙
[root@m01 ~]# ansible all -m service -a 'name=firewalld state=started'

service:指定开启的服务
state:
    - enabled 开启
    - disabled 禁止

## 开启防火墙指定服务(临时开启,重启后失效)
[root@m01 ~]# ansible web_group -m firewalld -a 'service=http state=enabled'

## 开启防火墙指定服务(永久开启,需要重启防火墙)
[root@m01 ~]# ansible web_group -m firewalld -a 'service=https permanent=yes state=enabled'

## 放行端口
[root@m01 ~]# ansible web_group -m firewalld -a 'port=80/tcp state=enabled'

Ansible 获取主机信息模块

# 看到每台主机中所有变量
[root@m01 ~]# ansible web01 -m setup

# 查看主机名
[root@m01 ~]# ansible web01 -m setup -a 'filter=ansible_hostname'
web01 | SUCCESS => {
    "ansible_facts": {
        "ansible_hostname": "www",
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false
}

# 查看完整主机名
[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
}

# 获取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:f8:98:80",
            "mtu": 1500,
            "netmask": "255.255.255.0",
            "network": "10.0.0.0",
            "type": "ether"
        },
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false
}

# 节选网卡信息
[root@m01 ~]# ansible web01 -m setup -a 'filter=ansible_default_ipv4['address']'

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个数(只显示总的个数)。

Ansible 解压模块

unarchive

src:要解压的源文件
dest:解压到的目标路径
remote_src:要解压的包在远端的服务器上
    - yes
    - no
owner:属主
group:属组
mode:权限

Ansible 压缩模块

archive

path: 要压缩的源文件
dest: 要压缩到的目标路径
remove: 删除源文件
    - yes
    - no
format: 压缩后的后缀
exclude_path: 排除特定的文件
force_archive: 创建单文件的压缩
    - yes
    - no
# 压缩“/path/to/foo/”到“/path/to/foo.tgz”
- name: Compress directory /path/to/foo/ into /path/to/foo.tgz
  archive:
    path: /path/to/foo
    dest: /path/to/foo.tgz

# 将常规文件/path/to/foo压缩为/path/to/foo.gz并删除源文件
- name: Compress regular file /path/to/foo into /path/to/foo.gz and remove it
  archive:
    path: /path/to/foo
    remove: yes

# 创建/path/to/foo的zip归档文件
- name: Create a zip archive of /path/to/foo
  archive:
    path: /path/to/foo
    format: zip

# 创建多个文件的bz2存档,根目录为/path
- name: Create a bz2 archive of multiple files, rooted at /path
  archive:
    path:
    - /path/to/foo
    - /path/wong/foo
    dest: /path/file.tar.bz2
    format: bz2

# 创建globbed路径的bz2归档文件,同时排除特定的dirname
- name: Create a bz2 archive of a globbed path, while excluding specific dirnames
  archive:
    path:
    - /path/to/foo/*
    dest: /path/file.tar.bz2
    exclude_path:
    - /path/to/foo/bar
    - /path/to/foo/baz
    format: bz2

# 创建globbed路径的bz2存档,同时排除dirnames的glob
- name: Create a bz2 archive of a globbed path, while excluding a glob of dirnames
  archive:
    path:
    - /path/to/foo/*
    dest: /path/file.tar.bz2
    exclude_path:
    - /path/to/foo/ba*
    format: bz2

# 使用gzip压缩单个归档文件(例如,不要先用tar压缩它)
- name: Use gzip to compress a single archive (i.e don't archive it first with tar)
  archive:
    path: /path/to/foo/single.file
    dest: /path/file.gz
    format: gz

# 创建单个文件的tar.gz存档。
- name: Create a tar.gz archive of a single file.
  archive:
    path: /path/to/foo/single.file
    dest: /path/file.tar.gz
    format: gz
    force_archive: true

Ansible 数据库模块

## 数据库用户管理模块 grant all on wordpress.* to wp_user@'172.161.1.%' identified by '123';
mysql_user

name:数据库用户名 wp_user
host:数据库主机ip 172.16.1.%
password 数据库密码 123
priv:指定权限privileges 'wordpress.*:ALL'
state
    - present
    - absent

## 数据库库管理模块 create database wordpress
mysql_db
name:指定库名
state:
    - present 创建数据库
    - absent 删除数据库
    - import 导入数据
    - dump 导出数据
target:指定导入/导出的数据文件

## 数据库主从集群管理模块
mysql_replication