作用:ansible是一款强大的配置管理工具,可以对成百上千台服务器进行管理,ansible可以理解为一个管理员,基于SSH协议对多台服务器进行指令下
发实现多台服务器的批量操作,一次下发一条命令(ansible ad-hoc模式)的方式来控制服务器,也可以将多条命令写在纸上(ansible playbook模式)让服
务器按照你写好指令工作,也可以通过管理配置实现多台服务器同一时间做不通的事情。上述这些操作都可以基于ansible来实现,前提是ansible可以通
过SSH协议远程服务器
安装:
Centos或者redhat可以通过yum安装
yum -y install ansible
配置:正常情况下默认配置即可满足
规划:
配置文件详解:/etc/ansible/ansible.cfg
inventory=/etc/ansible/hosts 表示主机清单inventory文件的位置
forks=5 并发连接数默认为5
sudo_user=root 默认执行命令的用户
remote_port=22 指定连接被管理节点的管理端口,默认是22端口,建议修改成其它的端口,能够更安全
host_key_checking = False 设置是否检查SSH主机的秘钥,值为True/False。关闭后第一次连接不会提示配置实例
timeout=60 设置SSH连接的超时时间,单位为秒
log_path = /var/log/ansible.log 指定一个存储ansible的文件
配置文件参考:
[defaults] #通用默认配置 inventory = /etc/ansible/hosts #被控制端IP或者DNS列表 library = /usr/share/my_modules/ ##默认搜寻模块的位置 remote_tmp = ~/.ansible/tmp #远程执行临时文件 local_tmp = ~/.ansible/tmp plugin_filters_cfg = /etc/ansible/plugin_filters.yml forks = 5 ##并行线程数 poll_interval = 15 ##回频率或轮询间隔时间 sudo_user = root ##sudo远程执行用户名 ask_sudo_pass = True ##使用sudo,是否需要输入密码 ask_pass = True ##是否需要输入密码 transport = smart ##通信机制 remote_port = 22 ##远程SSH端口 module_lang = C ##模块和系统之间通信的语言 module_set_locale = False gathering = implicit ##控制默认facts收集(远程系统变量) gather_subset = all gather_timeout = 10 roles_path = /etc/ansible/roles ##使用playbook搜索Ansible roles host_key_checking = False ##是否检查远程主机密钥 sudo_exe = sudo ##sudo远程执行命令 sudo_flags = -H -S -n ##传递sudo之外的参数 timeout = 10 ##SSH超时时间 remote_user = root ##远程登录用户名 log_path = /var/log/ansible.log ##日志文件存放路径 module_name = command ##Ansible命令默认执行的模块 executable = /bin/sh ##执行的shell环境,用户shell模块 hash_behaviour = replace ##特定的优先级覆盖变量 jinja2_extensions = jinja2.ext.do,jinja2.ext.i18 ##允许开启jinja2扩展模块 private_key_file = /path/to/file ##私钥文件存储位置 display_skipped_hosts = True ##显示跳过任何任务的状态 system_warnings = True ##禁用系统运行Ansible潜在问题警告 deprecation_warnings = True ##PlayBook输出禁用“不建议使用”警告 command_warnings = False ##command模块Ansible默认发出警告 nocolor = 1 ##输出带上颜色区别,0表示开启,1表示关闭 pipelining = False ##开启pipe SSH通道优化 [accelerate] ##accelerate缓存加速 accelerate_port = 5099 ##加速连接端口5099 accelerate_timeout = 30 ##命令执行超过时间,单位为s accelerate_connect_timeout = 5.0 ##上一个活动连接的时间,单位为min accelerate_daemon_timeout = 30 ##允许多个私钥被加载到daemon accelerate_multi_key = yes ##任何客户端想要连接daemon都要开启这个选项 ———————————————— 版权声明:本文为CSDN博主「皛皛」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。 原文链接:https://blog.csdn.net/lcl_xiaowugui/article/details/81908445
inventory文件编辑:
ansible_connection 与主机的连接类型,比如local,ssh或者paramiko ansible1.2以前默认使用
ansible_ssh_host 如果要远程的主机名与你设置的主机的别名不通,就可以通过该变量设置
ansible_ssh_port 如果不是默认是22端口,可以通过该变量设置
ansible_ssh_user 默认的ssh用户名
ansible_ssh_pass 远程主机的远程密码,该方式不安全,建议使用--ask-sudo-pass或者ssh密钥的方式连接
ansible_sudo_pass 输入sudo所需的密码,即被连接主机的普通账号密码,建议使用--ask-sudo-pass(手动输入密码验证的方式,相对安全)
ansible_sudo_exe sudo命令路径,适用于1.8及以上版本
ansible_ssh_private_key_file ssh使用的私钥文件,适用于有多个密钥
ansible_python_interpreter 目标主机python的路径,主要用于多python版本来指定用哪个python版本
举例说明
[test] 172.16.204.134 ansible_connection=ssh ansible_ssh_user=root ansible_ssh_port=2222 ansible_ssh_pass="mimashi123"
ansible ad-hoc模式(使用ansible命令来控制inventory中的主机列表)
查看ansible命令参数 ansible -h
[root@localhost ~]# ansible -h Usage: ansible <host-pattern> [options] Options: -a MODULE_ARGS, --args=MODULE_ARGS #模块的参数,如果执行默认COMMAND的模块,即是命令参数,如:“date”,"pwd"等等 module arguments # 模块参数 -k, --ask-pass ask for SSH password #登录密码,提示输入SSH密码而不是假设基于密钥的验证 --ask-su-pass ask for su password #su切换密码 -K, --ask-sudo-pass ask for sudo password # 提示密码使用sudo,sudo表示提权操作 --ask-vault-pass ask for vault password -B SECONDS, --background=SECONDS # 后台运行超时时间 run asynchronously, failing after X seconds (default=N/A) -C, --check don't make any changes; instead, try to predict some #只是测试一下会改变什么内容,不会真正去执行;相反,试图预测一些可能发生的变化 of the changes that may occur -c CONNECTION, --connection=CONNECTION #连接类型使用。可能的选项是paramiko(SSH),SSH和地方。当地主要是用于crontab或启动。 connection type to use (default=smart) -f FORKS, --forks=FORKS #并行任务数。NUM被指定为一个整数,默认是5 specify number of parallel processes to use (default=5) -h, --help show this help message and exit # 打开帮助文档API -i INVENTORY, --inventory-file=INVENTORY #指定库存主机文件的路径,默认为/etc/ansible/hosts specify inventory host file (default=/etc/ansible/hosts) -l SUBSET, --limit=SUBSET #进一步限制所选主机/组模式 --limit=192.168.91.135 只对这个ip执行 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 # 执行模块的名字,默认使用 command 模块,所以如果是只执行单一命令可以不用 -m参数 module name to execute (default=command) -M MODULE_PATH, --module-path=MODULE_PATH #要执行的模块的路径,默认为/usr/share/ansible/ specify path(s) to module library (default=/usr/share/ansible/) -o, --one-line condense output # 压缩输出,摘要输出.尝试一切都在一行上输出。 -P POLL_INTERVAL, --poll=POLL_INTERVAL #调查背景工作每隔数秒。需要- b set the poll interval if using -B (default=15) --private-key=PRIVATE_KEY_FILE # 私钥路径,使用这个文件来验证连接 use this file to authenticate the connection -S, --su run operations with su #用 su 命令 -R SU_USER, --su-user=SU_USER # 指定SU的用户,默认是root用户 run operations with su as this user (default=root) -s, --sudo run operations with sudo (nopasswd) -U SUDO_USER, --sudo-user=SUDO_USER #sudo到哪个用户,默认为 root desired sudo user (default=root) -T TIMEOUT, --timeout=TIMEOUT #指定SSH默认超时时间, 默认是10S override the SSH timeout in seconds (default=10) -t TREE, --tree=TREE log output to this directory #将日志内容保存在该输出目录,结果保存在一个文件中在每台主机上。 -u REMOTE_USER, --user=REMOTE_USER #远程用户, 默认是root用户 connect as this user (default=root) --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 # 输出ansible的版本
使用ansible命令^_^:
1.列出配置过的主机列表(可以看到hosts中的node节点配置成功)
root@manager1 ansible]# ansible all --list hosts (1): 172.16.204.134
2.使用--ask-pass(使用ansible_ssh_pass等类似变量是非常危险的,容易导致密码泄露,使用--ask-pass则可以避免密码泄露)
root@manager1 ansible]# ansible all -m ping --ask-pass #ansible all -m ping 测试所有主机的连通性 SSH password: 172.16.204.134 | SUCCESS => { "changed": false, "ping": "pong" }
3.配置密钥方式控制所有主机
- ansible本机生成公钥:执行一条 ssh-keygen -t rsa命令即可
[root@manager1 .ssh]# ssh-keygen -t rsa Generating public/private rsa key pair. Enter file in which to save the key (/root/.ssh/id_rsa): Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in /root/.ssh/id_rsa. Your public key has been saved in /root/.ssh/id_rsa.pub. The key fingerprint is: SHA256:ZHO/Ttd8KD6r+pehmUmXCUxgn1qto0n7oaOQ0e2pKCA root@manager1 The key's randomart image is: +---[RSA 2048]----+ | o. | | . ..o | | +o= . | | . + =oo | | . . S o..o | |E o o =..=. + | |.. o *..*+oo +| | . o ..o==+o .| | .. o.o++o+o | +----[SHA256]-----+ [root@manager1 .ssh]# pwd /root/.ssh [root@manager1 .ssh]# ll total 12 -rw------- 1 root root 1675 Jan 9 22:57 id_rsa -rw-r--r-- 1 root root 395 Jan 9 22:57 id_rsa.pub -rw-r--r-- 1 root root 358 Jan 9 20:49 known_hosts
- ansible给所有主机授权密钥认证(将公钥文件发送到远程主机,实现免密钥SSH认证)
#下面命令是授权root的id.rsa.pub和user需要对应,稍微注意下
[root@manager1 .ssh]# ansible all -m authorized_key -a "user=root key='{{ lookup('file','/root/.ssh/id.rsa.pub') }}' path=/root/.ssh/authorized_keys manage_dir=yes" --ask-pass
#172.16.204.139不存在,所以授权失败
172.16.204.139 | UNREACHABLE! => {
"changed": false,
"msg": "Failed to connect to the host via ssh: ssh: connect to host 172.16.204.139 port 22: No route to host
",
"unreachable": true
}
172.16.204.134 | SUCCESS => {
"changed": false,
"comment": null,
"exclusive": false,
"gid": 0,
"group": "root",
"key": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDlPWGRzZk6MRro7977zRgtmvbc+osYossPL9vFpuynOrkYBprXM/bXQFkSMtoD/BAxAdEAXhgya4zaq0qLjSxYqFNGHUR2sGsNwIbBtXxnIGyravH6U9hyVgZCb3GTcKgYNxqXv+DGZGfqzQX4PRZjV3nmcLLbv19qopQdwbSspzxNbpbu/Lx8Ce0C8nLTDYFB6N6ygPWOoUvWS3PZJlJaP9n0h6GSDnDEz3gGjHeeSQn3NmE5iVH2oEjffgcwBgxl+zRikv0698q2FLr9O8VJCSh9pqSX0oPg2K1Enlu8JeM/TazHcAJUDNuKgZaZglnxWKy8NZ2m0/Bm68TTcX/d root@manager1",
"key_options": null,
"keyfile": "/root/.ssh/authorized_keys",
"manage_dir": true,
"mode": "0600",
"owner": "root",
"path": "/root/.ssh/authorized_keys",
"secontext": "system_u:object_r:ssh_home_t:s0",
"size": 395,
"state": "file",
"uid": 0,
"unique": false,
"user": "root",
"validate_certs": true
}
- 使用ansible内置的SSH密钥管理模块authorized_key来执行批量SSH授信的任务
[root@manager1 .ssh]# vim /etc/ansible/hosts #组名 ansible_ssh_private_key_file指定私钥文件
[test] 172.16.204.134 ansible_connection=ssh ansible_ssh_user=root ansible_ssh_private_key_file=/root/.ssh/id_rsa
4.获取已授信主机的当前时间
[root@manager1 .ssh]# ansible all -a "date +'%F %H:%M:%S'" 172.16.204.134 | SUCCESS | rc=0 >> 2020-01-10 00:58:58
5.批量上传文件(copy模块): ansible all -m copy -a "src=/opt/aaa.txt dest=/root" 主要使用了copy模块
#查看远程主机/root目录下的文件 root@manager1 .ssh]# ansible all -m shell -a "ls -l /root/" 172.16.204.134 | SUCCESS | rc=0 >> total 4 -rw-------. 1 root root 1264 Oct 16 12:56 anaconda-ks.cfg [root@manager1 opt]# ansible all -m copy -a "src=/opt/aaa.txt dest=/root" 172.16.204.134 | SUCCESS => { "changed": true, "checksum": "da39a3ee5e6b4b0d3255bfef95601890afd80709", "dest": "/root/aaa.txt", "gid": 0, "group": "root", "md5sum": "d41d8cd98f00b204e9800998ecf8427e", "mode": "0644", "owner": "root", "secontext": "system_u:object_r:admin_home_t:s0", "size": 0, "src": "/root/.ansible/tmp/ansible-tmp-1578644172.98-65497852724657/source", "state": "file", "uid": 0 } [root@manager1 opt]# ansible all -m shell -a "ls -l /root/" 172.16.204.134 | SUCCESS | rc=0 >> total 4 -rw-r--r--. 1 root root 0 Jan 10 03:16 aaa.txt -rw-------. 1 root root 1264 Oct 16 12:56 anaconda-ks.cfg
6.systemd或者service模块:批量启动服务
centos7启动服务使用的systemd centos7之前的版本使用的server来控制服务
主要参数:
- name: 服务名,例如
crond.service
,最好带上后缀.service - state: 需要的操作,reloaded, restarted, started, stopped
- enabled:是否需要开机启动
- daemon_reload:systemd 读取配置文件,每次修改了文件,最好都运行一次,确保应用了
#Centos7
[root@manager1 ansible_tower]# ansible test -m systemd -a 'name=docker state=started'
#Centos6
[root@manager1 ansible_tower]# ansible test -m service -a 'name=docker state=started'
7.script模块:在被管理端执行管理端的脚本,无须将脚本传到被管理服务器上
主要参数:
- chdir # 在远程执行脚本前先切换到此目录下。
- creates # 当此文件存在时,不执行脚本。可用于实现幂等性。
- removes # 当此文件不存在时,不执行脚本。可用于实现幂等性。
- free_form= # 本地待执行的脚本路径、选项、参数。之所以称为free_form,是因为它是脚本名+选项+参数(可以理解为需要执行的脚本)
#!/bin/bash ls -l ./ [root@manager1 ansible_tower]# ansible test -m script -a 'chdir=/opt/ ls.sh' 172.16.204.134 | SUCCESS => { "changed": true, "rc": 0, "stderr": "Shared connection to 172.16.204.134 closed. ", "stdout": "total 288328 -rw-r--r--. 1 root root 293849789 Jan 15 21:23 ansible-tower-setup-bundle-latest.el7.tar.gz drwxr-xr-x. 2 root root 21 Jan 15 21:24 docker_harbor -rw-r--r--. 1 root root 1392184 Jan 12 22:25 harbor-offline-installer-v1.9.4.tgz -rw-r--r--. 1 root root 5 Jan 15 20:39 test.sh ", "stdout_lines": [ "total 288328", "-rw-r--r--. 1 root root 293849789 Jan 15 21:23 ansible-tower-setup-bundle-latest.el7.tar.gz", "drwxr-xr-x. 2 root root 21 Jan 15 21:24 docker_harbor", "-rw-r--r--. 1 root root 1392184 Jan 12 22:25 harbor-offline-installer-v1.9.4.tgz", "-rw-r--r--. 1 root root 5 Jan 15 20:39 test.sh" ] }
8.yum模块:使用yum在被管理端通过yum安装工具
- name:要进行操作的软件包的名字,也可以传递一个url或者一个本地的rpm包的路径
- state:状态仅有卸载选择,三个选项都是卸载(present,absent,latest)
[root@manager1 ansible_tower]# ansible test -m yum -a 'name=vsftpd' 172.16.204.134 | SUCCESS => { "changed": true, "msg": "", "rc": 0, "results": [ "Loaded plugins: fastestmirror Loading mirror speeds from cached hostfile * base: mirrors.huaweicloud.com * extras: mirrors.huaweicloud.com * updates: mirrors.huaweicloud.com Resolving Dependencies --> Running transaction check ---> Package vsftpd.x86_64 0:3.0.2-25.el7 will be installed --> Finished Dependency Resolution Dependencies Resolved ================================================================================ Package Arch Version Repository Size ================================================================================ Installing: vsftpd x86_64 3.0.2-25.el7 base 171 k Transaction Summary ================================================================================ Install 1 Package Total download size: 171 k Installed size: 353 k Downloading packages: Running transaction check Running transaction test Transaction test succeeded Running transaction Installing : vsftpd-3.0.2-25.el7.x86_64 1/1 Verifying : vsftpd-3.0.2-25.el7.x86_64 1/1 Installed: vsftpd.x86_64 0:3.0.2-25.el7 Complete! " ] } [root@manager1 ansible_tower]# ansible test -m systemd -a 'name=vsftpd state=started' 172.16.204.134 | SUCCESS => { "changed": true, "name": "vsftpd", "state": "started", "status": { "ActiveEnterTimestampMonotonic": "0", "ActiveExitTimestampMonotonic": "0", "ActiveState": "inactive", "After": "systemd-journald.socket system.slice network.target basic.target", "AllowIsolate": "no", "AmbientCapabilities": "0", "AssertResult": "no", "AssertTimestampMonotonic": "0", "Before": "shutdown.target", "BlockIOAccounting": "no", "BlockIOWeight": "18446744073709551615", "CPUAccounting": "no", "CPUQuotaPerSecUSec": "infinity", "CPUSchedulingPolicy": "0", "CPUSchedulingPriority": "0", "CPUSchedulingResetOnFork": "no", "CPUShares": "18446744073709551615", "CanIsolate": "no", "CanReload": "no", "CanStart": "yes", "CanStop": "yes", "CapabilityBoundingSet": "18446744073709551615", "ConditionResult": "no", "ConditionTimestampMonotonic": "0", "Conflicts": "shutdown.target", "ControlPID": "0", "DefaultDependencies": "yes", "Delegate": "no", "Description": "Vsftpd ftp daemon", "DevicePolicy": "auto", "ExecMainCode": "0", "ExecMainExitTimestampMonotonic": "0", "ExecMainPID": "0", "ExecMainStartTimestampMonotonic": "0", "ExecMainStatus": "0", "ExecStart": "{ path=/usr/sbin/vsftpd ; argv[]=/usr/sbin/vsftpd /etc/vsftpd/vsftpd.conf ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }", "FailureAction": "none", "FileDescriptorStoreMax": "0", "FragmentPath": "/usr/lib/systemd/system/vsftpd.service", "GuessMainPID": "yes", "IOScheduling": "0", "Id": "vsftpd.service", "IgnoreOnIsolate": "no", "IgnoreOnSnapshot": "no", "IgnoreSIGPIPE": "yes", "InactiveEnterTimestampMonotonic": "0", "InactiveExitTimestampMonotonic": "0", "JobTimeoutAction": "none", "JobTimeoutUSec": "0", "KillMode": "control-group", "KillSignal": "15", "LimitAS": "18446744073709551615", "LimitCORE": "18446744073709551615", "LimitCPU": "18446744073709551615", "LimitDATA": "18446744073709551615", "LimitFSIZE": "18446744073709551615", "LimitLOCKS": "18446744073709551615", "LimitMEMLOCK": "65536", "LimitMSGQUEUE": "819200", "LimitNICE": "0", "LimitNOFILE": "4096", "LimitNPROC": "3820", "LimitRSS": "18446744073709551615", "LimitRTPRIO": "0", "LimitRTTIME": "18446744073709551615", "LimitSIGPENDING": "3820", "LimitSTACK": "18446744073709551615", "LoadState": "loaded", "MainPID": "0", "MemoryAccounting": "no", "MemoryCurrent": "18446744073709551615", "MemoryLimit": "18446744073709551615", "MountFlags": "0", "Names": "vsftpd.service", "NeedDaemonReload": "no", "Nice": "0", "NoNewPrivileges": "no", "NonBlocking": "no", "NotifyAccess": "none", "OOMScoreAdjust": "0", "OnFailureJobMode": "replace", "PermissionsStartOnly": "no", "PrivateDevices": "no", "PrivateNetwork": "no", "PrivateTmp": "no", "ProtectHome": "no", "ProtectSystem": "no", "RefuseManualStart": "no", "RefuseManualStop": "no", "RemainAfterExit": "no", "Requires": "system.slice basic.target", "Restart": "no", "RestartUSec": "100ms", "Result": "success", "RootDirectoryStartOnly": "no", "RuntimeDirectoryMode": "0755", "SameProcessGroup": "no", "SecureBits": "0", "SendSIGHUP": "no", "SendSIGKILL": "yes", "Slice": "system.slice", "StandardError": "inherit", "StandardInput": "null", "StandardOutput": "journal", "StartLimitAction": "none", "StartLimitBurst": "5", "StartLimitInterval": "10000000", "StartupBlockIOWeight": "18446744073709551615", "StartupCPUShares": "18446744073709551615", "StatusErrno": "0", "StopWhenUnneeded": "no", "SubState": "dead", "SyslogLevelPrefix": "yes", "SyslogPriority": "30", "SystemCallErrorNumber": "0", "TTYReset": "no", "TTYVHangup": "no", "TTYVTDisallocate": "no", "TasksAccounting": "no", "TasksCurrent": "18446744073709551615", "TasksMax": "18446744073709551615", "TimeoutStartUSec": "1min 30s", "TimeoutStopUSec": "1min 30s", "TimerSlackNSec": "50000", "Transient": "no", "Type": "forking", "UMask": "0022", "UnitFilePreset": "disabled", "UnitFileState": "disabled", "WatchdogTimestampMonotonic": "0", "WatchdogUSec": "0" } }
9.cron模块:定时任务模块
- backup:对远程主机上的原任务计划内容修改之前做备份
- cron_file:如果指定该选项,则用该文件替换远程主机上的cron.d目录下的用户的任务计划
- day:日(1-31,,/2,……)
- hour:小时(0-23,,/2,……)
- minute:分钟(0-59,,/2,……)
- month:月(1-12,,/2,……)
- weekday:周(0-7,*,……)
- job:要执行的任务,依赖于state=present
- name:该任务的描述
- special_time:指定什么时候执行,参数:reboot,yearly,annually,monthly,weekly,daily,hourl
- state:确认该任务计划是创建还是删除
- user:以哪个用户的身份执行#创建一个计划任务
root@manager1 ansible_tower]# ansible test -m cron -a "name='test' hour=0 minute=0 job='sh /opt/test.sh'" 172.16.204.134 | SUCCESS => { "changed": true, "envs": [], "jobs": [ "test" ] } #被管理端确认 [root@work1 opt]# crontab -l #Ansible: test 0 0 * * * sh /opt/test.sh
============================================
#删除已创建的任务:state=absent删除计划任务,删除的任务名为name='test'
[root@manager1 ansible_tower]# ansible test -m cron -a "name='test' state=absent"
172.16.204.134 | SUCCESS => {
"changed": true,
"envs": [],
"jobs": []
}
#被管理端确认
[root@work1 opt]# crontab -l
[root@work1 opt]#
10.file模块:文件操作模块:对文件目录的创建、删除、软硬连接、定义权限等操作
- force:需要在两种情况下强制创建软链接,一种是源文件不存在但之后会建立的情况下;另一种是目标软链接已存在,需要先取消之前的软链,然后创建新的软链,有两个选项:yes|no
- group:定义文件/目录的属组
- mode:定义文件/目录的权限
- owner:定义文件/目录的属主
- path:必选项,定义文件/目录的路径
- recurse:递归的设置文件的属性,只对目录有效
- src:要被链接的源文件的路径,只应用于state=link的情况
- dest:被链接到的路径,只应用于state=link的情况
- state: directory:如果目录不存在,创建目录
- - file:即使文件不存在,也不会被创建
- - link:创建软链接
- - hard:创建硬链接
- - touch:如果文件不存在,则会创建一个新的文件,如果文件或目录已存在,则更新其最后修改时间
- - absent:删除目录、文件或者取消链接文件
创建目录
#在管理端执行创建目录的命令 [root@manager1 ansible_tower]# ansible test -m file -a 'path=/opt/file_dir state=directory' 172.16.204.134 | SUCCESS => { "changed": true, "gid": 0, "group": "root", "mode": "0755", "owner": "root", "path": "/opt/file_dir", "secontext": "unconfined_u:object_r:usr_t:s0", "size": 6, "state": "directory", "uid": 0 } #在被管理端查看目录是否创建 [root@work1 opt]# ll /opt/ total 288328 -rw-r--r--. 1 root root 293849789 Jan 15 21:23 ansible-tower-setup-bundle-latest.el7.tar.gz drwxr-xr-x. 2 root root 21 Jan 15 21:24 docker_harbor drwxr-xr-x. 2 root root 6 Jan 16 02:14 file_dir -rw-r--r--. 1 root root 1392184 Jan 12 22:25 harbor-offline-installer-v1.9.4.tgz -rw-r--r--. 1 root root 5 Jan 15 20:39 test.sh
创建文件
#在管理端执行创建文件的指令 [root@manager1 ansible_tower]# ansible test -m file -a 'path=/opt/file.txt state=touch' 172.16.204.134 | SUCCESS => { "changed": true, "dest": "/opt/file.txt", "gid": 0, "group": "root", "mode": "0644", "owner": "root", "secontext": "unconfined_u:object_r:usr_t:s0", "size": 0, "state": "file", "uid": 0 } #在被管理端确认文件是否创建 root@work1 opt]# ll /opt/file.txt -rw-r--r--. 1 root root 0 Jan 16 02:17 /opt/file.txt
删除文件或者目录
#管理端删除文件的指令 [root@manager1 ansible_tower]# ansible test -m file -a 'path=/opt/file.txt state=absent' 172.16.204.134 | SUCCESS => { "changed": true, "path": "/opt/file.txt", "state": "absent" } #被管理端确认文件是否删除 [root@work1 opt]# ll /opt/file.txt ls: cannot access /opt/file.txt: No such file or directory [root@work1 opt]#
11.get_url模块:用于从http,https.ftp等通过url下载模块
- url:必选项,url路径
- dest:下载存放路径
- timeout:下载超时时间
[root@manager1 ansible_tower]# ansible test -m get_url -a 'url=http://nginx.org/download/nginx-1.8.1.tar.gz dest=/opt timeout=300' 172.16.204.134 | SUCCESS => { "changed": true, "checksum_dest": null, "checksum_src": "a99dc2ee4c60e3134891cd13c111f42901252c2b", "dest": "/opt/nginx-1.8.1.tar.gz", "gid": 0, "group": "root", "md5sum": "2e91695074dbdfbf1bcec0ada9fda462", "mode": "0644", "msg": "OK (833473 bytes)", "owner": "root", "secontext": "system_u:object_r:usr_t:s0", "size": 833473, "src": "/tmp/tmpQcyXAs", "state": "file", "status_code": 200, "uid": 0, "url": "http://nginx.org/download/nginx-1.8.1.tar.gz" }
unarchive模块:解压缩模块,将本地压缩包,解压到远程主机指定目录,如果已经存在则不解压缩
- dest:远程主机上的一个路径,即文件解压的路径,目录必须存在
- src: 压缩文件路径
- remote_src:远端是否已经存在,默认false
#将管理端的压缩包解压到被管理端 [root@manager1 opt]# ansible test -m unarchive -a 'src=/opt/Python-3.6.6.tgz dest=/opt' 172.16.204.134 | SUCCESS => { "changed": true, "dest": "/opt", "extract_results": { "cmd": [ "/usr/bin/gtar", "--extract", "-C", "/opt", "-z", "-f", "/root/.ansible/tmp/ansible-tmp-1579224596.69-118324470711945/source" ], "err": "", "out": "", "rc": 0 }, "gid": 0, "group": "root", "handler": "TgzArchive", "mode": "0755", "owner": "root", "secontext": "system_u:object_r:usr_t:s0", "size": 199, "src": "/root/.ansible/tmp/ansible-tmp-1579224596.69-118324470711945/source", "state": "directory", "uid": 0 } #确认是否已解压到被管理端 [root@work1 ~]# ll /opt/ total 289148 -rw-r--r--. 1 root root 293849789 Jan 15 21:23 ansible-tower-setup-bundle-latest.el7.tar.gz drwxr-xr-x. 2 root root 21 Jan 15 21:24 docker_harbor drwxr-xr-x. 2 root root 6 Jan 16 02:14 file_dir -rw-r--r--. 1 root root 1392184 Jan 12 22:25 harbor-offline-installer-v1.9.4.tgz -rw-r--r--. 1 root root 833473 Jan 16 03:04 nginx-1.8.1.tar.gz drwxr-xr-x. 17 501 501 4096 Jun 27 2018 Python-3.6.6 #已成功 -rw-r--r--. 1 root root 5 Jan 15 20:39 test.sh
wait_for模块:等待执行模块,由上个任务完成后并达到预期的值,然后进行下一步操作,通常用于检测端口是否存活,文件是否存在,或文件中的字符串
delay # 在检查操作进行之前等待的秒数
host # 等待这个主机处于启动状态,默认为127.0.0.1
port # 等待这个端口已经开放
path # 这个文件是否已经存在
search_regex # 在文件中进行正则匹配
state # present/started/stopped/absent/drained.默认started
当检查的是一个端口时:
started:保证端口是开放的
stopped:保证端口是关闭的
当检查的是一个文件时:
present/started:在检查到文件存在才会继续
absent:检查到文件被移除后才会继续
sleep # 两次检查之间sleep的秒数,默认1秒
timeout # 检查的等待超时时间(秒数,默认300)
#探测22和80端口 172.16.204.134 | SUCCESS => { "changed": false, "elapsed": 3, "path": null, "port": 22, "search_regex": null, "state": "started" } [root@manager1 opt]# ansible test -m wait_for -a 'timeout=10 port=80 delay=3' 172.16.204.134 | FAILED! => { "changed": false, "elapsed": 10, "msg": "Timeout when waiting for 127.0.0.1:80" }