Jenkins+Ansible 实现自动化运维 DevOps

时间:2022-07-22
本文章向大家介绍Jenkins+Ansible 实现自动化运维 DevOps,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

Jenkins+Ansible 实现自动化运维 DevOps

自动化运维流程图

前置环境安装

服务器之间配置SSH免密登录

转至 https://www.arcinbj.com/archives/ssh-keygen

Java安装

转至 https://www.arcinbj.com/archives/java-install

Git安装

yum install -y git

Maven安装

转至 https://www.arcinbj.com/archives/maven-install

Ansible安装

yum install -y ansible

# 文件夹后面会用到
mkdir -p /opt/ansible
mkdir -p /opt/ansible/host
mkdir -p /opt/ansible/yaml

Jenkins安装

注:个人感觉 还是用 对应的安装包 比如Linux 就选用Linux的安装包

鄙人刚开始选的war包 结果折腾了好久 要么拿不到PATH命令 要么拿到命令没有授权 很脑袋疼 直接选对应包 一键轻松

官网下载

https://jenkins.io

国内镜像下载

因为墙的原因,直接从官网下载会比较耗时

1.下载jenkins

国内清华大学软件开源镜像站

mkdir -p /opt/jenkins

cd /opt/jenkin

wget https://mirrors.tuna.tsinghua.edu.cn/jenkins/redhat/jenkins-2.229-1.1.noarch.rpm

2.安装

rpm -i /opt/jenkin/jenkins-2.229-1.1.noarch.rpm

3.配置

配置权限

vi /etc/sysconfig/jenkins

# 将原先的 JENKINS_USER = "jenkins" 
# 改为 JENKINS_USER = "root"
# 获得全局权限

配置国内加速镜像

vi hudson.model.UpdateCenter.xml

# 将Url 改为
https://mirrors.tuna.tsinghua.edu.cn/jenkins/updates/update-center.json

3.启动Jenkins

service jenkins start 或 systemctl start jenkins.service

4.初始化Jenkins

4.安装插件

 Extended Choice Parameter Plug-In
 # 用来做 多选框 

5.配置环境变量

Linux 输入 echo $PATH

复制下来 保存到 Jenkins环境变量中

6.新建项目

设置构建选项-变量传参

设置构建Shell脚本

if [ -z  "${version}" ]; then 
   errorParam="版本号不可为空";
   echo $errorParam;
   exit 1;
fi

cd /data/project

rm -rf demo-project

# 克隆项目 可克隆分支 默认主分支
if [ -n  "${branch}" ]; then 
   git clone  -b ${branch} "http://git用户名:git用户密码@git地址/xxx.git";
fi
if [ -z  "${branch}" ]; then 
   git clone "http://git用户名:git用户密码@git地址/xxx.git";
fi


cd demo-project

# 打包 先clean 再package(如果不clean 有可能打包会丢文件)
mvn clean package

# 远程部署
ansible-playbook /opt/ansible/yaml/demo-shell.yaml -i /opt/ansible/host -e "version=${version} server=${server}"

Ansible

Ansible 发布端

YAML

- hosts: nginx_master
  remote_user: root
  tasks:
    - name: 拷贝代码-分发服务器
      tags: copy_code
      copy: src="/data/project/demo-project/target/demo.war" dest="/root/tempFile"
    - name: 分发服务器拷贝代码到-2号环境
      tags: startup_project
      shell: |
        ansible-playbook /opt/ansible/yaml/demo-copy.yaml -i /opt/ansible/host/2-host -e "version=${version} server=${server}"

HOST IP地址

[nginx_master]
xxx.xxx.xxx.xxx

Ansible 服务器分发端

YAML

- hosts: "{{server}}"
  remote_user: root
  tasks:
    - name: 拷贝代码
      tags: copy_code
      copy: src="/root/tempFile/demo.war" dest="/root/tempFile"
    - name: 构建代码
      tags: building_code
      shell: |
        cd /usr/local/shells
        sh ./tomcat-bulider.sh -version "{{version}}"
    - name: 启动项目
      tags: startup_project
      shell: |
        cd /usr/local/tomcat/apache-tomcat-7.0.93/bin
        nohup sh ./startup.sh &  

HOST IP地址

[server_1]
xxx.xxx.xxx.xxx

[server_2]
xxx.xxx.xxx.xxx

项目构建

转至 https://www.arcinbj.com/archives/linux-01

结语

鄙人,搭建了两天,中间淌过各种水,希望阅读的朋友少走弯路,代码无BUG!

喜欢的可以转发一下!