Serverspec Documentation

repository·master·Indexed 25 days ago

https://github.com/mizzy/serverspec

An RSpec-based testing framework for verifying the state of remote servers. It provides resource types to test file system properties, network interfaces, running processes, and command output. It includes specialized support for Windows IIS Application Pools and websites, Linux audit systems, and integration with Vagrant for SSH backend configuration. The framework includes a setup wizard via Serverspec::Setup and a CLI tool called serverspec-init for scaffolding test suites.

Tokens
3.9K
Snippets
2
Records
32
Agent score
81%

What's inside Serverspec

  1. Configure WinRM backend for Windows

    master

    For Windows testing using the winrm backend, the generated spec_helper.rb requires specific credentials and endpoint configuration.

    Note that the setup template uses placeholders for <username> and <password> which must be updated in the resulting spec/spec_helper.rb. The endpoint is typically constructed as http://<TARGET_HOST>:5985/wsman.

    # Example of the WinRM configuration logic generated in spec_helper.rb
    user = <username>
    pass = <password>
    endpoint = "http://#{ENV['TARGET_HOST']}:5985/wsman"
    
    opts = {
      user: user,
      password: pass,
      endpoint: endpoint,
      operation_timeout: 300,
      no_ssl_peer_verification: false,
    }
    
    winrm = ::WinRM::Connection.new(opts)
    Specinfra.configuration.winrm = winrm
  2. Configure SSH backend with Vagrant

    master

    When setting up a UN*X environment with an ssh backend, Serverspec::Setup can integrate with Vagrant. If you choose to use a Vagrant instance, the generated spec_helper.rb will:

    1. Run vagrant up <host> to ensure the machine is running.
    2. Use vagrant ssh-config <host> to extract connection details.
    3. Automatically configure Net::SSH options using the extracted configuration.

    This allows you to run tests against virtual machines managed by Vagrant without manually managing SSH keys or hostnames.

    # Example of how the generated spec_helper.rb handles Vagrant
    `vagrant up #{host}`
    
    config = Tempfile.new('', Dir.tmpdir)
    config.write(`vagrant ssh-config #{host}`)
    config.close
    
    options = Net::SSH::Config.for(host, [config.path])
    set :host,        options[:host_name] || host
    set :ssh_options, options
  3. Initialize a new Serverspec test suite with serverspec-init

    master
    Use the serverspec-init CLI tool to scaffold a new Serverspec test suite. This command sets up the necessary directory structure and configuration files required to begin writing infrastructure tests with Serverspec.
  4. Initialize a Serverspec test environment

    master

    You can use Serverspec::Setup.run to programmatically trigger an interactive setup wizard. This wizard configures your testing environment by prompting for:

    1. OS Type: UN*X or Windows.
    2. Backend Type:
      • For UN*X: ssh or exec (local).
      • For Windows: winrm or cmd (local).
    3. Target Host:
      • If using ssh, you can specify a Vagrant instance. If Vagrant is detected, the setup can auto-configure using your Vagrantfile.
      • Otherwise, you provide a target hostname.

    Upon completion, the setup utility generates the following files and directories:

    • spec/ and spec/<hostname>/ directories.
    • spec/<hostname>/sample_spec.rb: A template spec file containing example package and service tests.
    • spec/spec_helper.rb: A configuration file tailored to your selected OS and backend.
    • Rakefile: A file to run tests for different targets using rake.
    • .rspec: RSpec configuration for colorized documentation output.
  5. Configure the target host via TARGET_HOST

    master
    Serverspec uses the TARGET_HOST environment variable to identify which host a test failure occurred on. If TARGET_HOST is not set, it falls back to Specinfra.configuration.host. When a test fails, Serverspec will include this host information in the failure output (e.g., On host 'hostname').
  6. Run Serverspec tests via Rake

    master

    The Serverspec::Setup utility generates a Rakefile that allows you to run tests for specific target hosts. The Rakefile defines a spec namespace with tasks for each directory found in spec/*.

    To run all tests, use:

    rake spec:all

    To run tests for a specific host (e.g., a host named my-server), use:

    rake spec:my-server

    Each task sets the ENV['TARGET_HOST'] environment variable, which the spec_helper.rb uses to determine the connection target.

  7. Inspect command output with the Command resource type

    master

    The Serverspec::Type::Command class provides methods to inspect the results of a command execution, including its standard output, standard error, and exit status. This is useful for verifying that a command ran successfully and produced the expected output.

    Key methods available:

    • stdout: Returns the standard output of the command as a string.
    • stdout_as_json: Parses the standard output as JSON and returns the resulting object. This requires the multi_json gem to be available.
    • stderr: Returns the standard error of the command as a string.
    • exit_status: Returns the exit status of the command as an integer.
  8. Verify file content and parse it as JSON or YAML

    master

    The File resource allows you to inspect the content of a file and parse it directly into structured data formats.

    • content: Returns the raw string content of the file.
    • content_as_json: Parses the file content as JSON using MultiJson.
    • content_as_yaml: Parses the file content as YAML.

    This is useful for testing configuration files where you need to verify specific keys or values within a structured format.

  9. Verify X.509 certificate validity and purpose

    master

    Use these methods to perform assertions on the temporal validity and intended use of a certificate:

    • certificate?: Returns true if the file is a valid X.509 certificate.
    • valid?: Returns true if the current time is between the certificate's notBefore and notAfter dates.
    • validity_in_days: Returns the number of days remaining until the certificate expires. Returns 0 if the command fails.
    • has_purpose?(p): Returns true if the certificate is valid for the specified purpose p (e.g., sslclient, sslserver).
  10. Test running processes with the `process` resource type

    master

    The process resource type allows you to verify the state, ownership, and count of running processes on a system. You can check if a process is running, identify its owner (user/group), and verify the number of instances currently active.

    Available methods include:

    • running?: Returns true if the process is currently running, false otherwise.
    • user: Returns the username of the process owner.
    • group: Returns the group name of the process owner.
    • count: Returns the integer number of running instances of the process.
    • Dynamic attributes: You can call get_column(keyword) via method_missing to retrieve other process attributes (e.g., cmdline, etime) if the underlying runner supports them.
  11. Use the be_listening matcher for network ports

    master

    The be_listening matcher (implemented via the Serverspec::Type::Port class) allows you to verify if a specific network port is listening on a given protocol and local address.

    Supported protocols include:

    • udp
    • tcp
    • tcp6
    • udp6

    When using the matcher, you can optionally specify the protocol and the local IP address (IPv4 or IPv6). If an invalid protocol is provided, an ArgumentError is raised. If an invalid IP address is provided, an ArgumentError is raised stating that the matcher requires a valid IPv4 or IPv6 address.

  12. Check file access for specific users

    master

    The readable?, writable?, and executable? methods can be used to check if a specific user has access to a file, rather than just checking the general permission bits.

    To check access for a specific user, pass the username as the by_user argument. If by_user is provided, the method checks if that specific user can perform the action (read, write, or execute).