ansible使用【3】--结合jenkin做参数化构建
1.实际效果:
2. Jenkins的配置信息是:
2.1 服务器的ip及配置信息是:
2.2 多选框的参数配置,
没有的话需要下载插件 Extended Choice Parameter
2.3 pipeline的设置
具体的pipeline是:
pipeline {
agent any
stages {
stage('Deploy tools') {
steps {
script {
def servers = SERVERS.split(',')
def hosts = "[webservers]\n"
for (server in servers) {
def parts = server.split(':')
hosts += "${parts[0]} ansible_user=${parts[1]} ansible_password=${parts[2]} ansible_become_pass=${parts[2]}\n"
}
def options = params.option.split(',')
def optionsSection = "[options]\n"
options.each { option ->
optionsSection += "option=${option}\n"
}
hosts += optionsSection
writeFile file: '/home/liqi/host_inventory.ini', text: hosts
}
sh 'ansible-playbook -i /home/liqi/host_inventory.ini /home/liqi/copy.yml'
}
}
}
}
这个内容简单解释下:
- 就是读取参数化配置,用for循环取出参数,保存到hosts变量里,再把hosts变量的内容写入文件host_inventory.ini中,最后执行ansible执行剧本。
2.4 验证一下是否写入成功:
这里,因为我之前配置的225和107是成功的!
3.构建成功的jenkins
4.剧本copy.ini内容
我这剧本,就是把主控机器的mini_common拷贝到目标机器(比如107,135等等),方便我后续执行测试
- hosts: webservers # 主机标签
become: yes
tasks:
- name: Update apt sources list # 更新apt源
become: yes
shell: sed -i 's|http://ports.ubuntu.com/ubuntu-ports/|https://mirrors.tuna.tsinghua.edu.cn/ubuntu-ports/|g' /etc/apt/sources.list
- name: Update apt package index # 更新apt
apt:
update_cache: yes
become: yes
- name: Ensure rsync is installed # 确保安装了rsync同步工具包
package:
name: rsync
state: present # present是已经准备好的意思
- name: Ensure directory exists # 确保目标目录存在,没有的就创建
file:
path: ~/liqi_test
state: directory
- name: Copy tools directory # 拷贝文件
synchronize: # 这个synchronize就是利用rsync来实现的,所以必须有rsync工具包
src: /home/mini_common/
dest: ~/liqi_test
become: no
参考资料 chatGPT