引言
Ansible是简单强大的自动化运维工具。本文介绍Ansible的使用和实战。
一、Ansible安装
1 2 3 4 5 6 7 8 9 10 11
| yum install ansible
apt install ansible
pip install ansible
ansible --version
|
二、Inventory配置
1 2 3 4 5 6 7 8 9 10 11
| [web] web1 ansible_host=192.168.1.10 web2 ansible_host=192.168.1.11
[db] db1 ansible_host=192.168.1.20
[all:vars] ansible_user=root ansible_ssh_private_key_file=/root/.ssh/id_rsa
|
三、Ad-Hoc命令
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| ansible all -m ping
ansible web -m shell -a "uptime"
ansible web -m copy -a "src=/tmp/file.txt dest=/tmp/"
ansible web -m yum -a "name=nginx state=present"
ansible web -m service -a "name=nginx state=started enabled=yes"
|
四、Playbook编写
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| --- - name: Install and configure Nginx hosts: web become: yes vars: nginx_port: 80 nginx_root: /var/www/html tasks: - name: Install Nginx yum: name: nginx state: present - name: Copy config file template: src: nginx.conf.j2 dest: /etc/nginx/nginx.conf notify: Restart Nginx - name: Start Nginx service: name: nginx state: started enabled: yes handlers: - name: Restart Nginx service: name: nginx state: restarted
|
1 2 3 4 5 6 7 8
| ansible-playbook nginx.yml
ansible-playbook nginx.yml --syntax-check
ansible-playbook nginx.yml --check
|
五、角色(Roles)
1 2 3 4 5 6 7 8 9 10 11 12
| ansible-galaxy init nginx
nginx/ ├── defaults/ ├── files/ ├── handlers/ ├── meta/ ├── tasks/ ├── templates/ └── vars/
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| --- - name: Install Nginx yum: name: nginx state: present
- name: Configure Nginx template: src: nginx.conf.j2 dest: /etc/nginx/nginx.conf notify: Restart Nginx
- name: Start Nginx service: name: nginx state: started enabled: yes
|
1 2 3 4 5 6
| --- - hosts: web roles: - nginx - mysql
|
六、实战案例:部署Java应用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| --- - name: Deploy Java Application hosts: app become: yes vars: app_name: myapp app_port: 8080 app_jar: myapp.jar tasks: - name: Install Java yum: name: java-11-openjdk state: present - name: Create app directory file: path: /opt/{{ app_name }} state: directory - name: Copy jar file copy: src: target/{{ app_jar }} dest: /opt/{{ app_name }}/{{ app_jar }} - name: Create systemd service template: src: app.service.j2 dest: /etc/systemd/system/{{ app_name }}.service - name: Start application systemd: name: "{{ app_name }}" state: restarted enabled: yes daemon_reload: yes
|
总结
Ansible核心:
- 无Agent:SSH连接,无需安装客户端
- Playbook:YAML格式,易读易写
- 幂等性:多次执行结果一致
- 角色:模块化组织
参考资料