-
主机设定:
server1 172.25.254.51 gitlab主机
server2 172.25.254.52 jenkins+docker主机
server3 172.25.254.53 harbor仓库主机 docker
server7 172.25.254.57 docker主机
server8 172.25.254.58 测试环境主机
server9 172.25.254.59 生产环境主机 -
在server8和server9安装ansible:
wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo
yum install ansible -y
一、配置gitlab和server1
- 在gitlab新建一个项目:
- 在server1克隆这个项目:
git clone git@172.25.254.51:root/playbook.git
- 编辑一个playbook:
playbook的内容为安装并启动httpd
[root@server1 ~]# ls
anaconda-ks.cfg demo playbook
[root@server1 ~]# cd playbook/
[root@server1 playbook]# vim playbook.yml
[root@server1 playbook]# cat playbook.yml
##写入
---
- hosts: all
tasks:
- name: install httpd
yum:
name: httpd
state: present
- name: start httpd
service:
name: httpd
state: started
- jenkins可以通过参数化构建,创建inventory文件:
[root@server1 playbook]# mkdir inventory
[root@server1 playbook]# cd inventory/
[root@server1 inventory]# vim test
[root@server1 inventory]# cat test
[test]
172.25.254.58
[root@server1 inventory]# vim prod
[root@server1 inventory]# cat prod
[prod]
172.25.254.59
在运行playbook时可以通过-i
选项来指定不同的inventory文件。
- 创建ansible配置文件,要求远程连接时使用ansible用户并以sudo的方式执行:
[root@server1 playbook]# vim ansible.cfg
[root@server1 playbook]# cat ansible.cfg
[defaults]
remote_user = ansible
[privilege_escalation]
become=True
become_method=sudo
become_user=root
become_ask_pass=False
二、配置jenkins
- 在jenkins创建一个ansible项目:
三、配置server7和server8
- 在执行ansible playbook时需要ssh免密,但是jenkins在构建的时候使用的是普通用户jenkins,因此需要在这个用户下做免密:
usermod -s /bin/bash jenkins
su - jenkins
ssh-keygen
ssh-copy-id ansible@172.25.254.58
ssh-copy-id ansible@172.25.254.59
- 远程连接使用的用户是普通用户ansible,需要在客户端主机添加这个用户并进行配置:
useradd ansible
passwd ansible #设置密码
可以免密登录:
配置权限
visudo
##添加
ansible ALL=(ALL) NOPASSWD: ALL
此时在jenkins主机查看workspace:
[root@server2 ~]# su - jenkins
-bash-4.2$ cd workspace/
-bash-4.2$ ls
ansible ansible@tmp docker test test@tmp
-bash-4.2$ cd ansible
-bash-4.2$ ls
ansible.cfg inventory playbook.yml README.md
可以看到已经拿到了gitlab中的文件。
四、测试
- 使用参数化构建jenkins,在ansible项目的配置中:
- 构建中选择执行shell,并运行ansible playbook:
- 保存后可以开始构建,首先需要选择构建参数:
根据inventory文件的信息,选择test参数就意味着在server8的测试环境上远程执行这个playbook。