首页 > 其他分享 >Ansible——模块

Ansible——模块

时间:2024-03-08 17:55:51浏览次数:25  
标签:-- backup ansible 61 Ansible master 模块 root

Ansible介绍

Ansible是一个同时管理多个远程主机的软件(任何可以通过SSH协议登录的机器),因此Ansible可以管理远程虚拟机、物理机,也可以是本地主机(linux、windows)。

Ansible通过SSH协议实现管理节点、远程节点的通信。

只要是能够SSH登录的主机完成的操作,都可以通Ansible自动化操作,比如批量复制、批量删除、批量修改、批量查看、批量安装、重启、更新等。

Anisble架构

Ansible命令语法

ansible批量管理命令主要涉及6部分

ansible主命令
指定ansible管理的主机信息,可以是主机组名、主机ip地址、或是all
调用ansible的模块参数 -m
指定用哪一个功能模块,模块的名字,如shell模块
调用对应模块的功能参数,-a
执行对应模块中的哪些功能,如hostname

ansible是新出现的自动化运维工具,基于Python开发,集合了众多运维工具(puppet、cfengine、chef、func、fabric)的优点,实现了批量系统配置、批量程序部署、批量运行命令等功能。

Options:
  -a MODULE_ARGS, --args=MODULE_ARGS    
             #module arguments
             #指定执行模块使用的参数  
  --ask-vault-pass      
             #ask for vault password
             #加密playbook文件时提示输入密码
  -B SECONDS, --background=SECONDS
             #run asynchronously, failing after X seconds(default=N/A)
             #后台运行超时时间,异步运行,X秒之后失败
  -C, --check           
             #don't make any changes; instead, try to predict some of the changes that may occur
             #模拟执行,不会真正在机器上执行(查看执行会产生什么变化)
  -D, --diff            
             #when changing (small) files and templates, show the differences in those files; works great with --check
             #当更新的文件数及内容较少时,该选项可显示这些文件不同的地方,该选项结合-C用会有较好的效果
  -e EXTRA_VARS, --extra-vars=EXTRA_VARS
             #set additional variables as key=value or YAML/JSON
             #执行命令时添加额外参数变量
  -f FORKS, --forks=FORKS
             #specify number of parallel processes to use(default=5)
             #并行任务数。FORKS被指定为一个整数,默认是5
  -h, --help            
             #show this help message and exit
             #打开帮助文档API
  -i INVENTORY, --inventory-file=INVENTORY
             #specify inventory host path(default=/etc/ansible/hosts) or comma separated host list.
             #指定要读取的Inventory文件
  -l SUBSET, --limit=SUBSET
             #further limit selected hosts to an additional pattern
             #限定执行的主机范围
  --list-hosts          
             #outputs a list of matching hosts; does not execute anything else
             #列出执行匹配到的主机,但并不会执行
  -m MODULE_NAME, --module-name=MODULE_NAME
             #module name to execute (default=command)
             #指定执行使用的模块,默认使用 command 模块
  -M MODULE_PATH, --module-path=MODULE_PATH
             #specify path(s) to module library (default=None)
             #要执行的模块的路径
  --new-vault-password-file=NEW_VAULT_PASSWORD_FILE
             #new vault password file for rekey
             #    
  -o, --one-line        
             #condense output
             #压缩输出,摘要输出.尝试一切都在一行上输出
  --output=OUTPUT_FILE  
             #output file name for encrypt or decrypt; use - for stdout
             #
  -P POLL_INTERVAL, --poll=POLL_INTERVAL
             #set the poll interval if using -B (default=15)
             #设置轮询间隔,每隔数秒。需要- B
  --syntax-check        
             #perform a syntax check on the playbook, but do not execute it
             #检查Playbook中的语法书写
  -t TREE, --tree=TREE  
             #log output to this directory
             #将日志内容保存在该输出目录,结果保存在一个文件中在每台主机上
  --vault-password-file=VAULT_PASSWORD_FILE
             #vault password file
             #
  -v, --verbose         
             #verbose mode (-vvv for more, -vvvv to enable connection debugging)
             #执行详细输出
  --version             
             #show program's version number and exit
             #显示版本


  Connection Options:
    control as whom and how to connect to hosts


    -k, --ask-pass      
             #ask for connection password
             #
    --private-key=PRIVATE_KEY_FILE, --key-file=PRIVATE_KEY_FILE
             #use this file to authenticate the connection
             #
    -u REMOTE_USER, --user=REMOTE_USER
             #connect as this user (default=None)
             #指定远程主机以USERNAME运行命令
    -c CONNECTION, --connection=CONNECTION
             #connection type to use (default=smart)
             #指定连接方式,可用选项paramiko (SSH)、ssh、local,local方式常用于crontab和kickstarts
    -T TIMEOUT, --timeout=TIMEOUT
             #override the connection timeout in seconds(default=10)
             #SSH连接超时时间设定,默认10s
    --ssh-common-args=SSH_COMMON_ARGS
             #specify common arguments to pass to sftp/scp/ssh (e.g.ProxyCommand)
             #
    --sftp-extra-args=SFTP_EXTRA_ARGS
             #specify extra arguments to pass to sftp only (e.g. -f, -l)
             #
    --scp-extra-args=SCP_EXTRA_ARGS
             #specify extra arguments to pass to scp only (e.g. -l)
             #
    --ssh-extra-args=SSH_EXTRA_ARGS
             #specify extra arguments to pass to ssh only (e.g. -R)
             #


  Privilege Escalation Options:
    control how and which user you become as on target hosts


    -s, --sudo          
             #run operations with sudo (nopasswd) (deprecated, use become)
             #相当于Linux系统下的sudo命令
    -U SUDO_USER, --sudo-user=SUDO_USER
             #desired sudo user (default=root) (deprecated, use become)
             #使用sudo,相当于Linux下的sudo命令
    -S, --su            
             #run operations with su (deprecated, use become)
             #
    -R SU_USER, --su-user=SU_USER
             #run operations with su as this user (default=root) (deprecated, use become)
             #
   -b, --become        
             #run operations with become (does not imply password prompting)
             #
    --become-method=BECOME_METHOD
             #privilege escalation method to use (default=sudo),valid choices: [ sudo | su | pbrun | pfexec | doas |dzdo | ksu | runas ]
             #
    --become-user=BECOME_USER
             #run operations as this user (default=root)
             #
    --ask-sudo-pass     
             #ask for sudo password (deprecated, use become)
             #
    --ask-su-pass       
             #ask for su password (deprecated, use become)
             #
    -K, --ask-become-pass
             #ask for privilege escalation password
             #

ansible安装部署

master-61管理机安装

yum install epel-release ansible libselinux-python -y  前提是配置好了阿里云的epel源

版本查看

ansible --version

主机清单配置文件

vim /etc/ansible/hosts
[web]
172.16.1.7
172.16.1.8
[nfs]
172.16.1.31

ansible主机登录认证

两种方式:
传统的密码认证
密钥管理
ansible基于公私钥认证
1.将master61机器的公钥,分发给想免密登录的机器
2.后续在对该机器操作,就直接进行ssh的公钥认证了,可以免密码,直接远程执行

[root@master-61 ~]#ansible web -m ping
172.16.1.8 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}

基于密码认证
在你的客户端机器、修改了ssh默认端口、以及密码需要修改主机清单文件才可以正确连接。
注意你得配置允许密码登录才能进行如下测试,可以再开一个web-9机器。
ansible主机清单配置文件语法(重要)

如给rsync机器,进行密码认证

[root@master-61 ~]#tail -2 /etc/ansible/hosts 
[backup]   可以写成主机名
172.16.1.41 ansible_port=22999 ansible_user=root ansible_password=123123  

修改被管理机的端口

vim /etc/ssh/sshd_config 将Port 22 改为 22999
测试执行

[root@master-61 ~]#ansible backup -m ping
172.16.1.41 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}

添加web机器组的信息

[root@master-61 ~]#tail /etc/ansible/hosts 

[web]
172.16.1.7 ansible_port=22999 ansible_user=root ansible_password=123123
172.16.1.8 ansible_port=22999 ansible_user=root ansible_password=123123

[nfs]
172.16.1.31

[backup]
172.16.1.41 ansible_ssh_port=22999 ansible_ssh_user=root ansible_ssh_pass=123123

测试执行

ansible web -m ping

同一组连续的ip

[web]
172.16.1.[7:9]

公共变量
当主机清单里,很多主机组,有相同的变量属性,可以写成公共变量 这部分配置是针对web主机组,抽象的变量

[web:vars]
ansible_ssh_port=22999
ansible_ssh_user=root
ansible_ssh_pass=123123
[web]
172.16.1.[7:9]
[nfs]
172.16.1.31 ansible_ssh_port=22999 
[backup]
172.16.1.41 ansible_ssh_port=22999 ansible_ssh_user=root ansible_ssh_pass=123123

测试

ansible web -m ping

所有主机都生效的变量(最终版)
指定主机组名all,即可针对所有主机生效,前提是,你要确保这个信息是所有主机通用的。

[all:vars]
ansible_port=22999
#ansible_user=root
#ansible_password=123123

[web]
172.16.1.7
172.16.1.8
172.16.1.9

[nfs]
172.16.1.31

[backup]
172.16.1.41

ansible命令执行方式

利用ansible命令实现批量管理(ad-hoc)模式
利用ansible剧本实现批量管理(playbook)模式
ad-hoc模式
该模式通常用来临时处理一些任务。例如

临时批量查看所有被管控机器的内存、负载、磁盘
临时批量分发某个特定文件

Playbook模式
定制化的批量执行任务,例如

一键安装Rsync
一键搭建LNMP集群等
ansible-doc命令
列出ansible所有支持的模块,这就是ansible这个万能工具箱所有的零件了。

[root@master-61 ~]#ansible-doc -l |grep ^ping
ping                                                          Try to connect to host, verify a usable python and re...
pingdom                                                       Pause/unpause Pingdom alerts   


[root@master-61 ~]#ansible-doc -l |grep ^shell
shell  


当前ansible支持3387个模块
[root@master-61 ~]#ansible-doc -l |wc -l
3387

查看某个模块的具体用法

[root@master-61 ~]#ansible-doc -s shell

[root@master-61 ~]#ansible-doc -s ping

ansible执行命令结果(状态颜色)

绿色:命令以用户期望的执行了,但是状态没有发生改变;

黄色:命令以用户期望的执行了,并且状态发生了改变;

紫色:警告信息,说明ansible提示你有更合适的用法;

红色:命令错误,执行失败;

蓝色: 详细的执行过程;

官网文档

https://docs.ansible.com/ansible/latest/collections/ansible/builtin/index.html#plugins-in-ansible-builtin

1 ping测试连通性

命令语法
ansible 主机组 -m 模块名 [模块参数]
查看模块解释

[root@master-61 ~]#ansible-doc -s ping
- name: Try to connect to host, verify a usable python and return `pong' on success
  ping:
      data:                  # Data to return for the `ping' return value. If this parameter is set to `crash', the
                               module will cause an exception.
[root@master-61 ~]#

执行

[root@master-61 ~]#ansible web -m ping
172.16.1.8 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}

2 command 简单命令模块

语法

[root@master-61 ~]#ansible-doc -s command

ansible 主机组 -m command -a "需要批量执行的命令"

command模块是ansible命令基本模块

使用command模块执行远程命令,命令不得用变量($HOME)
不得出现特殊符号< 、>、|、;、&,否则无法识别,需要则使用shell模块实现
也就是无法使用复杂的linux命令

远程查看主机名

ansible web -m command -a hostname
172.16.1.7 | CHANGED | rc=0 >>
web-7

简写,command是ansible的基础模块,默认就是-m command

ansible web -a hostname

关闭告警信息

[root@master-61 ~]#ansible web -m command -a "touch /opt/超哥带你学linux.log warn=False"

使用command提供的专有命令

Command练习
备份/var/log日志目录

[root@master-61 ~]#ansible backup -m command -a "tar -zcf /opt/log.tgz var/log chdir=/"

在/opt下创建chaoge666.log

[root@master-61 ~]#ansible backup -m command -a "touch chaoge666.log chdir=/opt"

备份/etc所有配置文件到 /backup_config/etc.tgz 。练习removes命令

1.这里就得提前考虑 /backup_config文件夹是否存在,必须先有文件夹,才能执行该备份命令


2.判断如果该文件夹不存在,则不执行备份
[root@master-61 ~]#ansible backup -m command -a 'tar -zcf /backup_config/etc.tgz removes=/backup_config'
172.16.1.41 | SUCCESS | rc=0 >>
skipped, since /backup_config does not exist


3.你必须先创建该文件夹
[root@master-61 ~]#ansible backup -m command -a 'mkdir /backup_config'

4.再次执行该命令
[root@master-61 ~]#ansible backup -m command -a 'tar -zcf /backup_config/etc.tgz /etc removes=/backup_config'

测试creates命令,如果目标目录已经存在了,就别创建该目录了

[root@master-61 ~]#ansible backup -m command -a 'mkdir /opt creates=/opt'
172.16.1.41 | SUCCESS | rc=0 >>
skipped, since /opt exists

执行命令,且忽略警告,要求你已经确认该命令是无误的

[root@master-61 ~]#ansible backup -m command -a 'touch /home/于超老师带你学ansible.log warn=False'
172.16.1.41 | CHANGED | rc=0 >>

3 shell模块(万能模块)

shell模块功能:在远程节点上执行命令(复杂的命令)

Shell练习
远程过滤ssh进程信息

[root@master-61 ~]#
[root@master-61 ~]#ansible backup -m shell -a 'ps -ef|grep ssh'
172.16.1.41 | CHANGED | rc=0 >>
root       2088      1  0 16:34 ?        00:00:00 sshd: root@pts/0
root       2128      1  0 16:37 ?        00:00:00 /usr/sbin/sshd -D
root       3951   2128  0 19:36 ?        00:00:00 sshd: root@pts/1
root       5907   2128  0 19:57 ?        00:00:00 sshd: root@pts/2
root       6099   6098  0 19:58 pts/2    00:00:00 /bin/sh -c ps -ef|grep ssh
root       6101   6099  0 19:58 pts/2    00:00:00 /bin/sh -c ps -ef|grep ssh

使用重定向符号,创建文件

[root@master-61 ~]#ansible backup -m shell -a "echo 超哥带你学ansible >> /tmp/t1.log"
172.16.1.41 | CHANGED | rc=0 >>

[root@master-61 ~]#ansible backup -m shell -a "echo 超哥带你学ansible >> /tmp/t1.log"
172.16.1.41 | CHANGED | rc=0 >>

[root@master-61 ~]#ansible backup -m shell -a "cat /tmp/t1.log"
172.16.1.41 | CHANGED | rc=0 >>
超哥带你学ansible
超哥带你学ansible

远程执行复杂linux命令
这个命令就无法在command中执行

通过一条命令,做如下事情

创建文件夹
生成sh脚本文件
赋予脚本可执行权限
执行脚本
忽略warning信息

[root@master-61 ~]#ansible backup -m shell -a "mkdir -p /server/scripts/;echo 'hostname' > /server/scripts/hostname.sh;chmod +x /server/scripts/hostname.sh;/usr/bin/bash /server/scripts/hostname.sh"

[WARNING]: Consider using the file module with state=directory rather than running 'mkdir'.  If you need to use command
because file is insufficient you can add 'warn: false' to this command task or set 'command_warnings=False' in
ansible.cfg to get rid of this message.
172.16.1.41 | CHANGED | rc=0 >>
rsync-41

4 copy拷贝文件

copy模块是远程推送数据模块,只能把数据推送给远程主机节点,无法拉取数据到本地。

既然是文件拷贝,可用参数也就是围绕文件属性。

语法

ansible 主机组 -m copy -a "参数"

copy练习
简单发送文件

[root@master-61 ~]#ansible backup -m copy -a 'src=/tmp/chaoge.log dest=/opt/'

[root@master-61 ~]#ansible backup -m shell -a 'ls /opt'
172.16.1.41 | CHANGED | rc=0 >>
chaoge.log

发送文件且指定文件属性
权限改为600、修改为www用户(要求目标机器存在该用户)

创建www用户
[root@master-61 ~]#ansible backup -m shell -a "useradd www"

远程拷贝文件,修改权限
[root@master-61 ~]#ansible backup -m copy -a "src=/opt/master61.log  dest=/tmp/ owner=www group=www mode=600"

远程检查文件信息
[root@master-61 ~]#ansible backup -m shell -a "ls -l /tmp/master61.log"

发送文件且先做好备份
使用backup参数,防止覆盖远程文件,丢失备份,提前备份该目标机器的数据

1.检查目标机器的文件
[root@master-61 ~]#ansible backup -m shell -a "cat /opt/master61.log"
172.16.1.41 | CHANGED | rc=0 >>
超哥牛比


2.远程拷贝文件,且做好备份
[root@master-61 ~]#ansible backup -m copy -a "src=/opt/master61.log  dest=/opt/ owner=www group=www mode=600 backup=yes"
172.16.1.41 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "backup_file": "/opt/master61.log.14596.2022-04-25@15:49:21~", 
    "changed": true, 
    "checksum": "da39a3ee5e6b4b0d3255bfef95601890afd80709", 
    "dest": "/opt/master61.log", 
    "gid": 1889, 
    "group": "www", 
    "md5sum": "d41d8cd98f00b204e9800998ecf8427e", 
    "mode": "0600", 
    "owner": "www", 
    "size": 0, 
    "src": "/root/.ansible/tmp/ansible-tmp-1650872960.6-29130-227131703855286/source", 
    "state": "file", 
    "uid": 1889
}

3.发现ansible帮你做好了备份
[root@master-61 ~]#ansible backup -m shell -a "ls /opt -l"
172.16.1.41 | CHANGED | rc=0 >>
total 4
-rw------- 1 www  www   0 Apr 25 15:49 master61.log
-rw-r--r-- 1 root root 13 Apr 25 15:47 master61.log.14596.2022-04-25@15:49:21~

指定数据写入到远程文件中
向rsyncd.conf中填入账号密码,覆盖其原有的文件内容

[root@master-61 ~]#ansible backup -m copy -a "content='rsync_backup:yuchao666' dest=/etc/rsync.passwd mode=600" 

[root@master-61 ~]#ansible backup -m shell -a "cat /etc/rsync.passwd"
172.16.1.41 | CHANGED | rc=0 >>
rsync_backup:yuchao666

注意像这样的覆盖操作,还是添加备份参数更合适

[root@master-61 ~]#ansible backup -m copy -a "content='rsync_backup:chaoge666' dest=/etc/rsync.passwd mode=600 backup=yes" 

[root@master-61 ~]#ansible backup -m shell -a 'ls /etc/rsync*'

复制文件夹,注意结尾斜杠

[root@master-61 ~]#mkdir /opt/yuchao/666/sixsixsix -p


远程拷贝/opt/yuchao/下的所有内容
[root@master-61 ~]#ansible backup -m copy -a  "src=/opt/yuchao/ dest=/opt/"


远程拷贝/opt/yuchao整个目录到目标机器
[root@master-61 ~]#ansible backup -m copy -a  "src=/opt/yuchao dest=/opt/"

5 file文件操作模块

file模块作用是创建、以及设置文件目录属性。

file模块可以帮助我们完成一些对文件的基本操作,比如,创建文件或目录、删除文件或目录、修改文件权限等



此处我们介绍一些file模块的常用参数,然后再给出对应示例。

path参数 :必须参数,用于指定要操作的文件或目录,在之前版本的ansible中,使用dest参数或者name参数指定要操作的文件或目录,为了兼容之前的版本,使用dest或name也可以。

state参数 :此参数非常灵活,此参数对应的值需要根据情况设定,比如,当我们需要在远程主机中创建一个目录的时候,我们需要使用path参数指定对应的目录路径,假设,我想要在远程主机上创建/testdir/a/b目录,那么我则需要设置path=/testdir/a/b,但是,我们无法从"/testdir/a/b"这个路径看出b是一个文件还是一个目录,ansible也同样无法单单从一个字符串就知道你要创建文件还是目录,所以,我们需要通过state参数进行说明,当我们想要创建的/testdir/a/b是一个目录时,需要将state的值设置为directory,"directory"为目录之意,当它与path结合,ansible就能知道我们要操作的目标是一个目录,同理,当我们想要操作的/testdir/a/b是一个文件时,则需要将state的值设置为touch,当我们想要创建软链接文件时,需将state设置为link,想要创建硬链接文件时,需要将state设置为hard,当我们想要删除一个文件时(删除时不用区分目标是文件、目录、还是链接),则需要将state的值设置为absent,"absent"为缺席之意,当我们想让操作的目标"缺席"时,就表示我们想要删除目标。

src参数 :当state设置为link或者hard时,表示我们想要创建一个软链或者硬链,所以,我们必须指明软链或硬链链接的哪个文件,通过src参数即可指定链接源。

force参数  :  当state=link的时候,可配合此参数强制创建链接文件,当force=yes时,表示强制创建链接文件,不过强制创建链接文件分为两种情况,情况一:当你要创建的链接文件指向的源文件并不存在时,使用此参数,可以先强制创建出链接文件。情况二:当你要创建链接文件的目录中已经存在与链接文件同名的文件时,将force设置为yes,回将同名文件覆盖为链接文件,相当于删除同名文件,创建链接文件。情况三:当你要创建链接文件的目录中已经存在与链接文件同名的文件,并且链接文件指向的源文件也不存在,这时会强制替换同名文件为链接文件。

owner参数 :用于指定被操作文件的属主,属主对应的用户必须在远程主机中存在,否则会报错。

group参数 :用于指定被操作文件的属组,属组对应的组必须在远程主机中存在,否则会报错。

mode参数:用于指定被操作文件的权限,比如,如果想要将文件权限设置为"rw-r-x---",则可以使用mode=650进行设置,或者使用mode=0650,效果也是相同的,如果你想要设置特殊权限,比如为二进制文件设置suid,则可以使用mode=4700,很方便吧。

recurse参数:当要操作的文件为目录,将recurse设置为yes,可以递归的修改目录中文件的属性。

官网
https://docs.ansible.com/ansible/latest/modules/file_module.html#file-module

远程创建文件
ansible每次命令的执行,都会记录下当前的状态

[root@master-61 ~]#ansible backup -m file -a 'path=/opt/yuchao666.log state=touch'

创建文件夹

[root@master-61 ~]#ansible backup -m file -a 'path=/opt/yuchao666 state=directory'

创建文件且设定权限

[root@master-61 ~]#ansible backup -m file -a 'path=/opt/chaoge.pwd state=touch owner=www group=www mode=700'

创建软连接文件
软连接,也就是在目标机器上,指定源文件,创建软连接

[root@master-61 ~]#ansible backup -m file -a "src=/etc/hosts dest=/tmp/hosts_link state=link"

修改已存在文件/文件夹的属性

修改文件
[root@master-61 ~]#ansible backup -m file -a "path=/opt/chaoge.pwd mode=660"

修改文件夹
[root@master-61 ~]#ansible backup -m file -a "path=/opt/yuchao666  mode=660 owner=www group=www"

6 script脚本模块

官网

https://docs.ansible.com/ansible/latest/collections/ansible/builtin/script_module.html#ansible-collections-ansible-builtin-script-module

模块功能:把本地脚本传输到远程节点上并运行脚本

比起shell模块,script模块功能更强大,本地有一份脚本,就可以在所有机器上运行。

1.管理机创建测试脚本

cat > echo_server_info.sh <<EOF
#!/bin/bash
echo "$(hostname -I)" >> /tmp/server_info.log
echo "$(uptime)" >> /tmp/server_info.log
echo "$(free -m)" >> /tmp/server_info.log
EOF

2.添加执行权限
[root@master-61 ~]#chmod +x echo_server_info.sh 


3.远程执行
[root@master-61 ~]#ansible backup -m script -a "/root/echo_server_info.sh"

4.检查结果
[root@master-61 ~]#ansible backup -m shell -a 'cat /tmp/server_info.log'

远程一键部署rsync服务
可以先恢复rsync-41机器,再执行如下操作

1.编写rsync部署脚本  install_rsync.sh
#!/bin/bash
yum install rsync -y

cat > /etc/rsyncd.conf << 'EOF'
uid = www 
gid = www 
port = 873
fake super = yes
use chroot = no
max connections = 200
timeout = 600
ignore errors
read only = false
list = false
auth users = rsync_backup
secrets file = /etc/rsync.passwd
log file = /var/log/rsyncd.log
[backup]
comment = chaoge rsync backup!
path = /backup
EOF

useradd -u 1000 -M -s /sbin/nologin www
mkdir -p /{backup,data}
chown -R www:www /{backup,data}
echo "rsync_backup:yuchao666" > /etc/rsync.passwd
chmod 600 /etc/rsync.passwd
systemctl start rsyncd



2.远程执行脚本
[root@master-61 ~]#
[root@master-61 ~]#chmod +x install_rsync.sh 

[root@master-61 ~]#ansible backup -m script -a "/root/install_rsync.sh"


3.检查rsync服务
[root@master-61 ~]#ansible backup -m shell -a 'systemctl status rsyncd'


4.测试rsync服务
[root@master-61 ~]#export RSYNC_PASSWORD=yuchao666
[root@master-61 ~]#rsync -avzp /tmp/ [email protected]::backup
远程检查数据
[root@master-61 ~]#ansible backup -m shell -a 'ls /backup'



5.但是该方式依然是不合理的,shell不会帮你去检测文件是否重复性修改,软件是否重复性安装,因此我们会将一键部署rsync这样的任务,全部改造为ansible的模块脚本。

你现在多次执行该脚本的话,ansible已经尽力在检查哪些步骤是无须在做的了
[root@master-61 ~]#ansible backup -m script -a "/root/install_rsync.sh"

查看命令执行详细过程

[root@master-61 ~]#ansible backup  -vvvvv -m script -a "/root/install_rsync.sh"


[root@master-61 ~]#man ansible
       -v, --verbose
          verbose mode (-vvv for more, -vvvv to enable connection debugging)

7cron定时任务模块

官网文档
https://docs.ansible.com/ansible/latest/modules/cron_module.html#cron-module

cron模块用于管理定时任务的记录,编写任务

对比ansible的cron模块,和crontab

添加ntpdate定时任务
添加每5分钟执行一次和阿里云时间同步

[root@master-61 ~]#ansible backup -m cron -a "name=chaoge_cron job='/usr/sbin/ntpdate ntp.aliyun.com > /dev/null 2>&1' minute=*/5"


查看远程机器的crontab记录
[root@master-61 ~]#ansible backup -m shell -a "cat /var/spool/cron/root"
172.16.1.41 | CHANGED | rc=0 >>
* * * * * /usr/sbin/ntpdate time1.aliyun.com > /dev/null 2>&1
#Ansible: chaoge_cron
*/5 * * * * /usr/sbin/ntpdate ntp.aliyun.com > /dev/null 2>&1

删除定时任务
只能基于cron模块指定名字的修改

[root@master-61 ~]#ansible backup -m cron -a "name=chaoge_cron state=absent"
172.16.1.41 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "envs": [], 
    "jobs": []
}


[root@master-61 ~]#
[root@master-61 ~]#ansible backup -m shell -a "cat /var/spool/cron/root"
172.16.1.41 | CHANGED | rc=0 >>
* * * * * /usr/sbin/ntpdate time1.aliyun.com > /dev/null 2>&1


[root@master-61 ~]#ansible backup  -a 'crontab -l'
172.16.1.41 | CHANGED | rc=0 >>
* * * * * /usr/sbin/ntpdate time1.aliyun.com > /dev/null 2>&1

创建每分钟执行的任务
不指定任何时间规则,默认是每分钟

1.每分钟定时执行脚本,注意要求该脚本存在于目标机器上
[root@master-61 ~]#cat echo_hostname.sh 
#!/bin/bash
echo "$(date +%T) $(hostname)" >> /tmp/hostname.log


2.远程拷贝脚本
[root@master-61 ~]#ansible backup -m copy -a "src=/root/echo_hostname.sh dest=/opt/echo_hostname.sh"


3.设置定时任务,多次执行该命令,会覆盖同name的任务
[root@master-61 ~]#ansible backup -m cron -a "job='/bin/bash /opt/echo_hostname.sh' name=chaoge_cron_hostname"

修改指定名称的定时任务

[root@master-61 ~]#ansible backup -a "crontab -l"

[root@master-61 ~]#ansible backup -a "cat /tmp/hostname.log"

修改定时任务为每天晚上11点15分执行
[root@master-61 ~]#ansible backup -m cron -a "name='chaoge_cron_hostname' job='bin/bash /opt/echo_hostname.sh' minute=15 hour=23"

[root@master-61 ~]#ansible backup -a "crontab -l"

8 group模块

https://docs.ansible.com/ansible/latest/modules/group_module.html#group-
官网文档

语法

模块参数    参数描述
name    创建指定的组名
gid        组的GID
state        absent,移除远程主机的组
             present,创建远端主机的组

创建chaoge_ops组,gid=1234

[root@master-61 ~]#ansible backup -m group -a "name=chaoge_ops gid=1234"

[root@master-61 ~]#ansible backup -a "grep chaoge_ops /etc/group"
172.16.1.41 | CHANGED | rc=0 >>
chaoge_ops:x:1234:

删除组

[root@master-61 ~]#ansible backup -m group -a "name=chaoge_ops gid=1234 state=absent"

[root@master-61 ~]#ansible backup -a "grep chaoge_ops /etc/group"

9 user用户模块

用户管理,也就是关于用户的

uid
用户名
用户主组
用户附加组
创建用户
删除用户
创建关于用户的公私钥
用户过期时间
用户密码过期时间

https://docs.ansible.com/ansible/latest/modules/user_module.html#user-module
官网文档

语法参数

实例用法
https://docs.ansible.com/ansible/latest/collections/ansible/builtin/user_module.html#examples


创建chaoge01用户,uid为8888

[root@master-61 ~]#ansible backup -m user -a "name=chaoge01 uid=8888"

[root@master-61 ~]#ansible backup -a "grep chaoge01 /etc/passwd"
172.16.1.41 | CHANGED | rc=0 >>
chaoge01:x:8888:8888::/home/chaoge01:/bin/bash

创建用户cc01
uid、gid为1777
没有家目录、不允许登录

注意该用户组是否存在,否则报错
[root@master-61 ~]#ansible backup -m group -a "name=cc01 gid=1777"

创建用户,设置权限
[root@master-61 ~]#ansible backup -m user -a "name=cc01 uid=1777 group=1777 create_home=no shell=/sbin/nologin"


检查用户
[root@master-61 ~]#ansible backup -a 'grep cc01 /etc/passwd'
172.16.1.41 | CHANGED | rc=0 >>
cc01:x:1777:1777::/home/cc01:/sbin/nologin

10 yum安装软件



官网文档示例用法

https://docs.ansible.com/ansible/latest/collections/ansible/builtin/yum_module.html#examples

安装net-tools最新版本 latest参数也用于升级软件包

[root@master-61 ~]#ansible backup -m yum -a "name=net-tools state=latest"

卸载net-tools软件

[root@master-61 ~]#ansible backup -m yum -a "name=net-tools state=absent"

安装rsync服务

[root@master-61 ~]#ansible backup -m yum -a "name=rsync state=installed"


检查rsync
[root@master-61 ~]#ansible backup -m shell -a "rpm -qa rsync"

11 service/systemd模块

该模块作用是针对yum包管理

service适用于centos6前的系统

systemd命令应用于centos7系统

要注意的是service模块依旧对centos7有效,但是建议大家使用systemd模块

systemd模块参数

如果使用systemctl 管理程序的话,可以使用systemd模块,systemctl 可以 控制程序启/停,reload,开机启动,观察程序状态(status)等,掌握使用后管理就更方便了

主要参数
daemon_reload:在执行任何其他操作之前运行守护进程重新加载,以确保systemd已经读取其他更改
enabled:服务是否开机自动启动yes|no。enabled和state至少要有一个被定义
masked:是否将服务设置为masked状态,被mask的服务是无法启动的
name:必选项,服务名称
no_block(2.3后新增):不要同步等待操作请求完成
state:对当前服务执行启动,停止、重启、重新加载等操作(started,stopped,restarted,reloaded)
user:使用服务的调用者运行systemctl,而不是系统的服务管理者

安装、启动nginx服务

1.安装nginx服务
[root@master-61 ~]#ansible 172.16.1.7 -m yum -a "name=nginx state=installed"

2.启动服务
[root@master-61 ~]#ansible web -m systemd -a "name=nginx state=started"

3.查询状态,这里ansible未直接提供status参数,你可以借助command模块即可
[root@master-61 ~]#ansible web -a "systemctl status nginx"

4.停止nginx服务
[root@master-61 ~]#ansible web -m systemd -a "name=nginx state=stopped"

5.设置nginx开机自启
[root@master-61 ~]#ansible web -m systemd -a "name=nginx state=started enabled=yes"

6.检查nginx状态
[root@master-61 ~]#ansible web -a "systemctl is-enabled nginx"

[root@master-61 ~]#ansible web -a "systemctl status nginx"

7.关闭开机自启、且停止服务
[root@master-61 ~]#ansible web -m systemd -a "name=nginx state=stopped  enabled=no"

8.再次检查状态
[root@master-61 ~]#ansible web  -m shell -a "systemctl is-enabled nginx;systemctl status nginx"

12 mount挂载模块

官网
https://docs.ansible.com/ansible/latest/collections/ansible/posix/mount_module.html#mount-

给web-7机器挂载nfs目录(只写入/etc/fstab而不挂载)

[root@master-61 ~]#ansible web -m mount -a "src='172.16.1.1:/nfs-nginx-data' path=/usr/share/nginx/html fstype=nfs state=present"

给web-7机器挂载nfs目录(立即挂载且写入/etc/fstab)

[root@master-61 ~]#ansible web -m mount -a "src='172.16.1.31:/nfs-nginx-data' path=/usr/share/nginx/html fstype=nfs state=mounted"

检查
[root@master-61 ~]#ansible web -a "df -h"

[root@master-61 ~]#ansible web -a "cat /etc/fstab"

取消挂载,以及删除fstab记录

[root@master-61 ~]#ansible web -m mount -a "src='172.16.1.31:/nfs-nginx-data' path=/usr/share/nginx/html fstype=nfs state=absent"

验证
[root@master-61 ~]#ansible web -a "df -h"
[root@master-61 ~]#ansible web -a "cat /etc/fstab"

取消挂载,不删除fstab记录

[root@master-61 ~]#ansible web -m mount -a "src='172.16.1.31:/nfs-nginx-data' path=/usr/share/nginx/html fstype=nfs state=umounted"

总结参数

mounted 挂载设备且写入fstab
present 仅写入fstab 不挂载
absent  卸载且删除fstab记录
umounted 只卸载不删除fstab记录

13 archive压缩模块

官网文档
https://docs.ansible.com/ansible/latest/collections/community/general/archive_module.html

支持压缩类型

bz2

gz ← (default)

tar

xz

zip 

用法文档
https://docs.ansible.com/ansible/latest/collections/community/general/archive_module.html#examples
指定format即可

压缩/etc配置文件到指定路径

[root@master-61 ~]#ansible web -m archive -a "path=/etc dest=/opt/etc.tgz"
[root@master-61 ~]#ansible web -a "ls /opt -l"
[root@master-61 ~]#ansible web -a "file /opt/etc.tgz"

压缩/var/log为zip类型到指定路径

[root@master-61 ~]#ansible web -m archive -a "path=/var/log dest=/opt/log.zip format=zip"

[root@master-61 ~]#ansible web -a "file /opt/log.zip"

14 unarchive解压缩模块

https://docs.ansible.com/ansible/latest/collections/ansible/builtin/unarchive_module.html#examples

解压缩etc.tgz到指定目录(远程解压)
remote_src远程数据源

指定目录必须存在
[root@master-61 ~]#ansible web -m file -a "path=/opt/etc_file state=directory"


解压缩
[root@master-61 ~]#ansible web -m unarchive -a "src=/opt/etc.tgz dest=/opt/etc_file/ remote_src=yes"

查看
[root@master-61 ~]#ansible web -a "ls /opt/etc_file/etc/"

将管理机的压缩包,解压到远程机器上
将master-61的压缩文件,解压到web-7机器上

1.生成etc.tgz数据
[root@master-61 ~]#cd / && tar -zcf /opt/etc.tgz etc


2.远程解压到web-7机器上
[root@master-61 /]#ansible web -m unarchive -a "src=/opt/etc.tgz  dest=/tmp/"

3.检查
[root@master-61 /]#ansible web -a "ls /tmp/etc/"

标签:--,backup,ansible,61,Ansible,master,模块,root
From: https://www.cnblogs.com/btcm409181423/p/18059458

相关文章

  • python的ansible库--ansible_runner
    介绍AnsibleRunner是ansible官方提供的一个工具和python库,当直接与Ansible进行交互或作为另一个系统的一部分与Ansible进行交互时,无论是通过容器映像接口,作为独立工具还是作为可以导入的Python模块,它都可以提供帮助。目的是为Ansible提供稳定且一致的接口抽象。参考网站[官方......
  • FMS设备监察系统无线传输模块及网关快速应用教程
    设备监察系统又叫做FMS(Facilities  Monitoring  System),该FMS系统由 GUI(配置上位机)、FMS网关和lora无线模块节点三部分组成。亿佰特上市的E53-470FMS22S、E53-DTU(470FMS22)产品是基于LoRa扩频技术开发的设备监察系统无线传输模块及网关,其强大的抗干扰能力,让无线通信在工业现......
  • Linux架构24 ansible之get_url模块, 服务管理模块, 用户管理模块, 定时任务模块, 挂载
    3.get_url模块-name:Downloadfoo.confget_url:url:http://example.com/path/file.confdest:/etc/foo.confmode:'0440'checksum:md5:b5bb9...#公司内部库,验证文件是否为要求的文件checksum:sha256:b5bb9...#另一种验证方式......
  • MATLAB----遗传算法及Simulink延时模块实例
    clctic%%参数初始化maxgen=100;%进化代数,即迭代次数,初始预定值选为100sizepop=200;%种群规模,初始预定值选为100pcross=0.9;%交叉概率选择,0和1之间,一般取0.9pmutation=0.01;%变异概率选择,0和1之间,一般取0.01individuals=struct('fitness',zeros(1,sizepop),'chrom',[]);%种群......
  • vue3 报错解决:找不到模块或其相应的类型声明。(Vue 3 can not find module)
    当我们在引入应该组件的时候提示找不到这个组件但是项目明明就有这个物理文件报错原因:typescript只能理解.ts文件,无法理解.vue文件 这个时候我们应该这样首先原因:1、volar插件没开takeover模式去看volar插件介绍,开takeover模式2、volar未选择tyscript最新版本解决:1、......
  • 全新QSiC 1200V 模块:GCMS020A120S1-E1、GCMS040A120S1-E1、GCMX020B120S1-E1、GCMS020
    全新QSiC1200VSOT-227SiC模块,提升能源标准,这些超高效模块支持电动汽车、医疗电源和太阳能大功率应用的创新设计。特点低开关损耗低结至外壳热阻非常坚固,易于安装直接安装到散热器上(隔离封装)超低损耗的高频操作SiCSBDs的零反向恢复电流SiCMOSFETs的小关断尾电流低杂散电感......
  • Hi1102A和Hi1105模块在远距离无线图传领域的选型浅析
    Hi1102A和Hi1105V500都是属于海思旗下的两款WIFI+BT+GNSS+FM四功能一体(江湖俗称四合一)高性能方案,应该可以推出,这个原本是在手机方案集成使用的,本身海思有视频安防主控HI315X系列平台,如果搭配上自己的无线phy芯片,一体化集成的性能应该就完美,于是有了远距离无线图传模块化集成的......
  • tarfile压缩模块
    tarfile压缩模块创建文件importtarfile""" 此过程只是创建压缩包并不打包数据"""#创建压缩包fp=tarfile.open("ceshi.tar","w",encoding="utf-8")#写入文件"""add(路径,别名)"""fp.add("2",&......
  • 六.模块导入和输出格式化
    1.模块导入2.输出格式美化 1.模块导入>>>导入:import文件名调用:文件名.方法名(参数)>>>导入:from文件名import方法名调用:方法名(参数)>>>导入文件内所有方法:from文件名import*  >>>导入:import多层包名.文件名调用:多层包名.文件名.方法名(参数)多层包......
  • OS的Path模块
    OS的Path模块basename#返回文件名部分pathvar="/home/wangwen/mywork/ceshi.py"pathvar=__file__res=os.path.basename(pathvar)print(res)#outceshi.pydirname#返回路径部分pathvar="/home/wangwen/mywork/ceshi.py"pathvar=__file__res......