我正在使用 packer 在 aws 上构建 ami,在提供 ami 之后,我正在使用 serverspec 测试映像,但是测试 nginx 失败,这是测试
cat test/spec/localhost/nginx_spec.rb 2.4.2
require 'spec_helper'
describe package('nginx'), :if => os[:family] == 'redhat' do
it { should be_installed }
end
describe service('nginx'), :if => os[:family] == 'redhat' do
it { should be_enabled }
it { should be_running }
end
describe port(80) do
it { should be_listening }
end
这是输出
amazon-ebs: Port "80"
amazon-ebs: should be listening (FAILED - 1)
amazon-ebs:
amazon-ebs: Failures:
amazon-ebs:
amazon-ebs: 1) Port "80" should be listening
amazon-ebs: On host `localhost'
amazon-ebs: Failure/Error: it { should be_listening }
amazon-ebs: expected Port "80" to be listening
amazon-ebs: /bin/sh -c ss\ -tunl\ \|\ grep\ --\ :80\\\
amazon-ebs:
amazon-ebs: # ./spec/localhost/nginx_spec.rb:13:in `block (2 levels) in <top (required)>'
amazon-ebs:
amazon-ebs: Finished in 0.0683 seconds (files took 0.36256 seconds to load)
amazon-ebs: 4 examples, 1 failure
amazon-ebs:
amazon-ebs: Failed examples:
amazon-ebs:
amazon-ebs: rspec ./spec/localhost/nginx_spec.rb:13 # Port "80" should be listening
现在我在打包程序上添加了 ss 来检查 nginx 是否正在监听
{
"type": "shell",
"inline": ["cd /tmp/test", "/sbin/ss -tlenp | grep :80", "rake"]
}
输出:
==> amazon-ebs: Provisioning with shell script: /var/folders/d1/wm78jkb141lgjt9xn8x02dd5m7khx2/T/packer-shell407127288
amazon-ebs: LISTEN 0 128 *:80 *:* ino:32776 sk:ffff880033844d80 <->
amazon-ebs: LISTEN 0 128 *:80 *:* ino:32775 sk:ffff880033845d00 <->
servespec 测试失败,但 nginx 正在监听端口 80
答案1
问题是 ss 命令在路径下,如果测试使用 sh -c并且/sbin
没有/sbin
PATH
PATH 中没有 sbin
export PATH=/usr/bin:/root/bin:/usr/local/bin
cd /root/test
rake
Package "nginx"
should be installed
Service "nginx"
should be enabled
should be running
Port "80"
should be listening (FAILED - 1)
Failures:
1) Port "80" should be listening
On host `localhost'
Failure/Error: it { should be_listening }
expected Port "80" to be listening
/bin/sh -c ss\ -tunl\ \|\ grep\ --\ :80\\\
# ./spec/localhost/nginx_spec.rb:13:in `block (2 levels) in <top (required)>'
Finished in 0.08334 seconds (files took 0.34911 seconds to load)
4 examples, 1 failure
Failed examples:
rspec ./spec/localhost/nginx_spec.rb:13 # Port "80" should be listening
将 sbin 添加到 PATH 中
export PATH=/usr/bin:/root/bin:/usr/local/bin:/sbin
rake
cd /root/test
Package "nginx"
should be installed
Service "nginx"
should be enabled
should be running
Port "80"
should be listening
Finished in 0.06054 seconds (files took 0.33548 seconds to load)
4 examples, 0 failures
在我的单元测试中设置 PATH
echo "set :path, '/sbin:/usr/sbin:\$PATH'" >> spec/spec_helper.rb