第一个ansible例子

本文将介绍如何使用Ansible在远程主机上打印“Hello world”。

主机信息

  • Ansible主机:192.168.2.104

  • 目标主机:192.168.2.105

步骤

以下操作均在Ansible上执行

1、编辑/etc/ansible/hosts文件,加入以下内容

192.168.2.105 ansible_port=22 ansible_user=root ansible_ssh_pass=root

2、执行以下命令,然后会发现在192.168.2.105的/root/多了一个文件hello.txt,文件内容为hello world

$ ansible 192.168.2.105 -m shell -a "echo 'hello world' > /root/hello.txt" 
192.168.2.105 | CHANGED | rc=0 >>

该命令中-m shell表示使用Ansible的shell模块,-a后面为该模块的参数。

多台主机批量执行

如果我们要在多台主机上打印“Hello world”,那么我们可以如下做。

首先,编辑/etc/ansible/hosts如下:

192.168.2.105 ansible_port=22 ansible_user=root ansible_ssh_pass=root
192.168.2.106 ansible_port=22 ansible_user=root ansible_ssh_pass=root

[all]
192.168.2.105
192.168.2.106

然后执行命令

$ ansible all -m shell -a "echo 'hello world' > /root/hello.txt"

Last updated