2

我正在使用 Terraform 自动构建基于 AWS EC2 的 docker 主机,然后使用其远程 exec 选项下载 docker 文件,构建并运行它。

我希望将其与 Serverspec 集成,但我正在努力解决两件事:

  1. 将新创建的 AWS EC2 实例的外部 dns 传递给 Serverspec 的最佳方式。

  2. 如何为 Serverspec 配置 SSH 选项,以便它使用 ec2-user 账户在 Amazon Linux AMI 上正确执行。

我通常会使用预定义的密钥对连接到 EC2 实例,并且从不使用密码,但是 ServerSpec 似乎使用 sudo -p 格式在服务器上运行命令。

非常感谢任何建议。

spec_helper.rb 的内容

require 'serverspec'
require 'net/ssh'

set :ssh_options, :user => 'ec2-user'

还使用如下编辑的 rakefile 来强制纠正 EC2 外部 dns(屏蔽):

require 'rake'
require 'rspec/core/rake_task'

hosts = %w(
  ec2-nn-nn-nn-nnn.eu-west-1.compute.amazonaws.com
)

set :ssh_options, :user => 'ec2-user'

task :spec => 'spec:all'

namespace :spec do
  task :all => hosts.map {|h| 'spec:' + h.split('.')[0] }
  hosts.each do |host|
    short_name = host.split('.')[0]
    role       = short_name.match(/[^0-9]+/)[0]

    desc "Run serverspec to #{host}"
    RSpec::Core::RakeTask.new(short_name) do |t|
      ENV['TARGET_HOST'] = host
      t.pattern = "spec/Nexus/*_spec.rb"
    end
  end
end
4

1 回答 1

1
  1. You could make the IP address an output in Terraform. In fact, the link gives an example doing just that to get the IP address of an AWS instance, named web in this case:

    output "address" {
        value = "${aws_instance.web.public_dns}"
    }
    

    Then you can get this value from the command line after a terraform apply with terraform output address.

  2. You can set the sudo password with the config option :sudo_password. If the ec2-user can run sudo without a password, set this to ''. (See this blog post for an example.) Or pass it in the SUDO_PASSWORD environment variable, described here: http://serverspec.org/tutorial.html

于 2016-06-16T02:33:18.480 回答