安装ansible [root@ansible ~]# yum install -y ansible
修改管理哪些主机的清单文件 [root@ansible ansible]# vi /etc/ansible/hosts [webserver] 192.168.1.21 192.168.1.22 192.168.1.23
给ansible和被管理的主机之间做一个密钥登录 [root@ansible ansible]# ssh-keygen [root@ansible ansible]# ssh-copy-id 192.168.1.21
管理主机分两种方式(命令/剧本) 命令: 命令格式 ansible <hosts> [options]
例子1: ping 测通是否通畅 [root@ansible ansible]# ansible webserver -m ping -u root ...省略
例子2: 调用目录下的echo命令 [root@ansible ansible]# ansible all -a "/bin/echo hello world" ...省略
例子3: copy文件到另一个目录 [root@ansible ansible]# ansible webserver -m copy -a "src=/etc/passwd dest=/opt/passwd"
...省略
例子4: 安装软件 [root@ansible ansible]# ansible webserver -m yum -a "name=lrzsz" ...省略
例子5: 添加用户 [root@ansible ansible]# ansible webserver -m user -a "name=zhangsan password=123"
例子6: 启动系统的某个服务 [root@ansible ansible]# ansible webserver -m service -a "name=sshd state=started" ...省略 [root@ansible ansible]# ansible webserver -m service -a "name=httpd state=started" ...省略 [root@ansible ansible]# ansible webserver -m service -a 'name=httpd state=restarted' ...省略
例子7: 重启某个服务 [root@ansible ansible]# ansible webserver -m service -a "name=httpd state=restarted" ...省略
例子8: 指定3台机器执行同一个命令(属于并行执行) [root@ansible ansible]# ansible webserver -a "echo hello" -f 3 ...省略
例子9: 获取系统信息 [root@ansible ansible]# ansible webserver -m setup ...省略
剧本: Playbook组成
hosts: 目标主机
remote_user: 执行操作的用户身份
vars: 执行中的一些变量
tasks: 定义顺序执行的action,每个action调用一个模块
handers: event处理操作,仅有在action触发时才会执行,多次触发只执行一次并按照声明的顺序执行。
例子10: 安装httpd服务 [root@ansible /]# vi test.yml
-
hosts: webserver remote_user: root tasks:
- name: install httpd yum: pkg=httpd state=latest
-
hosts: webserver remote_user: root tasks:
- name: start httpd service: name=httpd state=started
例子11: 获取debug信息 [root@ansible /]# vi debug.yml
- hosts: webserver
remote_user: root
tasks:
- name: debug debug: msg: "{{ansible_default_ipv4.gateway}}"
例子12: shell模块 [root@ansible /]# vi shell.yml
- hosts: webserver
remote_user: root
tasks:
- name: guanbifanghuoqiang shell: systemctl stop firewalld
例子13: 拷贝模块 [root@ansible /]# vi copy.yml
-
hosts: all remote_user: root tasks:
- name: copy copy: src=/etc/passwd dest=/home 例子14:创建用户 然后再 删除用户 执行双任务 [root@ansible /]# vi user.yml
-
hosts: all remote_user: root tasks:
-
name: create user user: name: apeng uid: 5000 group: ftp shell: /bin/bash groups: apeng append: yes
-
name: delete user user: name: apeng state: absent remove: yes
-
例子15: 安装httpd 然后再 卸载 [root@ansible /]# vi yum.yml
- hosts: all
remote_user: root
tasks:
- name: install httpd yum: name: httpd state: latest
- name: remove httpd yum: name: httpd state: absent
实例16: command模块 [root@ansible /]# vi command.yml
- hosts: root
remote_user: root
tasks:
- name: cmd command: ls