部署到云主机(公网IP)
# 介绍
Ansible 可以从中央控制节点统一配置服务器、安装软件或执行各种 IT 任务。它采用一对多、 无客户端(agentless)的机制, 从控制节点上通过 SSH 发送指令给远端的客户机来完成任务(除了 SSH 外也可以用别的协议)。
# 示例
# 前置准备
1.
首先在需要部署的(linux)主机上执行下面的命令,获取密钥:
ssh-keygen -t ed25519 -f ~/.ssh/ssh-key
2.
将1
生成的密钥存放在私有仓库
(查看示例仓库 (opens new window)),
公钥内容追加到目标机器的 /root/.ssh/authorized_keys 文件中:
- ssh-key.yml
PRIVATE_KEY: |
# 这里填写生成的密钥
xxxxxx
xxxxxx
3.
确保仓库中有如下文件,如果没有请新增:
.coding-ci.yml
hosts
playbook.yml
示例文件如下:
- .coding-ci.yml
# .codingci.yml
master:
push:
stages:
- name: copy to cvm
imports: https://xxx.coding.net/p/plugins/d/oci-private-key/git/tree/master/ssh-key.yml
image: plugins/ansible
settings:
private_key: $PRIVATE_KEY
inventory: hosts
playbook: playbook.yml
- hosts
# hosts
# 这里填写主机分组名
[hostgroup]
# 这里填写部署主机的ip
114.114.114.114
- playbook.yml
# playbook.yml
- hosts:
- hostgroup
tasks:
# 执行脚本
- name: echo hello
shell: echo hello orange
完整的文件结构如下(查看完整文件示例仓库 (opens new window)):
- oci_project ......项目根目录
- .coding-ci.yml ......ci配置文件
- hosts ......主机分组配置
- playbook.yml ......主机任务
# 可连接公网的主机部署playbook
- playbook.yml
# playbook.yml
- hosts:
- hostgroup
tasks:
# 复制工作空间下代码文件
- name: copy
copy:
# 源路径
src: /workspace
# 目标路径
dest: /dir/to/
# 启动app
- name: run app
# go run xxx;pyhton run.py;java xxx
shell: go run main.go
# 主机编排
在仓库中添加hosts文件,将要部署的主机进行分组编排,方便实现灰度或者蓝绿发布等措施。
ungrouped:
hosts:
mail.example.com:
webservers:
hosts:
foo.example.com:
bar.example.com:
dbservers:
hosts:
one.example.com:
two.example.com:
three.example.com:
east:
hosts:
foo.example.com:
one.example.com:
two.example.com:
west:
hosts:
bar.example.com:
three.example.com:
prod:
children:
east:
test:
children:
west:
# 部署过程
在仓库中添加playbook.yml文件,指定具体部署过程。
- name: Update web servers
#指定执行的主机分组
hosts: webservers
#指定执行用户
remote_user: root
tasks:
- name: Ensure apache is at the latest version
ansible.builtin.yum:
name: httpd
state: latest
- name: Write the apache config file
ansible.builtin.template:
src: /srv/httpd.j2
dest: /etc/httpd.conf
- name: Update db servers
hosts: databases
remote_user: root
tasks:
- name: Ensure postgresql is at the latest version
ansible.builtin.yum:
name: postgresql
state: latest
- name: Ensure that postgresql is started
ansible.builtin.service:
name: postgresql
state: started
# 更多用法
← 部署到TSF 部署到云主机(堡垒机) →