Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 73 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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

Expand Down
56 changes: 56 additions & 0 deletions REFERENCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

### <a name="noderings"></a>`noderings`
Expand Down Expand Up @@ -550,3 +554,55 @@ Default value: `[]`
Seconds to wait for each operation to finish.

Default value: `900`

## Tasks

### <a name="resolve_reference"></a>`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.
1 change: 1 addition & 0 deletions bolt_plugin.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{}
147 changes: 147 additions & 0 deletions lib/puppet_x/noderings/bolt_inventory.rb
Original file line number Diff line number Diff line change
@@ -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
6 changes: 4 additions & 2 deletions metadata.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -64,6 +64,8 @@
"dns",
"dnssec",
"firewall",
"marketplace"
"marketplace",
"bolt",
"inventory"
]
}
Loading