在 Chef-solo 部署 bash 脚本中检测主机操作系统发行版
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15660887/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Detect host operating system distro in chef-solo deploy bash script
提问by offwhite
When deploying a chef-solo setup you need to switch between using sudo or not eg:
在部署 Chef-solo 设置时,您需要在是否使用 sudo 之间切换,例如:
bash install.sh
and
和
sudo bash install.sh
Depending on the distro on the host server. How can this be automated?
取决于主机服务器上的发行版。这如何自动化?
回答by Litmus
ohai already populates these attributes and are readily available in your recipe for example,
ohai 已经填充了这些属性,并且可以在您的食谱中轻松获得,例如,
"platform": "centos",
"platform_version": "6.4",
"platform_family": "rhel",
you can reference to these as
你可以参考这些作为
if node[:platform_family].include?("rhel")
...
end
To see what other attributes ohai sets, just type
要查看 ohai 设置的其他属性,只需键入
ohai
on the command line.
在命令行上。
回答by offwhite
You can detect the distro on the remote host and deploy accordingly. in deploy.sh:
您可以检测远程主机上的发行版并进行相应的部署。在 deploy.sh 中:
DISTRO=`ssh -o 'StrictHostKeyChecking no' ${host} 'bash -s' < bootstrap.sh`
The DISTRO variable is populated by whatever is echoed by the bootstrap.sh script, which is run on the host machine. So we can now use bootstrap.sh to detect the distro or any other server settings we need to and echo, which will be bubbled to the local script and you can respond accordingly.
DISTRO 变量由 bootstrap.sh 脚本响应的任何内容填充,该脚本在主机上运行。所以我们现在可以使用 bootstrap.sh 来检测发行版或我们需要的任何其他服务器设置并回显,这将被冒泡到本地脚本,您可以做出相应的响应。
example deploy.sh:
示例部署.sh:
#!/bin/bash
# Usage: ./deploy.sh [host]
host=""
if [ -z "$host" ]; then
echo "Please provide a host - eg: ./deploy [email protected]"
exit 1
fi
echo "deploying to ${host}"
# The host key might change when we instantiate a new VM, so
# we remove (-R) the old host key from known_hosts
ssh-keygen -R "${host#*@}" 2> /dev/null
# rough test for what distro the server is on
DISTRO=`ssh -o 'StrictHostKeyChecking no' ${host} 'bash -s' < bootstrap.sh`
if [ "$DISTRO" == "FED" ]; then
echo "Detected a Fedora, RHEL, CentOS distro on host"
tar cjh . | ssh -o 'StrictHostKeyChecking no' "$host" '
rm -rf /tmp/chef &&
mkdir /tmp/chef &&
cd /tmp/chef &&
tar xj &&
bash install.sh'
elif [ "$DISTRO" == "DEB" ]; then
echo "Detected a Debian, Ubuntu distro on host"
tar cj . | ssh -o 'StrictHostKeyChecking no' "$host" '
sudo rm -rf ~/chef &&
mkdir ~/chef &&
cd ~/chef &&
tar xj &&
sudo bash install.sh'
fi
example bootstrap.sh:
示例 bootstrap.sh:
#!/bin/bash
# Fedora/RHEL/CentOS distro
if [ -f /etc/redhat-release ]; then
echo "FED"
# Debian/Ubuntu
elif [ -r /lib/lsb/init-functions ]; then
echo "DEB"
fi
This will allow you to detect the platform very early in the deploy process.
这将允许您在部署过程的早期检测平台。

