当前位置:网站首页>【ansible问题处理】远程执行用户环境变量加载问题
【ansible问题处理】远程执行用户环境变量加载问题
2022-06-24 13:03:00 【一边学习一边哭】
问题现象
使用ansible命令行执行远程命令
使用command模块,出现报错:[Errno 2] No such file or directory
一样的命令换shell模块,出现报错:/bin/sh: ifconfig: command not foundnon-zero return code
问题原因
通过shell模块的报错可以很清晰的发现,是执行过程中找不到命令。
所以问题原因变得清晰,远程执行过程中环境变量加载不全的问题,导致有些命令找不到。
为什么会导致环境变量加载不全?
ansible命令行远程执行命令时,实际上执行的是non-login shell,non-login shell只会加载~/.bashrc、/etc/bashrc两个文件
关于login shell和non-login shell 加载配置文件
login shell加载环境变量顺序:/etc/profile --> ~/.bash_profile --> ~/.bashrc --> /etc/bashrc
non-login shell加载环境变量顺序:~/.bashrc --> /etc/bashrc
问题解决
*方法一:修改ansible配置文件
修改ansible.cfg配置文件,切换用户实现login shell,加载环境变量。这种方法比较合适,修改ansible参数,对于其他使用ansible的用户是无感的。
[privilege_escalation]
become=True
become_method=sudo
become_user=root
#become_ask_pass=False
become_flags='-i'become=True(必须),开启切换用户。ansible命令行选项对应 --become 或 -b
become_method 支持sudo 或者 su,如果使用su切换用户,become_flags需要改成 '-' 或 '-l'。ansible命令行选项对应 --become-method
become_user 填写需要切换的用户。ansible命令行选项对应 --become-user
become_flags sudo或者su命令的选项。ansible命令行没有对应选项,必须要写入ansible.cfg配置文件。
方法二:手动加载环境变量
方法2.1:
可以选择在执行命令或者脚本之前,先执行 source /etc/profile。但是这种方法每次执行的时候都需要先手动加载环境变量
方法2.2:
在远程机器执行 echo "source /etc/profile" >> /etc/bashrc ,这个方法一劳永逸,但是需要远程机器执行一次。
方法三:命令使用绝对路径
这种方法是最笨的。既然只是获取不到环境变量而已,那么只需要每次用到命令的时候,都输入命令的绝对路径就好了。
如果你只是临时解决一下问题,也不想折腾上面两种方法,可以先使用绝对路径解决。
边栏推荐
- 返回新列表
- AutoRF:从单视角观察中学习3D物体辐射场(CVPR 2022)
- Maximum path sum in binary tree [handle any subtree, then handle the whole tree]
- Go语言三个高效编程的技巧
- Rasa 3. X learning series - it is a great honor to be a source code contributor of Rasa contributors, and to build and share the rasa community with rasa source code contributors all over the world!
- Linux 安装 CenOS7 MySQL - 8.0.26
- English writing of Mathematics -- Basic Chinese and English vocabulary (common vocabulary of geometry and trigonometry)
- Unit contour creation method
- SAP Marketing Cloud 功能概述(四)
- 港股上市公司公告 API 数据接口
猜你喜欢
随机推荐
Generate binary tree according to preorder & inorder traversal [partition / generation / splicing of left subtree | root | right subtree]
c语言---18 函数(自定义函数)
Common singleton mode & simple factory
The difference between V-IF and v-show
OpenHarmony 1
HarmonyOS.2
PgSQL queries the largest or smallest data of a field in a group
JS remove string spaces
A review of text contrastive learning
鲲鹏arm服务器编译安装PaddlePaddle
10_那些格调很高的个性签名
Linux 安装 CenOS7 MySQL - 8.0.26
AutoRF:从单视角观察中学习3D物体辐射场(CVPR 2022)
Can a team do both projects and products?
Unity 热力图建立方法
Simulated 100 questions and answers of fluorination process examination in 2022
Online text entity extraction capability helps applications analyze massive text data
21set classic case
js去除字符串空格
Télétravail: Camping à la maison gadgets de bureau | rédaction communautaire

![Jerry's serial port receiving IO needs to set the digital function [chapter]](/img/04/48e7da42101a53827463d479952f67.png)
![[untitled]](/img/6c/df2ebb3e39d1e47b8dd74cfdddbb06.gif)






