Python项目实战——Ansible自动化任务(2)(ansible中的playbook模式)

Ansible Playbook模式

1.1什么是Playbook及其组成

playbook不同于ad-hoc模式,适合部署复杂应用程序。优势:Playbook可以定制配置,可以按照指定的操作步骤有序执行,支持同步和异步方式。playbook是通过YAML格式来进行描述定义的, 语法简单,操作方便。playbook由一个或者多个play组成, 一个play可以包含多个task, 因此可使用多个不同的模块,完成一件事情。play: 定义的是主机的角色task:定义具体执行的任务,由模板定义的操作列表

1.2 Playbook的配置语法

playbook基本使用

ansible-playbook playbook.yml [options]

常用选项总结:

1.3 .yaml语法格式要点:

yaml文件以"---"作为文档的开始
缩进:表示层级结构,每个缩进由两个空格组成, 不能使用tab。
冒号: 以冒号结尾的除外,其他所有冒号后面所有必须有空格。
短横线: 表示列表项,使用一个短横杠加一个空格。
大小写敏感

1.4 用piaybook模式自动化运维操作

(1)ansible的主配置文件设定

[defaults]
#  资源清单inventory文件的位置
inventory = /etc/ansible/hosts
# 指向存放Ansible模块的目录,支持多个目录方式,只要用冒号(:)隔开就可以
library = /usr/share/ansible
# 设置默认执行命令的用户
sudo_user = root
# 设置是否检查SSH主机的密钥,值为True/False。
host_key_checking=False
# ssh连接的管理端口,默认为22端口,建议修改,更加安全
remoto_port = 22
# 存储ansible日志的文件(默认不记录日志)
log_path = /var/log/ansible.log

[ssh_connection]
ssh_args = -o StrictHostKeyChecking=no

(2)ansible的主机清单管理

[test]
172.25.254.10:22 ansible_ssh_user=root ansible_ssh_pass='123'
172.25.254.30:22 ansible_ssh_user=root ansible_ssh_pass='123'

(3)创建yaml文件 

此处需要开启3台服务器

# vim /etc/ansible/westos.yml   注意该文件可以键在任意位置

---
- hosts: test
  remote_user: root
  vars:
          filename: "westos.txt"
          http_port: 8080

  tasks: 
        - name: test
          file: name=/mnt/{{filename}} state='touch'
        - name: create new user
          user: name=skqnb uid=1111 system=yes shell=/bin/bash
        - name: install httpd service
          yum: name=httpd state='present'
        - name: config http
          template: src=./template/httpd.conf dest=/etc/httpd/conf/httpd.conf
          notify:
                - restart apache
        - name: copy index.html
          copy: src=./template/index.html dest=/var/www/html/index.html backup=yes mode=666 
  handlers:
        - name: restart apcahe   
          service: name=httpd state=restarted enabled=true   

(4)测试  在安装有ansible的服务器做测试

ansible-playbook westos.yml

猜你喜欢

转载自blog.csdn.net/weixin_43215948/article/details/107733737