ansible自动化部署之路笔记

使用ansible编写自动化部署playbook,解放运维手工操作

模块使用笔记

changed_when判断条件,用于重发发布,检测服务是否已经启用

 1 - hosts: redis
 2   gather_facts: no
 3   tasks:
 4     # 判断是否已经发布
 5     - name: redis already deploy ?
 6       shell: . /etc/profile && . /etc/bashrc && docker ps -a | grep 'redis' ; echo $?
 7       register: result_deploy_redis
 8       changed_when: result_deploy_redis['stdout']|int != 0
 9 
10     - name: Pull Docker Images
11       shell: "docker pull {{registry_address}}:5000/{{item}}:latest"
12       with_items:
13         - redis
14       when: result_deploy_redis['stdout']|int != 0

lineinfile模块用于修改文本中某一行

1     - name: modify redis passwd
2       lineinfile:
3         dest: "/etc/redis/redis.conf"
4         regexp: "^requirepass"
5         line: "requirepass {{redis_pwd}}"
6       when: result_deploy_redis['stdout']|int != 0

replace用于精准匹配,修改配置特别适用

1     - name: Edit config01 of kamailio
2       replace:
3         path: /etc/kamailio/kamailio.cfg
4         regexp: "mysql://.*testxx"
5         replace: "mysql://{{ mysql_user }}:{{ mysql_passwd }}@{{ mysql_ip }}:3306/testcc"
6       when: result_deploy['stdout']|int != 0

copy模块就比较坑了,因为ansible本身的原因,拷贝超过50MB的文件特别特别特别的慢,这里使用synchronize模块来代替,其实就是rsync服务,需要在目标服务器安装rsync服务

1 - name: Copy logstah software
2 synchronize:
3 src: "{{deploy_dir}}/icc_deploy/major_data/logstash/logstash-5.6.4"
4 dest: "{{deploy_dir}}/App"
5 when: result_deploy_logstash['stdout']|int != 0

在创建swarm集群时,需要在节点机器获取主机名,然后委派给master主机执行命令,需要使用delegate_to模块

1 #针对节点打标签,ansible是swarm的master节点,即本机
2 - hosts: web
3   gather_facts: yes
4   tasks:
5     - name: "web node tagging"
6       shell: "echo `docker node update --label-add web=true {{ansible_hostname}}`"
7     - name: "delegate_to"
8       shell: "docker node update --label-add web=true {{ansible_hostname}}"
9       delegate_to: localhost
原文地址:https://www.cnblogs.com/shetao/p/14892535.html