前言
部署Linux虚拟机的时候我们往往采用minimal安装的方法,所以一般每次用于学习或部署研究性服务的时候需要重复性的进行一些配置和优化,所以大概想了一个能够减少工作的一些自动化初始化的方法。
一般初始化
按照个人习惯的话,先配置网络、时间同步、yum源、防火墙、selinux、swap。
1.网络配置
ini
#修改网卡配置文件来先获取DHCP服务器分配的IP地址
sed -i "s/ONBOOT=no/ONBOOT=yes/" /etc/sysconfig/network-scripts/ifcfg-ens192
systemctl restart network
查看从DHCP服务器上获取到的IP地址,后面可以通过手动设定静态ip来固定ip。
2.时间同步
bash
yum install ntp -y
timedatectl set-timezone "Asia/Shanghai"
systemctl enable ntpd
systemctl restart ntpd
date
3.更换yum源地址(CentOS7的yum源大部分已经无法使用了)
这里用的是华为源镜像站,更换yum源后安装一些基础的软件
bash
yum install wget -y
wget -O /etc/yum.repos.d/CentOS-Base.repo https://repo.huaweicloud.com/repository/conf/CentOS-7-anon.repo
yum clean all
yum makecache
#再安装基础需要用到的软件
yum install vim epel-release traceroute net-tools socat conntrack nfs-utils git -y
4.安全性初始化
bash
# 关闭防火墙
systemctl stop firewalld
systemctl disable firewalld
# 关闭selinux
sed -i 's/enforcing/disabled/' /etc/selinux/config # 永久
setenforce 0 # 临时
# 关闭swap
swapoff -a # 临时
sed -ri 's/.*swap.*/#&/' /etc/fstab # 永久
在Gitlab-CI中利用Ansible自动初始化
前提:我的Gitlab使用的运行在是K8S环境中的Deployment应用,在前提配置上有一些更多的工作,比如:配置Harbor镜像仓库,构建好带有sshnopass的ansible镜像等。
如果是直接在Linux上部署的Gitlab的话只需要部署好Gitlab-Runner在本机或其他机器上并进行相应注册好,这里不再赘述其他。
我这里准备了三个文件,.gitlab-ci.yml,hosts_pass,playbook.yaml。项目运行会自动生成名为hosts的文本文件。
.gitlab-ci.yml:配置目标虚拟机的免密操作,生成hosts清单,开始ansible任务
hosts_pass:保存目标虚拟机信息,存储ip和密码
playbook.yaml:虚拟机执行的初始化操作任务
bash
# .gitlab-ci.yml
stages:
- deploy
deploy_server:
stage: deploy
#下方image在主机模式下不需要写
image: harbor.povison-pro.com/library/alpinelinux/ansible:latest
script:
- echo -e "y\n" | ssh-keygen -q -t rsa -N "" -f ~/.ssh/id_rsa #创建密钥文件
- awk '{print "sshpass -p " $2 " ssh-copy-id -o StrictHostKeyChecking=no root@" $1}' hosts_pass | sh #配置单向密钥操作
- echo "[node]" > hosts #创建hosts清单文件
- awk '{print $1}' hosts_pass >> hosts #配置hosts清单文件
- ansible-playbook -i hosts playbook.yaml
yaml
#playbook.yml
---
- name: 配置服务器
hosts: all
become: true
vars:
ansible_ssh_common_args: '-o StrictHostKeyChecking=no'
tasks:
- name: 安装 ntp 和 wget
package:
name: "{{ item }}"
state: present
loop:
- ntp
- wget
- name: 启用并启动 ntpd 服务
systemd:
name: ntpd
state: started
enabled: yes
- name: 设置时区为上海
command: timedatectl set-timezone "Asia/Shanghai"
- name: 更换 CentOS yum 源
command: wget -O /etc/yum.repos.d/CentOS-Base.repo https://repo.huaweicloud.com/repository/conf/CentOS-7-anon.repo
notify:
- 清理和更新 yum 缓存
- name: 安装额外软件包
package:
name: "{{ item }}"
state: present
loop:
- nfs-utils
- epel-release
- traceroute
- net-tools
- git
- vim
- name: 关闭防火墙
systemd:
name: firewalld
state: stopped
enabled: no
- name: 关闭 SELinux
lineinfile:
path: /etc/selinux/config
regexp: '^(SELINUX=)'
line: 'SELINUX=disabled'
- name: 关闭 swap
command: "{{ item }}"
loop:
- swapoff -a
- sed -ri 's/.*swap.*/#&/' /etc/fstab
notify:
- 重启服务器
handlers:
- name: 清理和更新 yum 缓存
command: yum makecache
- name: 重启服务器
shell: sleep 3 && reboot
async: 1
poll: 0
bash
#ip pass
192.168.110.41 000000 #示例,如果感觉比较敏感也可以改为使用环境变量进行配置
效果如图
文章写的比较粗糙,如果有其他问题欢迎交流讨论啦。