Ansible Playbook 实战
创建主机清单文件
1
2
3
4
5
6cat > /etc/ansible/hosts.ini <<EOF
# 云主机清单
[YZJ]
192.11.14.13 ansible_user=root ansible_ssh_pass=IxxsdasddwaXXXXXXX description="Web 主机"
192.11.14.[59:61] user=root ansible_ssh_pass=DXXXXXSCDDSSXCXSSk description="Kafka集群"
EOF创建 Playbook 文件 agent_deploy.yml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83- name: OCSP Agent自动部署(ARM/X86架构,文档路径写死)
hosts: all
gather_facts: yes
tasks:
# 1. 停止目标主机旧ocsp-agent服务
- name: 停止ocsp-agent服务
ansible.builtin.systemd:
name: ocsp-agent
state: stopped
ignore_errors: yes
# 2. 删除目标主机旧服务文件
- name: 删除旧ocsp-agent服务文件
ansible.builtin.file:
path: /etc/systemd/system/ocsp-agent.service
state: absent
ignore_errors: yes
# 3. 按架构设置部署机源文件路径
- name: 按架构设置部署机源文件路径
ansible.builtin.set_fact:
telegraf_source_path: "{% if ansible_architecture == 'x86_64' %}/opt/ocsp/apps/x86/telegraf-1.32.7{% elif ansible_architecture in ['aarch64', 'arm64'] %}/opt/ocsp/apps/telegraf-1.32.7{% else %}unknown_architecture{% endif %}"
# 4. 复制Telegraf到目标主机
- name: 复制Telegraf到目标主机
ansible.builtin.copy:
src: "{{ telegraf_source_path }}"
dest: /opt/ocsp/apps/
remote_src: no
force: yes
failed_when: telegraf_source_path == "unknown_architecture"
# 5. 设置telegraf可执行权限
- name: 设置telegraf可执行权限
ansible.builtin.file:
path: /opt/ocsp/apps/telegraf-1.32.7/telegraf
mode: "0755"
state: file
# 6. 验证目标主机telegraf文件
- name: 验证目标主机telegraf文件是否存在且可执行
ansible.builtin.stat:
path: /opt/ocsp/apps/telegraf-1.32.7/telegraf
get_checksum: no
get_mime: no
register: target_telegraf
failed_when: not target_telegraf.stat.exists or not target_telegraf.stat.executable
# 7. 安装ocsp-agent服务(使用正确的shell模块语法)
- name: 安装ocsp-agent服务
shell: /opt/ocsp/apps/telegraf-1.32.7/telegraf --service-name=ocsp-agent service install
register: install_result
ignore_errors: yes
# 8. 显示安装结果详情
- name: 显示安装结果详情
ansible.builtin.debug:
var: install_result
# 9. 检查服务是否安装成功
- name: 检查ocsp-agent服务文件
ansible.builtin.stat:
path: /etc/systemd/system/ocsp-agent.service
register: service_file
# 10. 启动ocsp-agent服务
- name: 启动ocsp-agent服务
ansible.builtin.systemd:
name: ocsp-agent
enabled: yes
state: started
register: service_status
ignore_errors: yes
# 11. 输出部署完成信息
- name: 输出部署完成信息
ansible.builtin.debug:
msg:
- "✅ 目标主机:{{ inventory_hostname }}(架构:{{ ansible_architecture }})"
- "📌 服务文件状态:{% if service_file.stat.exists %}已创建{% else %}未找到{% endif %}"
- "📌 服务运行状态:{% if service_status is succeeded %}已启动{% else %}启动失败{% endif %}"
- "💡 下一步:按文档登录服务端 http://11.111.1.111:18134/ 验证主机列表+39100端口"执行 Palybook 文件
1
2
3
4
5
6
7
8# 关闭 Python 接口告警信息提示
export ANSIBLE_PYTHON_INTERPRETER=/usr/bin/python
# 关闭 主机秘钥认真信息
export ANSIBLE_HOST_KEY_CHECKING=False
# 仅针对 YZJ 分组执行 Playbook
ansible-playbook -i ocsp.txt agent_deploy.yml -e "ansible_ssh_common_args='-o StrictHostKeyChecking=no'" --limit YZJ
