02-ansible常用模块

ansible常用模块

  • https://www.cnblogs.com/winstom/p/9791481.html
  • https://blog.csdn.net/weixin_45598345/article/details/118852309

ansible-doc

  • 此工具用来显示模块帮助,相当于man
#列出所有模块
ansible-doc -l  
#查看指定模块帮助用法
ansible-doc ping  
#查看指定模块帮助用法
ansible-doc -s  ping
#查看指定的插件
ansible-doc -t connection -l

ansible

  • Ansible Ad-Hoc 的执行方式的主要工具就是 ansible
  • 格式:ansible <host-pattern> [-m module_name] [-a args]
  • 选项说明:
--version #显示版本
-m module   #指定模块,默认为command
-v #详细过程 -vv -vvv更详细
--list-hosts #显示主机列表,可简写 --list
-C, --check   #检查,并不执行
-T, --timeout=TIMEOUT #执行命令的超时时间,默认10s
-k, --ask-pass     #提示输入ssh连接密码,默认Key验证 
-u, --user=REMOTE_USER #执行远程执行的用户,默认root
-b, --become    #代替旧版的sudo 切换
--become-user=USERNAME  #指定sudo的runas用户,默认为root
-K, --ask-become-pass  #提示输入sudo时的口令
-f FORKS, --forks FORKS #指定并发同时执行ansible任务的主机数

 ansible的Host-pattern

  • 用于匹配被控制的主机的列表
  • All :表示所有Inventory中的所有主机
  • 逻辑与
#在websrvs组并且在dbsrvs组中的主机
ansible "websrvs:&dbsrvs" -m ping
  • 逻辑非
#在websrvs组,但不在dbsrvs组中的主机
#注意:此处为单引号
ansible 'websrvs:!dbsrvs' -m ping
  • 综合逻辑
ansible 'websrvs:dbsrvs:&appsrvs:!ftpsrvs' -m ping
  • 正则表达式
ansible "websrvs:dbsrvs" -m ping
ansible "~(web|db).*\.chengzi\.com" -m ping

ansible命令执行过程

1. 加载自己的配置文件,默认/etc/ansible/ansible.cfg
2. 加载自己对应的模块文件,如:command
3. 通过ansible将模块或命令生成对应的临时py文件,并将该文件传输至远程服务器的对应执行用户
$HOME/.ansible/tmp/ansible-tmp-数字/XXX.PY文件
4. 给文件+x执行
5. 执行并返回结果
6. 删除临时py文件,退出

ansible 的执行状态

[root@centos8 ~]#grep -A 14 '\[colors\]' /etc/ansible/ansible.cfg 
[colors]
#highlight = white
#verbose = blue
#warn = bright purple
#error = red
#debug = dark gray
#deprecate = purple
#skip = cyan
#unreachable = red
#ok = green
#changed = yellow
#diff_add = green
#diff_remove = red
#diff_lines = cyan
  • 绿色:执行成功并且不需要做改变的操作
  • 黄色:执行成功并且对目标主机做变更
  • 红色:执行失败

ansible-console

  • 此工具可交互执行命令,支持tab,ansible 2.0+新增
  • 常用子命令:
    • 设置并发数: forks n 例如: forks 10
    • 切换组: cd 主机组 例如: cd web
    • 列出当前组主机列表: list
    • 列出所有的内置命令: ?或help

ansible-playbook

  • 此工具用于执行编写好的 playbook 任务
ansible-playbook hello.yml
cat hello.yml
---
#hello world yml file
- hosts: websrvs
 remote_user: root
 gather_facts: no
  
 tasks:
    - name: hello world
     command: /usr/bin/wall hello world

ansible-vault

  • 此工具可以用于加密解密yml文件
  • 格式:ansible-vault [create|decrypt|edit|encrypt|rekey|view]
ansible-vault encrypt hello.yml #加密
ansible-vault decrypt hello.yml #解密
ansible-vault view hello.yml #查看
ansible-vault edit hello.yml #编辑加密文件
ansible-vault rekey hello.yml #修改口令
ansible-vault create new.yml #创建新文件

Ansible常用模块

 

Command 模块

  • 功能:在远程主机执行命令,此为默认模块,可忽略 -m 选项
  • 注意:此命令不支持 $VARNAME < > | ; & 等,可能用shell模块实现
  • 注意:此模块不具有幂等性
ansible websrvs -m command -a 'chdir=/etc cat centos-release'
ansible websrvs -m command -a 'chdir=/etc creates=/data/f1.txt cat centos-release'
ansible websrvs -m command -a 'chdir=/etc removes=/data/f1.txt cat centos-release'
ansible websrvs -m command -a 'service vsftpd start'
ansible websrvs -m command -a 'echo zhongguo|passwd --stdin wang'   
ansible websrvs -m command -a 'rm -rf /data/'
ansible websrvs -m command -a 'echo hello > /data/hello.log'
ansible websrvs -m command -a "echo $HOSTNAME"

Shell 模块

  • 功能:和command相似,用shell执行命令,支持各种符号,比如:*,$, >
  • 注意:此模块不具有幂等性
ansible websrvs -m shell -a "echo $HOSTNAME"
ansible websrvs -m shell -a 'echo $HOSTNAME'
ansible websrvs -m shell -a 'echo centos | passwd --stdin wang'
ansible websrvs -m shell -a 'ls -l /etc/shadow'
ansible websrvs -m shell -a 'echo hello > /data/hello.log'
ansible websrvs -m shell -a 'cat /data/hello.log'

注意:调用bash执行命令,类似cat /tmp/test.md|awk -F'|' '{print $1,$2}' &>/tmp/example.txt复杂命令,即使使用shell也可能会失败
解决办法:写到脚本时,copy到远程,执行,再把需要的结果拉回执行命令的机器
范例:将shell模块代替command,设为模块 [root@ansible
~]#vim /etc/ansible/ansible.cfg #修改下面一行 module_name = shell

Script 模块

  • 功能:在远程主机上运行ansible服务器上的脚本(无需执行权限)
  • 注意:此模块不具有幂等性
ansible websrvs -m script -a /data/test.sh

Copy 模块

  • 功能:从ansible服务器主控端复制文件到远程主机
  • 注意: src=file 如果是没指明路径,则为当前目录或当前目录下的files目录下的file文件
#如目标存在,默认覆盖,此处指定先备份
ansible websrvs -m copy -a "src=/root/test1.sh dest=/tmp/test2.sh owner=wang mode=600 backup=yes"
#指定内容,直接生成目标文件    
ansible websrvs -m copy -a "content='test line1\ntest line2\n' dest=/tmp/test.txt"
#复制/etc目录自身,注意/etc/后面没有/
ansible websrvs -m copy -a "src=/etc dest=/backup"
#复制/etc/下的文件,不包括/etc/目录自身,注意/etc/后面有/
ansible websrvs -m copy -a "src=/etc/ dest=/backup"

Get_url 模块

  • 功能: 用于将文件从http、https或ftp下载到被管理机节点上
  • 常用参数如下:
url: 下载文件的URL,支持HTTP,HTTPS或FTP协议
dest: 下载到目标路径(绝对路径),如果目标是一个目录,就用服务器上面文件的名称,如果目标设置了名
称就用目标设置的名称
owner:指定属主
group:指定属组
mode:指定权限
force: 如果yes,dest不是目录,将每次下载文件,如果内容改变,替换文件。如果no,则只有在目标不存
在时才会下载该文件
checksum: 对目标文件在下载后计算摘要,以确保其完整性
           示例: checksum="sha256:D98291AC[...]B6DC7B97",
               checksum="sha256:http://example.com/path/sha256sum.txt"
url_username: 用于HTTP基本认证的用户名。 对于允许空密码的站点,此参数可以不使用`url_password'
url_password: 用于HTTP基本认证的密码。 如果未指定`url_username'参数,则不会使用`url_password'参数
validate_certs:如果“no”,SSL证书将不会被验证。 适用于自签名证书在私有网站上使用
timeout: URL请求的超时时间,秒为单位

#范例
ansible websrvs -m get_url -a 'url=http://nginx.org/download/nginx-1.18.0.tar.gz 
dest=/usr/local/src/nginx.tar.gz checksum="md5:b2d33d24d89b8b1f87ff5d251aa27eb8"'

Fetch 模块

  • 功能:从远程主机提取文件至ansible的主控端,copy相反,目前不支持目录
ansible websrvs -m fetch -a 'src=/root/test.sh dest=/data/scripts'
[root@ansible ~]#ansible all -m fetch -a 'src=/etc/redhat-release dest=/data/os'
[root@ansible ~]#tree /data/os/
/data/os/
├── 192.168.56.14
│   └── etc
│       └── redhat-release
├── 192.168.56.15
│   └── etc
│       └── redhat-release
└── 192.168.56.16
   └── etc
       └── redhat-release
6 directories, 3 files

File 模块

  • 功能:设置文件属性,创建软链接等
#创建空文件
ansible all -m file -a 'path=/data/test.txt state=touch'
#删除文件
ansible all
-m file -a 'path= /data/test.txt state=absent' #设置文件属性
ansible all
-m file -a "path=/root/test.sh owner=wang mode=755" #创建目录 ansible all -m file -a "path=/data/mysql state=directory owner=mysql group=mysql" #创建软链接 ansible all -m file -a 'src=/data/testfile path|dest|name=/data/testfile-link state=link' #创建目录 ansible all -m file -a 'path=/data/testdir state=directory' #递归修改目录属性,但不递归至子目录 ansible all -m file -a "path=/data/mysql state=directory owner=mysql group=mysql" #递归修改目录及子目录的属性 ansible all -m file -a "path=/data/mysql state=directory owner=mysql group=mysql recurse=yes"

stat 模块

  • 功能:检查文件或文件系统的状态
  • 注意:对于Windows目标,请改用win_stat模块
#选项:
path:文件/对象的完整路径(必须)
#常用的返回值判断:
exists: 判断是否存在
isuid: 调用用户的ID与所有者ID是否匹配

#案例
[root@ansible ansible]#cat stat.yml
---
- hosts: websrvs
 tasks:
    - name: check file
     stat: path=/data/mysql 
     register: st
    - name: debug
     debug:
       msg: "/data/mysql is not exist"
     when: not st.stat.exists

unarchive 模块

  • 功能:解包解压缩
  • 实现有两种用法:
    • 将ansible主机上的压缩包传到远程主机后解压缩至特定目录,设置copy=yes,此为默认值,可省略
    • 将远程主机上的某个压缩包解压缩到指定路径下,设置copy=no
  • 常见参数
copy:默认为yes,当copy=yes,拷贝的文件是从ansible主机复制到远程主机上,如果设置为copy=no,会在远程主机上寻找src源文件
remote_src:和copy功能一样且互斥,yes表示在远程主机,不在ansible主机,no表示文件在ansible主机上
src:源路径,可以是ansible主机上的路径,也可以是远程主机(被管理端或者第三方主机)上的路径,如果是远程主机上的路径,则需要设置copy=no
dest:远程主机上的目标路径
mode:设置解压缩后的文件权限
ansible all -m unarchive -a 'src=/data/foo.tgz dest=/var/lib/foo owner=wang group=bin'
ansible all -m unarchive -a 'src=/tmp/foo.zip dest=/data copy=no mode=0777'
ansible all -m unarchive -a 'src=https://example.com/example.zip dest=/data copy=no'
ansible websrvs -m unarchive -a 'src=https://releases.ansible.com/ansible/ansible-2.1.6.0-0.1.rc1.tar.gz 
dest=/data/ owner=root remote_src=yes'
ansible websrvs -m unarchive -a 'src=http://nginx.org/download/nginx-1.18.0.tar.gz dest=/usr/local/src/ copy=no'

Archive 模块

  • 功能:打包压缩保存在被管理节点
ansible websrvs -m archive -a 'path=/var/log/ dest=/data/log.tar.bz2 format=bz2 owner=wang mode=0600'

Hostname 模块

  • 功能:管理主机名
ansible node1 -m hostname -a "name=websrv"
ansible 192.168.56.18 -m hostname -a 'name=node18.chengzi.com'

Cron 模块

  • 功能:计划任务
  • 支持时间:minute,hour,day,month,weekday
#备份数据库脚本
[root@centos8 ~]#cat /root/mysql_backup.sh 
#!/bin/bash
mysqldump -A -F --single-transaction --master-data=2 -q -uroot|gzip >/data/mysql_`date +%F_%T`.sql.gz
#创建任务
ansible 192.168.56.15 -m cron -a 'hour=2 minute=30 weekday=1-5 name="backup mysql" job=/root/mysql_backup.sh'
ansible websrvs -m cron -a "minute=*/5 job='/usr/sbin/ntpdate ntp.aliyun.com &>/dev/null' name=Synctime"
#禁用计划任务
ansible websrvs -m cron -a "minute=*/5 job='/usr/sbin/ntpdate 172.20.0.1 &>/dev/null' name=Synctime disabled=yes"
#启用计划任务
ansible websrvs -m cron -a "minute=*/5 job='/usr/sbin/ntpdate 172.20.0.1 &>/dev/null' name=Synctime disabled=no"
#删除任务
ansible websrvs -m cron -a "name='backup mysql' state=absent"
ansible websrvs -m cron -a 'state=absent name=Synctime'

Yum 和 Apt 模块

  • 功能:
    • yum 管理软件包,只支持RHEL,CentOS,fedora,不支持Ubuntu其它版本
    • apt 模块管理 Debian 相关版本的软件包
#安装httpd
ansible websrvs -m yum -a 'name=httpd state=present'
#启用epel源进行安装
ansible websrvs -m yum -a 'name=nginx state=present enablerepo=epel'
#升级除kernel和foo开头以外的所有包
ansible websrvs -m yum -a 'name=* state=lastest exclude=kernel*,foo*'
#删除
ansible websrvs -m yum -a 'name=httpd state=absent' 
#查看包
ansible localhost -m yum -a "list=tree"

yum_repository 模块

- name: Add multiple repositories into the same file (1/2)
 yum_repository:
   name: epel
   description: EPEL YUM repo
   file: external_repos
   baseurl: https://download.fedoraproject.org/pub/epel/$releasever/$basearch/
   gpgcheck: no
- name: Add multiple repositories into the same file (2/2)
 yum_repository:
   name: rpmforge
   description: RPMforge YUM repo
   file: external_repos
   baseurl: http://apt.sw.be/redhat/el7/en/$basearch/rpmforge
   mirrorlist: http://mirrorlist.repoforge.org/el7/mirrors-rpmforge
   enabled: no
    
- name: Remove repository from a specific repo file
   yum_repository:
     name: epel
     file: external_repos
     state: absent
  • 创建和删除仓库
[root@ansible ~]#cat yum_repo.yml
- hosts: websrvs
 tasks:
    - name: Add multiple repositories into the same file 
     yum_repository:
       name: test
       description: EPEL YUM repo
       file: external_repos
       baseurl: https://download.fedoraproject.org/pub/epel/$releasever/$basearch/
       gpgcheck: no
        
[root@ansible ~]#ansible-playbook yum_repo.yml
[root@web1 ~]#cat /etc/yum.repos.d/external_repos.repo 
[test]
baseurl = https://download.fedoraproject.org/pub/epel/$releasever/$basearch/
gpgcheck = 0
name = EPEL YUM repo

Service 模块

  • 功能:管理服务
ansible all -m service -a 'name=httpd state=started enabled=yes'
ansible all -m service -a 'name=httpd state=stopped'
ansible all -m service -a 'name=httpd state=reloaded'
ansible all -m shell -a "sed -i 's/^Listen 80/Listen 8080/' /etc/httpd/conf/httpd.conf"
ansible all -m service -a 'name=httpd state=restarted'

User 模块

  • 功能:管理用户
#创建用户
ansible all -m user -a 'name=user1 comment="test user" uid=2048 home=/app/user1 group=root'
ansible all -m user -a 'name=nginx comment=nginx uid=88 group=nginx groups="root,daemon" shell=/sbin/nologin system=yes create_home=no home=/data/nginx non_unique=yes'
#remove=yes表示删除用户及家目录等数据,默认remove=no
ansible all -m user -a 'name=nginx state=absent remove=yes'
#生成123456加密的密码
ansible localhost -m debug -a "msg={{ '123456'|password_hash('sha512','salt')}}"
localhost | SUCCESS => {
    "msg": "$6$salt$MktMKPZJ6t59GfxcJU20DwcwQzfMvOlHFVZiOVD71w."
}
#用上面创建的密码创建用户 ansible websrvs
-m user -a 'name=test password="$6$salt$MktMKPZJ6t59GfxcJU20DwcwQzfMvOlHFVZiOVD71w."' #创建用户test,并生成4096bit的私钥 ansible websrvs -m user -a 'name=test generate_ssh_key=yes ssh_key_bits=4096 ssh_key_file=.ssh/id_rsa'

Group 模块

  • 功能:管理组
#创建组
ansible websrvs -m group -a 'name=nginx gid=88 system=yes'
#删除组
ansible websrvs -m group -a 'name=nginx state=absent

Lineinfile 模块

  • ansible在使用sed进行替换时,经常会遇到需要转义的问题,而且ansible在遇到特殊符号进行替换时,存在问题,无法正常进行替换 。
  • ansible自身提供了两个模块:lineinfile模块和replace模块,可以方便的进行替换
  • 一般在ansible当中去修改某个文件的单行进行替换的时候需要使用lineinfile模块
  • regexp参数 :使用正则表达式匹配对应的行,当替换文本时,如果有多行文本都能被匹配,则只有最后面被匹配到的那行文本才会被替换,当删除文本时,如果有多行文本都能被匹配,这么这些行都会被删除。
  • 如果想进行多行匹配进行替换需要使用replace模块
  • 功能:相当于sed,可以修改文件内容
ansible websrvs -m lineinfile -a "path=/etc/httpd/conf/httpd.conf regexp='^Listen' line='Listen 80'"
ansible all -m lineinfile -a "path=/etc/selinux/config regexp='^SELINUX=' line='SELINUX=disabled'"
ansible all -m lineinfile  -a 'dest=/etc/fstab state=absent regexp="^#"'

Replace 模块

  • 该模块有点类似于sed命令,主要也是基于正则进行匹配和替换,建议使用
ansible all -m replace -a "path=/etc/fstab regexp='^(UUID.*)' replace='#\1'"  
ansible all -m replace -a "path=/etc/fstab regexp='^#(UUID.*)' replace='\1'"

mount 挂载和卸载

  • 功能: 挂载和卸载文件系统
#临时挂载
mount websrvs -m mount -a 'src="UUID=b3e48f45-f933-4c8e-a700-22a159ec9077" path=/home fstype=xfs opts=noatime state=present'
#临时取消挂载
mount websrvs -m mount -a 'path=/home fstype=xfs opts=noatime state=unmounted'
#永久挂载
ansible websrvs -m mount -a 'src=10.0.0.8:/data/wordpress path=/var/www/html/wpcontent/uploads opts="_netdev" state=mounted'
#永久卸载
ansible websrvs -m mount -a 'src=10.0.0.8:/data/wordpress path=/var/www/html/wpcontent/uploads state=absent'

Setup 模块

  • 功能: setup 模块来收集主机的系统信息,这些 facts 信息可以直接以变量的形式使用,但是如果主机较多,会影响执行速度
  • 可以使用 gather_facts: no 来禁止 Ansible 收集 facts 信息
ansible all -m setup
ansible all -m setup -a "filter=ansible_nodename"
ansible all -m setup -a "filter=ansible_hostname"
ansible all -m setup -a "filter=ansible_domain"
ansible all -m setup -a "filter=ansible_memtotal_mb"
ansible all -m setup -a "filter=ansible_memory_mb"
ansible all -m setup -a "filter=ansible_memfree_mb"
ansible all -m setup -a "filter=ansible_os_family"
ansible all -m setup -a "filter=ansible_distribution_major_version"
ansible all -m setup -a "filter=ansible_distribution_version"
ansible all -m setup -a "filter=ansible_processor_vcpus"
ansible all -m setup -a "filter=ansible_all_ipv4_addresses"
ansible all -m setup -a "filter=ansible_architecture"
ansible all -m setup -a "filter=ansible_uptime_seconds"
ansible all -m setup -a "filter=ansible_processor*"
ansible all -m setup -a 'filter=ansible_env'
ansible all -m setup -a 'filter=ansible_python_version'
#取IP地址
ansible 10.0.0.101 -m setup -a 'filter=ansible_all_ipv4_addresses'
#取默认IP
ansible all -m setup -a 'filter="ansible_default_ipv4"'

debug模块

  • 此模块可以用于输出信息,并且通过 msg 定制输出的信息内容
  • 注意: msg后面的变量有时需要加 " " 引起来

 

posted @ 2022-08-10 02:45  西瓜的春天  阅读(78)  评论(0)    收藏  举报