Ansible环境主要由三部分组成:
官网( https://docs.ansible.com/ansible/latest/getting_started/index.html )提供的架构如下图所示:

用途:
优点:
apt install ansible
注:下面都是使用root用户。
首先需要一个inventory文件,默认文件为 /etc/ansible/hosts ,也可以使用 -i 参数来显式指定。
创建文件 /etc/ansible/hosts ,内容如下:
[myvms]
192.168.1.55
运行 ansible all --list-hosts ,如下:
➜ ansible ansible all --list-hosts
hosts (1):
192.168.1.55
接下来,和远程节点建立SSH连接。
把主控节点的private key(一般是 ~/.ssh/id_rsa 文件)复制到远程节点的 ~/.ssh/authorized_keys/ 目录下(如果本地没有就用 ssh-keygen -t rsa 生成一下),可以用 ssh-copy-id root@ 来复制。
注:ansible可用 -u 参数指定登录用户名。
测试一下 ssh root@192.168.1.55 ,确保可以免密登录。
注: root@ 可以省略,但本地必须是root用户(因为复制时两端都使用的root用户)。
接下来用 ansible all -m ping 测试连通性:
➜ ~ ansible all -m ping
192.168.1.55 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/libexec/platform-python"
},
"changed": false,
"ping": "pong"
}
其语法为:
ansible [pattern] -m [module] -a "[module options]"
下面是一个“Hello World”例子:
➜ ~ ansible all -m debug -a "msg='hello world'"
192.168.1.55 | SUCCESS => {
"msg": "hello world"
}
其语法为:
ansible-playbook -i /path/to/my_inventory_file -u my_connection_user -k -f 3 -T 30 -t my_tag -M /path/to/my_modules -b -K my_playbook.yml
其中:
-i :指定inventory文件-u :指定SSH连接用户名-k :询问SSH连接密码-f :指定N个fork-T :设置超时时间(秒)-t :只运行指定tag的task-M :从指定路径载入本地module-b :executes with elevated privileges (uses become)-K :prompts the user for the become password.例:
创建 playbook1.yml 文件,内容如下:
- name: Hello ansible
hosts: all
tasks:
- name: PingPingPing
ansible.builtin.ping:
- name: Say hello
ansible.builtin.debug:
msg: Hello world
运行:
➜ ansible ansible-playbook playbook1.yml
PLAY [Hello ansible] *******************************************************************************
TASK [Gathering Facts] *****************************************************************************
ok: [192.168.1.55]
TASK [PingPingPing] ********************************************************************************
ok: [192.168.1.55]
TASK [Say hello] ***********************************************************************************
ok: [192.168.1.55] => {
"msg": "Hello world"
}
PLAY RECAP *****************************************************************************************
192.168.1.55 : ok=3 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
https://docs.ansible.com/ansible/latest/index.html
ansible -h :查看 ansible 用法ansible-doc :查看指定plugin用法,例如 ansible-doc pingansible-doc -h 查看 ansible-doc 用法。