diff --git a/README.md b/README.md index 86786f3..6ae60a5 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,9 @@ Manage [NodeRings](https://noderings.com) from OpenVox or Puppet: virtual machines ordered from the NodeRings marketplace, DNS zones and records (with -DNSSEC), firewall rulesets and SSH keys. +DNSSEC), firewall rulesets and SSH keys. The module is also a +[Bolt inventory plugin](#bolt-inventory-plugin) that turns your NodeRings VMs into +Bolt targets. New to it? The step-by-step guide [How to use Puppet and OpenVox on NodeRings to order a VPS](https://noderings.com/blog/puppet-vps) walks through a first run. @@ -202,9 +204,78 @@ ones in place and move them into order. `noderings_firewall_ruleset` resources it names, and `noderings_dns_record` requires its `noderings_dns_zone`. Every type requires the `noderings.yaml` file. +## Bolt inventory plugin + +The module is also a [Bolt](https://www.puppet.com/docs/bolt) inventory plugin. +It lists your NodeRings VMs as Bolt targets, so `bolt command run`, tasks and +plans reach every VM without a hand-written target list. New VMs show up the next +time Bolt reads the inventory. + +Add the module to your Bolt project: + +```shell +bolt module add noderings-noderings +``` + +Then reference the plugin in `inventory.yaml`: + +```yaml +groups: + - name: noderings + targets: + - _plugin: noderings + token: + _plugin: env_var + var: NODERINGS_TOKEN + config: + transport: ssh + ssh: + user: root + + # Only running VMs tagged web, with extra data as target vars. + - name: web + targets: + - _plugin: noderings + tags: [web] + target_mapping: + vars: + plan: plan_code + city: region_city +``` + +```shell +export NODERINGS_TOKEN=nr_... +bolt inventory show --targets noderings --detail +bolt command run 'uptime' --targets web +``` + +| Option | Default | Description | +|---|---|---| +| `token` | `NODERINGS_TOKEN` on the Bolt controller | API token. Read it with the `env_var` or a secret plugin rather than writing it into the inventory. | +| `api_url` | `https://api.noderings.com` | API URL | +| `organization_id` | the token's organization | Organization to list VMs from | +| `tags` | | Only VMs that have every one of these tags | +| `power_states` | `[running]` | Only VMs in these states, such as `running` or `stopped`; `[all]` for every VM | +| `name_pattern` | | Only VMs whose hostname matches this regular expression | +| `target_mapping` | `name: hostname`, `uri: ipv4` | Where each target field comes from (see below) | + +`target_mapping` takes the target fields `name`, `uri`, `alias` and `features` as +a VM field name, and `config`, `facts` and `vars` as a hash of VM field names, for +example `config: { ssh: { host: ipv6 } }`. A field can index into a list, such as +`tags.0`. The VM fields are `id`, `hostname`, `ipv4`, `ipv6`, `power_state`, +`distro`, `plan_code`, `plan_id`, `region_id`, `region_city`, `region_country`, +`provider_name`, `billing_type`, `firewall_ruleset_id`, `tags`, `cpus`, +`memory_mb`, `disk_mb` and `instant_app`. Every target also gets all of them +as the fact `noderings`, so plans can read `$target.facts['noderings']['region_city']`. +VMs that do not have an address yet are left out. + +The plugin runs on the Bolt controller and only reads the VM list. It never +changes anything in NodeRings. + ## Reference -See [REFERENCE.md](REFERENCE.md) for every type, parameter and property. +See [REFERENCE.md](REFERENCE.md) for every type, parameter and property, and the +plugin's `resolve_reference` task. ## Limitations diff --git a/REFERENCE.md b/REFERENCE.md index 77f9e33..7f7db61 100644 --- a/REFERENCE.md +++ b/REFERENCE.md @@ -16,6 +16,10 @@ * [`noderings_ssh_key`](#noderings_ssh_key): Manages an SSH public key stored in a NodeRings organization. `noderings_vm` installs stored keys on new virtual machines. * [`noderings_vm`](#noderings_vm): Manages a NodeRings virtual machine. When no VM has the hostname, Puppet orders the cheapest marketplace offer that matches `plan`, `country` +### Tasks + +* [`resolve_reference`](#resolve_reference): Bolt inventory plugin: lists NodeRings virtual machines as Bolt targets. Use it from inventory.yaml with _plugin: noderings. + ## Classes ### `noderings` @@ -550,3 +554,55 @@ Default value: `[]` Seconds to wait for each operation to finish. Default value: `900` + +## Tasks + +### `resolve_reference` + +Bolt inventory plugin: lists NodeRings virtual machines as Bolt targets. Use it from inventory.yaml with _plugin: noderings. + +**Supports noop?** false + +#### Parameters + +##### `token` + +Data type: `Optional[String[1]]` + +NodeRings API token. Defaults to the NODERINGS_TOKEN environment variable on the Bolt controller. + +##### `api_url` + +Data type: `Optional[String[1]]` + +NodeRings API URL. + +##### `organization_id` + +Data type: `Optional[String[1]]` + +Organization to list VMs from. Defaults to the token's organization. + +##### `tags` + +Data type: `Optional[Array[String[1]]]` + +Only VMs that have every one of these tags. + +##### `power_states` + +Data type: `Optional[Array[String[1]]]` + +Only VMs in these power states, such as running or stopped. Use [all] for every VM. Defaults to [running]. + +##### `name_pattern` + +Data type: `Optional[String[1]]` + +Only VMs whose hostname matches this regular expression. + +##### `target_mapping` + +Data type: `Optional[Hash]` + +Where each target field comes from: name, uri, alias, features take a VM field name; config, facts and vars take a hash of field names. Defaults to name: hostname, uri: ipv4. diff --git a/bolt_plugin.json b/bolt_plugin.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/bolt_plugin.json @@ -0,0 +1 @@ +{} diff --git a/lib/puppet_x/noderings/bolt_inventory.rb b/lib/puppet_x/noderings/bolt_inventory.rb new file mode 100644 index 0000000..bf3f0cd --- /dev/null +++ b/lib/puppet_x/noderings/bolt_inventory.rb @@ -0,0 +1,147 @@ +# frozen_string_literal: true + +# +# Copyright:: NodeRings +# License:: Apache-2.0 +# +# The Bolt inventory plugin: turns NodeRings virtual machines into Bolt +# targets. It runs inside the resolve_reference task, outside Puppet, so it +# only uses the plain-Ruby API client. + +require_relative 'client' +require_relative 'compute' + +module PuppetX + module Noderings + # Builds Bolt targets from the VMs of an organization. + module BoltInventory + # Where each target field comes from when target_mapping leaves it out. + DEFAULT_MAPPING = { 'name' => 'hostname', 'uri' => 'ipv4' }.freeze + TARGET_KEYS = %w[name uri alias config facts vars features].freeze + # The VM fields a mapping can refer to, also exposed as facts.noderings. + DATA_FIELDS = %w[ + id hostname ipv4 ipv6 power_state distro plan_code plan_id region_id region_city + region_country provider_name billing_type firewall_ruleset_id tags cpus memory_mb + disk_mb instant_app + ].freeze + + module_function + + # params are the task parameters: token, api_url, organization_id, + # tags, power_states, name_pattern, target_mapping. Returns the targets. + def resolve(params, env: ENV, transport: nil, sleeper: nil) + params = (params || {}).transform_keys(&:to_s) + token = first_present(params['token'], *TOKEN_ENV_VARS.map { |v| env[v] }) + unless token + raise UsageError, 'No NodeRings API token: set the token option of the noderings plugin ' \ + '(for example from the env_var plugin) or the NODERINGS_TOKEN environment variable.' + end + + client = Client.new( + token: token, + api_url: first_present(params['api_url'], env['NODERINGS_API_URL']), + organization_id: first_present(params['organization_id'], env['NODERINGS_ORGANIZATION_ID']), + user_agent: 'puppet-noderings-bolt-inventory', + transport: transport, sleeper: sleeper + ) + mapping = DEFAULT_MAPPING.merge(validate_mapping(params['target_mapping'] || {})) + filter = filters(params) + targets = client.list_virtual_machines.map { |machine| vm_data(machine) } + .select { |data| keep?(data, filter) } + .filter_map { |data| target(data, mapping) } + targets.sort_by { |t| [t['name'].to_s, t['uri'].to_s] } + end + + # The VM as the flat hash that mappings and facts.noderings use. + def vm_data(machine) + Compute.view(machine).merge( + 'region_city' => machine['regionCity'], + 'region_country' => machine['regionCountry'], + 'provider_name' => machine['providerName'], + 'cpus' => integer(machine['cpu']), + 'memory_mb' => integer(machine['memory']), + 'disk_mb' => integer(machine['storage']), + 'instant_app' => machine['instantAppSlug'].to_s.empty? ? nil : machine['instantAppSlug'], + ).slice(*DATA_FIELDS) + end + + def filters(params) + states = Array(params['power_states'] || ['running']).map { |s| s.to_s.downcase } + pattern = params['name_pattern'].to_s + { + tags: Array(params['tags']).map(&:to_s), + states: states.include?('all') ? nil : states, + pattern: pattern.empty? ? nil : Regexp.new(pattern), + } + rescue RegexpError => e + raise UsageError, "name_pattern is not a valid regular expression: #{e.message}" + end + + def keep?(data, filter) + return false if filter[:states] && !filter[:states].include?(data['power_state']) + return false unless (filter[:tags] - Array(data['tags'])).empty? + return false if filter[:pattern] && !filter[:pattern].match?(data['hostname'].to_s) + + true + end + + # One Bolt target, or nil when the mapped name and uri are both empty + # (a VM that has no address yet). + def target(data, mapping) + t = {} + mapping.each do |key, path| + value = %w[config facts vars].include?(key) ? map_tree(path, data) : lookup(data, path) + t[key] = value unless value.nil? || value == '' + end + return nil if t['uri'].nil? && t['name'].nil? + + t['name'] ||= t['uri'] + t['facts'] = { 'noderings' => data }.merge(t['facts'] || {}) + t + end + + # A nested hash of paths -> the same hash with values looked up. + def map_tree(tree, data) + tree.each_with_object({}) do |(k, v), out| + value = v.is_a?(Hash) ? map_tree(v, data) : lookup(data, v) + out[k] = value unless value.nil? + end + end + + # 'hostname' or 'tags.0' -> the value in data. + def lookup(data, path) + path.to_s.split('.').reduce(data) do |node, part| + case node + when Hash then node[part] + when Array then part.match?(%r{\A\d+\z}) ? node[part.to_i] : nil + end + end + end + + def validate_mapping(mapping) + raise UsageError, 'target_mapping must be a hash' unless mapping.is_a?(Hash) + + mapping = mapping.transform_keys(&:to_s) + unknown = mapping.keys - TARGET_KEYS + raise UsageError, "target_mapping has unknown keys: #{unknown.join(', ')} (allowed: #{TARGET_KEYS.join(', ')})" unless unknown.empty? + + bad = mapping.reject do |k, v| + %w[config facts vars].include?(k) ? v.is_a?(Hash) : v.is_a?(String) + end + raise UsageError, "target_mapping values must be field names, or hashes for config, facts and vars: #{bad.keys.join(', ')}" unless bad.empty? + + mapping + end + + def first_present(*values) + values.map { |v| v.to_s.strip }.find { |v| !v.empty? } + end + + def integer(value) + Integer(value.to_s, 10) + rescue ArgumentError + nil + end + end + end +end diff --git a/metadata.json b/metadata.json index 12f4ae7..679771a 100644 --- a/metadata.json +++ b/metadata.json @@ -2,7 +2,7 @@ "name": "noderings-noderings", "version": "0.2.0", "author": "NodeRings", - "summary": "Manage NodeRings virtual machines, DNS zones and records, firewall rulesets and SSH keys.", + "summary": "Manage NodeRings virtual machines, DNS zones and records, firewall rulesets and SSH keys, and list VMs as Bolt targets.", "license": "Apache-2.0", "source": "https://github.com/noderings/puppet-noderings", "project_page": "https://github.com/noderings/puppet-noderings", @@ -64,6 +64,8 @@ "dns", "dnssec", "firewall", - "marketplace" + "marketplace", + "bolt", + "inventory" ] } diff --git a/spec/unit/puppet_x/noderings/bolt_inventory_spec.rb b/spec/unit/puppet_x/noderings/bolt_inventory_spec.rb new file mode 100644 index 0000000..fb5c644 --- /dev/null +++ b/spec/unit/puppet_x/noderings/bolt_inventory_spec.rb @@ -0,0 +1,107 @@ +# frozen_string_literal: true + +require 'spec_helper' +require 'json' +require 'open3' +require 'tmpdir' +require_relative '../../../../lib/puppet_x/noderings/bolt_inventory' + +describe PuppetX::Noderings::BoltInventory do + def vm(id, hostname, ipv4, status: 'OPERATION_STATUS_STARTED', tags: [], **extra) + fake.vms[id] = { + 'id' => id, 'hostname' => hostname, 'ipv4' => ipv4, 'ipv6' => '2001:db8::1', + 'operationStatus' => status, 'tags' => tags, 'distro' => 'DISTRO_UBUNTU_24_04', + 'planCode' => 'SC-1C-1G', 'planId' => 'plan', 'regionId' => 'region', 'regionCity' => 'Ashburn', + 'regionCountry' => 'United States', 'providerName' => 'Acme', 'planBillingType' => 'BILLING_TYPE_USAGE', + 'cpu' => 1, 'memory' => '1024', 'storage' => 20_480, 'instantAppSlug' => '', + }.merge(extra) + end + + def resolve(params = {}, env = { 'NODERINGS_TOKEN' => 'test-token' }) + described_class.resolve(params, env: env, transport: fake, sleeper: ->(_s) {}) + end + + before do + vm('b', 'web-2', '203.0.113.2', tags: %w[web prod]) + vm('a', 'web-1', '203.0.113.1', tags: %w[web puppet-create-abc]) + vm('c', 'db-1', '203.0.113.3', status: 'OPERATION_STATUS_STOPPED', tags: ['db']) + vm('d', 'new-1', '', status: 'OPERATION_STATUS_PROVISIONING') + end + + it 'lists running VMs as targets named by hostname, sorted, with facts' do + targets = resolve + expect(targets.map { |t| [t['name'], t['uri']] }).to eq [%w[web-1 203.0.113.1], %w[web-2 203.0.113.2]] + facts = targets.first['facts']['noderings'] + expect(facts).to include( + 'id' => 'a', 'power_state' => 'running', 'distro' => 'ubuntu_24_04', 'region_city' => 'Ashburn', + 'provider_name' => 'Acme', 'cpus' => 1, 'memory_mb' => 1024, 'disk_mb' => 20_480, 'instant_app' => nil + ) + expect(facts['tags']).to eq ['web'] # the provider's internal create tag is hidden + end + + it 'filters by tags, power state and hostname' do + expect(resolve('tags' => %w[web prod]).map { |t| t['name'] }).to eq ['web-2'] + expect(resolve('power_states' => ['stopped']).map { |t| t['name'] }).to eq ['db-1'] + expect(resolve('power_states' => ['all']).map { |t| t['name'] }).to eq %w[db-1 new-1 web-1 web-2] + expect(resolve('name_pattern' => '^web-[2-9]$').map { |t| t['name'] }).to eq ['web-2'] + end + + it 'maps fields, including nested config, facts and vars' do + targets = resolve( + 'tags' => ['prod'], + 'target_mapping' => { + 'name' => 'id', 'uri' => 'ipv6', 'alias' => 'hostname', + 'config' => { 'ssh' => { 'host' => 'ipv4' } }, + 'vars' => { 'plan' => 'plan_code', 'first_tag' => 'tags.0', 'missing' => 'nope' }, + 'facts' => { 'city' => 'region_city' }, + }, + ) + expect(targets).to eq [{ + 'name' => 'b', 'uri' => '2001:db8::1', 'alias' => 'web-2', + 'config' => { 'ssh' => { 'host' => '203.0.113.2' } }, + 'vars' => { 'plan' => 'SC-1C-1G', 'first_tag' => 'prod' }, + 'facts' => { 'noderings' => targets.first['facts']['noderings'], 'city' => 'Ashburn' }, + }] + end + + it 'leaves out VMs without an address, and names by uri when the name is empty' do + targets = resolve('power_states' => ['all'], 'target_mapping' => { 'name' => 'instant_app' }) + expect(targets.map { |t| t['name'] }).to eq %w[203.0.113.1 203.0.113.2 203.0.113.3] + end + + it 'uses the token, API URL and organization from params before the environment' do + resolve({ 'token' => 'param-token', 'organization_id' => 'org-1' }, {}) + call = fake.calls.last + expect(call.inspect).to include('param-token').and include('org-1') + end + + it 'explains a missing token and bad options' do + expect { resolve({}, {}) }.to raise_error(PuppetX::Noderings::UsageError, %r{NODERINGS_TOKEN}) + expect { resolve('target_mapping' => { 'host' => 'ipv4' }) }.to raise_error(PuppetX::Noderings::UsageError, %r{unknown keys: host}) + expect { resolve('target_mapping' => { 'vars' => 'plan_code' }) }.to raise_error(PuppetX::Noderings::UsageError, %r{vars}) + expect { resolve('name_pattern' => '(') }.to raise_error(PuppetX::Noderings::UsageError, %r{regular expression}) + end + + describe 'the resolve_reference task' do + let(:root) { File.expand_path('../../../..', __dir__) } + + it 'loads its files from the Bolt install dir and reports errors the Bolt way' do + Dir.mktmpdir do |dir| + File.symlink(root, File.join(dir, 'noderings')) + env = ENV.to_h.reject { |k, _| PuppetX::Noderings::TOKEN_ENV_VARS.include?(k) } + out, status = Open3.capture2(env, 'ruby', File.join(root, 'tasks/resolve_reference.rb'), + stdin_data: { _installdir: dir }.to_json, unsetenv_others: true) + expect(status.exitstatus).to eq 1 + expect(JSON.parse(out)['_error']).to include('kind' => 'noderings/inventory-error', 'msg' => %r{No NodeRings API token}) + end + end + + it 'has metadata that lists every file it loads' do + meta = JSON.parse(File.read(File.join(root, 'tasks/resolve_reference.json'))) + files = meta['files'].map { |f| f.delete_prefix('noderings/') } + expect(files).to all(satisfy { |f| File.exist?(File.join(root, f)) }) + expect(files).to include('lib/puppet_x/noderings/bolt_inventory.rb', 'lib/puppet_x/noderings/client.rb', 'lib/puppet_x/noderings/compute.rb') + expect(meta['parameters']['token']['sensitive']).to be true + end + end +end diff --git a/tasks/resolve_reference.json b/tasks/resolve_reference.json new file mode 100644 index 0000000..7dd1a57 --- /dev/null +++ b/tasks/resolve_reference.json @@ -0,0 +1,41 @@ +{ + "description": "Bolt inventory plugin: lists NodeRings virtual machines as Bolt targets. Use it from inventory.yaml with _plugin: noderings.", + "input_method": "stdin", + "private": true, + "files": [ + "noderings/lib/puppet_x/noderings/client.rb", + "noderings/lib/puppet_x/noderings/compute.rb", + "noderings/lib/puppet_x/noderings/bolt_inventory.rb" + ], + "parameters": { + "token": { + "description": "NodeRings API token. Defaults to the NODERINGS_TOKEN environment variable on the Bolt controller.", + "type": "Optional[String[1]]", + "sensitive": true + }, + "api_url": { + "description": "NodeRings API URL.", + "type": "Optional[String[1]]" + }, + "organization_id": { + "description": "Organization to list VMs from. Defaults to the token's organization.", + "type": "Optional[String[1]]" + }, + "tags": { + "description": "Only VMs that have every one of these tags.", + "type": "Optional[Array[String[1]]]" + }, + "power_states": { + "description": "Only VMs in these power states, such as running or stopped. Use [all] for every VM. Defaults to [running].", + "type": "Optional[Array[String[1]]]" + }, + "name_pattern": { + "description": "Only VMs whose hostname matches this regular expression.", + "type": "Optional[String[1]]" + }, + "target_mapping": { + "description": "Where each target field comes from: name, uri, alias, features take a VM field name; config, facts and vars take a hash of field names. Defaults to name: hostname, uri: ipv4.", + "type": "Optional[Hash]" + } + } +} diff --git a/tasks/resolve_reference.rb b/tasks/resolve_reference.rb new file mode 100755 index 0000000..e67984a --- /dev/null +++ b/tasks/resolve_reference.rb @@ -0,0 +1,20 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# Bolt inventory plugin task: prints the NodeRings VMs as Bolt targets. +# Bolt runs it on the controller with the plugin's options as parameters. + +require 'json' + +input = $stdin.read.to_s +params = JSON.parse(input.strip.empty? ? '{}' : input) +lib = File.join(params.fetch('_installdir'), 'noderings', 'lib', 'puppet_x', 'noderings') +require File.join(lib, 'bolt_inventory') + +begin + targets = PuppetX::Noderings::BoltInventory.resolve(params) + puts({ value: targets }.to_json) +rescue PuppetX::Noderings::UsageError, PuppetX::Noderings::APIError, *PuppetX::Noderings::CONNECTION_ERRORS => e + puts({ _error: { msg: e.message, kind: 'noderings/inventory-error', details: {} } }.to_json) + exit 1 +end