因为最近工作中会经常需要提交代码,手动在多个服务器上拉取代码及重启各种服务,占用不少时间而且有的可能还会忘了重启,感觉挺麻烦的,就抽空学习了一下ansible. 今天完成了项目相关的自动拉取代码,重启服务的脚本。大概记录一下。
首先需要安装ansible.
pip install ansible
安装ansible 之后,可以通过ansible --version是可以查看具体的版本内容,以及配置文件的。
ansible 有两个比较重要的文件。一个是ansible 的config文件。一个是host文件。
其中config文件里面可以指定inventory, 就是具体的hosts文件的位置,你要执行任务,要确定你能连接到哪些服务器。而hosts里面就是存放配置信息的。
我的ansible的配置文件就放在了/etc/ansible/ansible.cfg.
[defaults]
inventory=/root/hosts
[ssh-connection]
ssh_args = -o StrictHostKeyChecking=no
而这里的hosts文件可以通过配置组的方式来做, 例如:
[test]
server1 ansible_ssh_host=192.168.0.2 ansible_ssh_port=22 ansible_ssh_user=root ansible_private_key_file=/home/root/.ssh/id_rsa ansible_become_pass=ansible
这里我觉得我需要说明的是private_key_file是通过配置key的方式登录,但是因为需要登录后从当前用户切换到其他用户,需要root的密码,所以配置文件里面需要配置ansible_become_pass这一项,即敲下sudo su other的密码。
这里我通过起别名的方式来指定每一台服务器
具体用的时候怎么写呢?
这里我简单给个case, 假设我们要在server1, server2上从当前的other用户切换到there用户,并拉取代码。并重启online服务。
---
- hosts: server1,server2
remote_user: other
tasks:
- name: checkout to there_home and pull onlineProject
become: yes
become_method: sudo
become_user: there
shell: "cd /home/there/server/online && git pull origin master"
- name: restart online systemd service
become: yes
become_method: sudo
become_user: root
shell: "cd /etc/systemd/system && systemctl restart online.service"