ansible
ansible 是一个远程管理服务器的工具, 安装好后, 可以执行 ansible-playbook main.yml 来执行想要在远程服务器上操作的事情. 最大的好处就是用来自动部署应用. 本文主要是讲解一下 main.yml 文件怎么来编写.
main.yml
就是你要做具体事情的 yml 文件, 名字可以随便取. 大致如下:
--- - host: webservers // 要管理的远程服务器组名称, 服务器地址维护在/etc/ansible/hosts 里, 也可以直接写地址 vars: port: 9527 // 定义了一个变量 端口号 remote_user: root // 远程登录后用什么用户执行 pre_tasks: // 执行正式 task 之前执行的任务 - name: pre task // 任务名称 shell: echo 'execute pre task' // 执行一行 shell 命令, 支持 >> 等符号 roles: // 引入 roles, 可以理解为引用了一个其他项目 ansible 包, 引用的 roles 可以是另一个完整的 ansible 脚本 - role: my_role // 要引用的 role 名称 when: "ansible_os_family == 'RedHat'" // 判断条件, ansible_os_family 是一个内置变量, 可直接使用 tasks: // 按顺序执行以下 task - include: my_tasks/some_task.yml // 可以引入其他 yml 文件 - name: get hostname // 这是一个 task, 名称 command: cat log.log // 执行一行 command , 和 shell 类似, 但是不支持 >> 等操作符 register: result // 执行的结果, 设到 result 这个变量中, 后面可以使用 - name: set hostname shell: cat {{result.stdout}} >> host.text - name: task1 command: echo 'execute task1' - name: task2 start apache service: // 启动 httpd 服务器, service 是一个 ansible 内置模块, 读者可以自行查看更多模块, 包括下载复制等等 name: httpd state: started tags: - apache // 这是一个标签, 可以用 ansible-playbook main.yml --tags "apache" 指定只执行这个任务 - name: copy and set value of index.html template: // 这是一个复制方法, 也叫模块, 并且.j2文件中可以使用{{}}来设置需要替换的变量 src: templates/index.html.j2 dest: /etc/httpd/index.html notify: // 唤醒执行后面的 handlers 中名字叫 restart apache 的任务 - restart apache post_tasks: // 最后需要执行的任务 - name: posy task shell: echo 'execute post task' handlers: - name: restart apache debug: // 这是一个打印模块 msg: start restart apche
不错