基于ansible的生产环境部署构建(十二) 角色maven

角色功能说明:

  • 该角色实现maven项目的构建和发布
  • 该角色使用的脚本比较简陋,该角色仅作为一个功能演示,后期会再做优化

角色部署:

  • 创建目录结构,创建软连接,关联默认变量文件
WorkDir=~/devops/ansible/os_init && cd ${WorkDir}
RoleName=maven
mkdir -pv roles/${RoleName}/{defaults,files,handlers,meta,tasks,templates,vars}
ln -s ${WorkDir}/defaults_var.yml roles/${RoleName}/defaults/main.yml
  • 创建项目构建发布脚本
cat >roles/${RoleName}/files/pro_mark.sh<<\EOF
#!/bin/bash
source /etc/profile
Pro_File=${1}
GitUser='root'
GitPass='vincent%40123'
cat ${Pro_File}|while read line
do
  IP=$(echo ${line}|awk '{print $1}')
  Git=$(echo ${line}|awk '{print $2}'|sed 's|https://||g')
  Project=$(echo ${line}|awk '{print $3}')
  Subpro=$(echo ${line}|awk '{print $4}')
  Java=$(echo ${line}|awk '{print $5}')
  Tomcat=$(echo ${line}|awk '{print $6}')
  Port=$(echo ${line}|awk '{print $7}')
  mkdir ${Subpro} && cd ${Subpro}
  git clone https://${GitUser}:${GitPass}@${Git}/${Project} &>/dev/null || echo "git clone error"
  cd * || echo "cd error"
  mvn -B -f pom.xml clean package -U -Dmaven.test.skip=true &> build.log || echo "maven error"
  ssh web_pro@${IP} "rm -rf /web/project/${Tomcat}_${Port}_${Subpro}/*" </dev/null || echo "rm ROOT.war error"
  find . -name "${Subpro}*.war" -exec scp {} web_pro@${IP}:/web/project/${Tomcat}_${Port}_${Subpro}/ROOT.war \; || echo "scp error"
  ssh web_pro@${IP} "ps -ef|grep java|grep ${Tomcat}_${Port}_${Subpro}|awk '{print \$2}'|xargs kill -9"
done
exit 0
EOF
  • 创建角色任务
cat >roles/${RoleName}/tasks/main.yml<<EOF
---
- name: "删除临时构建目录"
  file:
    path: /tmp/pro_mark
    state: absent
- name: "创建临时构建目录"
  file:
    path: /tmp/pro_mark
    state: directory
- name: "同步执行脚本"
  copy:
    src: pro_mark.sh
    dest: /tmp/pro_mark
- name: "安装git"
  yum:
    name: git
    state: latest
    disable_gpg_check: no
    update_cache: yes
- name: "安装构建工具maven"
  yum:
    name: maven
    state: latest
    disable_gpg_check: no
    update_cache: yes
- name: "列出所有配置文件"
  shell:
    ls
  args:
    chdir: "{{ pro_mark }}"
  register: pro_mark_list
- name: "传入文件,调用脚本,构建项目,分发war包"
  shell:
    "/bin/bash pro_mark.sh {{ pro_mark }}/{{ item }}"
  args:
    chdir: /tmp/pro_mark
  register: result
  with_items:
    - "{{ pro_mark_list.stdout_lines }}"
- name: "打印执行信息"
  debug:
    msg: "{{ result }}"
EOF
  • 创建任务playbook并执行
cat >os-init-11-${RoleName}.yml<<EOF
---
- hosts: localhost
  remote_user: root
  gather_facts: true
  roles:
    - ${RoleName}
EOF
ansible-playbook -i inventory/hosts os-init-11-${RoleName}.yml

[TOC]

你可能感兴趣的:(Ansible)