使用ansible安装golang

本文主要讲述如何使用Ansible在Redhat Linux系列上安装golang 19。

关于Ansible的基本概念可以参考运维自动化之Ansible

1. 安装Ansible

安装Ansible参考安装ansible | 鹏叔的技术博客

2. 编写Ansible Playbook

如果远程主机非root用户,需要准备一个ansible.cfg文件用于覆盖ansible默认配置,
也可以直接修改/etc/ansible/ansible.cfg

1
2
3
4
5
6
7
8
9
10
11
# vi ansible.cfg
[defaults]
# replace the user with actual user on controlled node
remote_user = user_name_on_managed_host

[privilege_escalation]
become = True
become_method = sudo
become_user = root
become_ask_pass = False

vi install_golang.yaml

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
---
- name: Install golang
hosts: all
become: yes
vars:
- golang_download_url: https://studygolang.com/dl/golang/go1.19.3.linux-amd64.tar.gz
env_file: /etc/profile

tasks:
- name: Unzip the downloaded file
unarchive:
src: "{{ golang_download_url }}"
dest: /usr/local
remote_src: yes

- name: Set Golang environment variables
lineinfile: dest={{ env_file }} insertafter={{ item.position }} line={{ item.value }} state=present
with_items:
- {position: EOF, value: "export GOPROXY=https://goproxy.cn,direct"}
- {position: EOF, value: "export PATH=$PATH:/usr/local/go/bin"}
notify: Reload profile

handlers:
- name: Reload profile
shell: source {{ env_file }}

3. 执行Ansible Playbook

1
ansible-playbook install_golang.yaml

4. 参考文档

分享Ansible批量安装golang环境

Linux System Roles