Ansible-02-批量执行远程命令,查看结果

前言
本文章使用ansible脚本,在主服务器(即操作的服务器)往其他服务器创建一个txt脚本,并在脚本中写入Hello,ansible

1、服务器准备

192.168.0.1 192.168.0.2

2、创建playbook

---
- name: create a txt file with hello,ansible content
  hosts: 192.168.0.2  # 替换为你的目标主机
  tasks:
    - name: Ensure the parent directories exist
      ansible.builtin.file:
        path: "/home/zxh/ansible"
        state: directory
        mode: '0755' #非必须
        recurse: yes
    - name: Create the test.txt file with content
      copy:
        content: "hello, ansible"
        dest: "/home/zxh/ansible/test.txt"  # 目标机器上创建文件的路径
        mode: '0644'  # 设置文件权限

如果目录/home/zxh/ansible/存在,则可去掉以下部分

- name: Ensure the parent directories exist
      ansible.builtin.file:
        path: "/home/zxh/ansible"
        state: directory
        mode: '0755'
        recurse: yes

3、执行ansible-playbook命令,开始批量操作

ansible-playbook -i 192.168.0.2, create_txt_file.yml

4、进入192.168.0.2 查看创建文件

ssh root@192.168.0.2

到此,就完成了使用ansible进行批量操作。但是,在执行ansible-playbook命令时,如果一个个添加IP地址,则会导致很繁琐,也不容易观察。所以ansible提供了更为简单的方式进行配置IP。

1、配置Ansible的hosts

Ansible 默认通过 /etc/ansible/hosts 或其他配置文件来查找主机列表,如下:

[ansible_test]
192.168.0.2

2、修改playbook的目标IP部分为ansible_test

---
- name: create a txt file with hello,ansible content
  hosts: ansible_test  # 替换为你的目标主机
  tasks:
    - name: Ensure the parent directories exist
      ansible.builtin.file:
        path: "/home/zxh/ansible"
        state: directory
        mode: '0755' #非必须
        recurse: yes
    - name: Create the test.txt file with content
      copy:
        content: "hello, ansible"
        dest: "/home/zxh/ansible/test.txt"  # 目标机器上创建文件的路径
        mode: '0644'  # 设置文件权限

3、执行ansible-playbook命令,这次不需要加IP了

ansible-playbook create_txt_file.yml

4、进入192.168.0.2 查看创建文件

ssh root@192.168.0.2

OK,万事大吉,本文结束。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值