1
0
0

Ansible 基础语法及Copy指令

2026-08-12
2026-08-13

Ansible

基础语法

ansible test -m shell -a "hostname"

  • ansible:这是 Ansible 的主要命令,用于执行各种操作。
  • test:这是目标主机的名称,可以是单个主机或者一个定义在 Ansible inventory 文件中的主机组。
  • -m shell:这是指定要在目标主机上执行的模块,这里是 shell 模块,表示要执行一个 shell 命令。
  • -a "hostname":这是传递给 shell 模块的参数,即要在目标主机上执行的命令是 "hostname"。

配置免密登录

生成私钥

ssh-keygen

向主机分发私钥

ssh-copy-id root@192.168.1.1

scp -r root@192.168.1100:/opt/node_export /opt/

copy关键字

ansible test  -m copy -a "src=/test/a.txt dest=/test/"
参数描述
src指定被copy的文件或目录
dest指定文件将被拷贝到远程主机的哪个目录中
force当远程主机的目标路径中已经存在同名文件,并且与ansible主机中的文件内容不同时,是否强制覆盖,可选值有yes和no,默认值为yes,表示覆盖,如果设置为no,则不会执行覆盖拷贝操作,远程主机中的文件保持不变。
backup当远程主机的目标路径中已经存在同名文件,并且与ansible主机中的文件内容不同时,是否对远程主机的文件进行备份,可选值有yes和no,当设置为yes时,会先备份远程主机中的文件,然后再将ansible主机中的文件拷贝到远程主机。
mode指定文件拷贝到远程主机后的权限,比如你想将权限设置为”rw-r–r–“,则可以使用mode=0644表示,如果你想要在user对应的权限位上添加执行权限,则可以使用mode=u+x表示

ansible test -m copy -a "src=/home/node dest=/opt/node_export/ "

ansible hpc-m copy -a "src=/home/node_export/ dest=/opt/node_export/ "

ansible test -m file -a "path=/opt/node_export state=directory"

/usr/lib/systemd/system

ansible hpc-m copy -a "src=/home/node_exporter.service dest=/usr/lib/systemd/system/ "

查看主机时间

ansible all -m command -a "date"

支持与分享

如果这篇文章对你有帮助,欢迎分享给更多人或者给予支持!