一,copy模块的作用:
复制文件到受控的远程主机
说明:刘宏缔的架构森林是一个专注架构的博客,地址:https://www.cnblogs.com/architectforest
对应的源码可以访问这里获取: https://github.com/liuhongdi/
说明:作者:刘宏缔 邮箱: 371125307@qq.com
二,copy模块的例子:
1,复制文件
#src : 被复制到远程主机的本地文件
#dest : 源文件复制到的远程主机的绝对路径
[liuhongdi@centos8 ~]$ ansible yujian -m copy -a 'src=/home/liuhongdi/china_ip.txt dest=/home/webop/china_ip2.txt'
2,受控机目标文件所在目录不存在时会报错:
[liuhongdi@centos8 ~]$ ansible yujian -m copy -a 'src=/home/liuhongdi/china_ip.txt dest=/home/webop1/china_ip2.txt' 121.122.123.47 | FAILED! => { "ansible_facts": { "discovered_interpreter_python": "/usr/libexec/platform-python" }, "changed": false, "checksum": "9194708f7a019d4fecf3af3284734136cc0b3383", "msg": "Destination directory /home/webop1 does not exist" }
3,目标文件已存在?
如果与源文件内容相同,则不会改变,
如果与源文件内容不同,则会覆盖目标文件
可以用backup指定是否覆盖前做备份
例子:
#backup=yes : 指定在覆盖目标文件前要做备份
[liuhongdi@centos8 ~]$ ansible yujian -m copy -a 'src=/home/liuhongdi/china_ip.txt dest=/home/webop/china_ip2.txt backup=yes'
备份文件的格式:带有时间标志:登录到受控机查看
[webop@blog ~]$ ls china_ip2.txt china_ip2.txt.814.2020-04-19@11:09:53~
4,指定目标文件的权限
例:
#owner: 设置文件/目录的所属用户
#group: 设置文件/目录的所属组
#mode: 设置文件权限,使用八进制数字(如0777,0644)
[liuhongdi@centos8 ~]$ ansible yujian -m copy -a 'src=/home/liuhongdi/china_ip.txt dest=/home/webop/china_ip3.txt owner=webop group=webop mode=0777'
登录到受控机查看效果:
[webop@blog ~]$ ll -rwxrwxrwx 1 webop webop 131707 Apr 19 11:32 china_ip3.txt
5,复制一个目录:
# 源目录带/和不带/的区别:
#带/表示只复制目录下的文件
#不带/表示复制目录本身及目录下的文件
[liuhongdi@centos8 ~]$ ls work multi-user.target.service.txt userid.csv [liuhongdi@centos8 ~]$ ansible yujian -m copy -a 'src=/home/liuhongdi/work/ dest=/home/webop/' 121.122.123.47 | CHANGED => { "changed": true, "dest": "/home/webop/", "src": "/home/liuhongdi/work/" }
[liuhongdi@centos8 ~]$ ansible yujian -m copy -a 'src=/home/liuhongdi/work dest=/home/webop/work2' 121.122.123.47 | CHANGED => { "changed": true, "dest": "/home/webop/work2/", "src": "/home/liuhongdi/work" }
6,指定目标文件内容:
#content:用content代替src参数,会把文档的内容输出到指定的目标文件
[liuhongdi@centos8 ~]$ ansible yujian -m copy -a 'content="abc" dest=/home/webop/china_ip4.txt'
登录到受控机查看效果
[webop@blog ~]$ more china_ip4.txt abc
7,当目标文件存在,且内容不一致时,不替换目标文件
#force=no
,则只有在目标不存在的情况下才会传输文件
[liuhongdi@centos8 ~]$ ansible yujian -m copy -a 'src=/home/liuhongdi/china_ip.txt dest=/home/webop/china_ip3.txt force=no'
三,查看ansible版本
[root@centos8 liuhongdi]# ansible --version ansible 2.9.5
四,查看centos版本
[root@centos8 conf]# cat /etc/redhat-release CentOS Linux release 8.1.1911 (Core)