
准备工作
- centos7的机器一台,本地安装的虚拟机或者其他 云主机
- centos7机器上已经成功安装ansible
- ansible的host中配置好分组为test的所有机器
- golang安装包,版本是golang1.12.1,这个可以自行选择
编写playbook脚本install_golang.yml
--- - hosts: test vars: url: ' tasks: - name: 下载golang安装包 get_url: url: "{{url}}" dest: "/tmp/golang.tar.gz" - name: install the golang shell: cd /tmp && tar xzf /tmp/golang.tar.gz && mv go /usr/local/ - name: mkdir gopath shell: cd /usr/local/ && mkdir gopath - name: set GOROOT environment lineinfile: dest=/etc/profile regexp="^export GOROOT=" line="export GOROOT=/usr/local/go" - name: set GOPATH environment lineinfile: dest=/etc/profile regexp="^export GOPATH=" line="export GOPATH=/usr/local/gopath" - name: set PATH environment lineinfile: dest=/etc/ profile regexp="^PATH=\$PATH:\$GOPATH" line="export PATH=$PATH:$GOPATH/bin:$GOROOT/bin" - name: source profile shell: sou rc e /etc/profile

执行脚本
执行命令:ansible-playbook install_golang.yml
执行没有错误说明自动化脚本安装成功
验证安装是否成功
# ansible -m shell -a "go version" test
localhost | SUCCESS | rc=0 >>
go version go1.12.1 linux/amd64
成功显示golang的版本信息说明成功安装
关于login shell 与 non-login shell
如果验证命令执行出现下面的错误信息,是ansible登录时的 环境变量 问题导致的
# ansible -m shell -a "go version" test localhost | FAILED | rc=127 >> /bin/sh: go: command not foundnon-zero return code
一般 ssh 用户登录执行的是login shell,会加载/etc/profile和~/.bash_profile;
ansible这类ssh远程执行是non-login shell,不会加载etc/profile和~/.bash_profile,而是回去加载/etc/bashrc和~/.bashrc,所以之前的脚本会出现找不到go命令错误,要让ansible的脚本可以找到go命令,需要在脚本install_golang.yml最后加上下面几行代码
- name: set GOROOT environment lineinfile: dest=/etc/bashrc regexp="^export GOROOT=" line="export GOROOT=/usr/local/go" - name: set GOPATH environment lineinfile: dest=/etc/bashrc regexp="^export GOPATH=" line="export GOPATH=/usr/local/gopath" - name: set PATH environment lineinfile: dest=/etc/bashrc regexp="^PATH=\$PATH:\$GOPATH" line="export PATH=$PATH:$GOPATH/bin:$GOROOT/bin" - name: source /etc/bashrc shell: source /etc/profile
如果还有问题可以私信给我,大家一起交流。