前言
本文章使用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,万事大吉,本文结束。