qhdx07
作者qhdx07·2022-05-12 11:32
系统架构师·as

Ansible设置远程环境变量问题

字数 1233阅读 874评论 1赞 0

一、问题背景

SSH远程执行脚本报错"command not found",且环境变量不生效,执行env命令后发现打印出来的环境变量少了很多。

原因是之前将环境变量配置在了/etc/profile中,但是SSH远程执行脚本时实际上执行的是non-login shell,而non-login shell不会读取/etc/profile配置文件。

二、关于login shell和non-login shell

简单来说,用SSH客户端(比如Putty)登陆Linux系统时,要求输入用户名/密码登录或根据SSH key登录时,就是login shell。

而在A机器上使用SSH免密码登录B机器,在B机器上执行Shell脚本,就是non-login shell。

用Ansible在目标机器上远程执行Shell脚本时,也是non-login shell,因为Ansible是基于SSH的。

Linux环境配置文件,以CentOS7为例:

/etc/profile

/etc/bashrc

~/.bash_profile

~/.bashrc

注意:~/.bash_profile引入了~/.bashrc,而~/.bashrc引入了/etc/bashrc,因此login shell可以读取到所有配置文件的环境变量

  1. /etc 下的是系统环境配置,对所有用户有效,但是/etc/profile只对login shell有效,而/etc/bashrc对login shell和non-login shell都有效。

2.~下的是当前用户环境配置,当前用户环境配置会继承/etc系统环境配置。

login shell加载环境变量的顺序:①/etc/profile ②~/.bash_profile ③~/.bashrc ④/etc/bashrc

nologin shell加载环境变量的顺序: ①/etc/bashrc ②~/.bashrc

三、解决non-login shell的环境配置问题

方法一:将login-shell和non-login shell都需要的环境配置放在~/.bashrc或/etc/bashrc中,其它配置放在~/.bash_profile或/etc/profile中。

方法二:如果环境配置只放在~/.bash_profile或/etc/profile中,需要执行non-login shell时先source ~/.bash_profile再执行命令。

方法三:更改ansible配置文件并添加hosts参数

①在ansible配置文件添加become_method=su,become_flags='-l' sudo对应的flag为-i 如果我登录的用户就是我希望用来执行命令的用户还需要设置become_allow_same_user=True

②在hosts里配置

ansible_become=true

ansible_become_user=

ansible_become_pass=

如果觉得我的文章对您有用,请点赞。您的支持将鼓励我继续创作!

0

添加新评论1 条评论

凉州-沙洲凉州-沙洲系统运维工程师IT中林
2022-06-21 11:50
ansible.cfg 配置 [privilege_escalation] bencome_method=sudo become_flags='-i' become_allow_same_user=True 正常加载环境变量。 谢谢楼主分享!刚好看到这个帖子,解决了我的问题,批量发布tomcat应用,启动后前台应用无法打开!
Ctrl+Enter 发表

作者其他文章

相关文章

相关问题

相关资料

X社区推广