↓ Skip to main content

Ansible vs. a Rack of Stubborn UPS Cards

·1822 words·9 mins· loading · loading ·
Zach Le
Author
Zach Le
Transforming my server rack into a jet engine

I thought I knew Ansible
#

The last time Ansible showed up on this blog, I’d turned nine numbered bash scripts into a six-role playbook for the Palworld server. Every host in that project was a Linux box: Ansible logged in, ran its modules, and the box did what it was told.

This time, the targets were the APC Smart-UPS units on a corporate network, each with an AP9641 Network Management Card 3 (NMC3) in the back, the little card that gives a UPS its own web page, SSH login, and email alerts. Every new UPS came with the same manual checklist: accounts, DNS, NTP, time zone, daylight saving time, low battery duration, what to do when power comes back, a name, and CEIP turned off. Then firmware for both the card and the UPS. Fine to click through once, not fine for a rack.

The constraint that shaped everything: on a corporate network, nothing may be sent to outside services. That meant plain ansible-core plus pexpect, no Galaxy collections, nothing that phones home, passwords in an encrypted vault, and strict SSH host key checking, even on days when turning it off would have made everything “just work”.

Same arrangement as everything lately: I decide what it should do, Claude writes the playbooks, and I run them against real hardware and make the calls. The playbooks are public at github.com/zle3/apc-ups-ansible.

The card is not a computer
#

Normal Ansible modules run on the target and need Python there. The network card is an appliance with a menu-driven CLI and an apc> prompt, and it has no Python. Network gear usually gets around that with network_cli, but that needs a “cliconf” plugin for the device, and nobody has written one for APC.

So every task runs on the control machine (delegate_to: localhost) and drives the card’s SSH session with ansible.builtin.expect, which waits for text to appear and types a response. The read-only info task, trimmed:

- name: Run about / upsabout / alarmcount over SSH
  ansible.builtin.expect:
    command: "{{ nmc_ssh }}"
    responses:
      "(?i)password:": "{{ nmc_password }}"
      # Each time the prompt appears, send the next command in the list.
      "apc>":
        - about
        - upsabout
        - alarmcount
        - bye
    timeout: 30
  delegate_to: localhost
  register: nmc_cli          # save the result in a variable
  no_log: true               # task args contain the password; hide them
  changed_when: false        # reading only, so never report "changed"
  check_mode: false
  failed_when: nmc_cli.stdout is not search(nmc_closed_regex) or nmc_cli.stdout is search(nmc_error_regex)

That "apc>" key is written literally for a reason. The first version used a variable there, and the session sat at the prompt doing nothing, because Ansible templates values, but not dictionary keys. Expect was waiting for the literal text {{ prompt }} to show up, which, shockingly, the card never printed.

Exit codes that mean nothing
#

Part 4 of the Palworld series ended on “don’t trust a clean exit code.” I did not expect a device whose exit codes are wrong every single time, on purpose.

The card ends every SSH session with exit code 255, even a good one. A session killed by an expect timeout also exits 255. So success is judged from the output instead: it has to contain Connection to <ip> closed. and can’t contain any E1xx: codes, which is how the CLI reports a failed command. That’s the failed_when line above.

Backups had the same problem from a different angle. OpenSSH 9 and newer scp speaks SFTP by default, and the card only speaks classic SCP, so it needs scp -O. After that, the transfer completes, and the card’s scp exits 1 anyway. The fix was the same: look for 100% in the output, and check the file actually landed.

Two smaller safeguards came out of the same stretch. Every SSH command has -o NumberOfPasswordPrompts=1, so a wrong password fails once instead of retrying into a lockout. And tasks that send passwords use no_log: true, which also hides the error when they fail, so they register the output, print it with debug, and check it with assert.

Settings the CLI pretends don’t exist
#

DNS, NTP, and time zone have CLI commands, so those follow the pattern every playbook here uses: read the current value, compare it with the wanted one, change only the difference, and verify. On Palworld, modules like cron and ufw did that for me. With no modules, it’s done by hand, every time.

Then the CLI guide turned out to have no command for daylight saving time, or for low battery duration, shutdown behavior, the UPS name, or CEIP.

The way around it is config.ini. The card accepts an uploaded config.ini that holds only a few keys, and leaves everything else alone. With a UPS on the other end, that was not something to take on faith, so I tested it: set low battery duration to 8 by hand, ran the playbook, and watched it go back to 7. Then I diffed full backups from before and after. Only the intended keys had changed.

So the flow is: download the current config.ini, compare each setting with Ansible’s ini lookup, upload a small file with only the differences, wait 15 seconds, download again, and verify.

nmc_ini_settings:
  - {section: SmartUPS, key: UPSName, value: "{{ ups_name }}"}
  - {section: SmartUPS, key: LowBatteryDuration, value: "{{ ups_low_battery_minutes | string }}"}
  # ...
  - {section: SystemDate/Time, key: DSTConfiguration, value: "{{ nmc_dst_names[site_dst] }}"}
  # CEIP sends usage data to Schneider Electric. Must stay off.
  - {section: CEIP, key: Tracking, value: disabled}

That | string is there because, since Ansible 2.19, the variable renders as the integer 7, while the ini lookup returns the string "7", so they never compared equal, and the setting looked wrong on every run.

Backups before and after every change earned their keep early, too. One diff showed the NTP servers had changed from IP addresses to pool names, while the playbook’s apply step had been skipped both times. Most likely, it was changed in the web UI in between. Without two backups to compare, nobody would have known when.

Firmware, where the vendor disagrees with itself
#

The CLI guide only describes UPS firmware updates from a USB stick. A separate Schneider FAQ describes doing it over the network with upsfwupdate, so the playbook follows that one. The card firmware FAQ says the “only supported method” for NMC3 3.0 and newer is Schneider’s Secure NMC System (SNS) tool, but the 3.6.1.2 download itself ships a Windows updater that pushes the same .nmc3 file over FTP or SCP, and the release notes list no step requirement. A plain scp upload worked.

The download isn’t even a firmware file. It’s a zip, containing a self-extracting .exe, which is itself a zip, containing the .nmc3. Python’s zipfile opens both layers without running anything, so the playbook unpacks whatever vendor zip gets dropped in a folder, and never executes the middle layer.

By default, devices go to the newest firmware available. If a vendor ever requires a step upgrade, you list the in-between version as a “waypoint”, and it’s installed only when it sits between the current version and the target. Picking “newest” needed Ansible’s version test, because, as plain strings, '3.6.1.2' > '10.0' is true.

On Palworld, the rule was a disposable VM before the real server. A UPS card doesn’t come in a disposable version, so the equivalent was a set of Python scripts pretending to be one: a fake SSH CLI, a fake scp, and a fake firmware updater. It caught a real gap: the fake card couldn’t “reboot”, so the firmware test sat out its full 15-minute wait for SSH to come back, until a fake listener learned to drop for 5 seconds after an upload.

On real hardware, the card went from 2.5.3.3 to 3.6.1.2 in one step. The next task, reading the UPS, failed, because, after a reboot, the card needs a while before it talks to the UPS again. That read now retries for up to 5 minutes.

A light blue web UI banner titled “This is not the latest available firmware”, pointing to the Secure NMC System Tool and a subscription
The banner on an outdated card. Annoying, but a handy tell.

To know when new firmware exists, there’s no scraping vendor sites: Schneider Security Notifications announce it, and firmware.yml --check shows which devices are behind.

Trusting four cards at once
#

With four cards, running ssh and every playbook per card by hand stopped making sense, so three things got added: a playbook that trusts all SSH host keys at once, a check that names any card whose apc password differs from the vault, and a single onboard.yml that runs everything for new devices.

The bulk key scan immediately came back with nothing but a banner:

SSH-2.0-cryptlib

The cards offer a single ECDSA key, and their SSH server answers nothing at all when ssh-keyscan asks for several key types in one go. So the playbook asks for each type separately.

Verifying those keys is the part I like most. Every new card already starts at the serial console, because it has no IP address yet, and the card’s CLI has ssh key -f to print its own fingerprint. So the fingerprint gets recorded there, over a cable nobody can tamper with, and goes into the inventory as ssh_fingerprint. The playbook compares automatically: a match is trusted without a question, a mismatch stops that card, and a changed key on a known device is never replaced automatically.

The first fleet run
#

onboard.yml ran against all four units, in one command: trust keys, create accounts, apply settings, update firmware, take backups, and write a CSV of serial numbers, MAC addresses, and firmware for the asset system. No failures. It also found real drift on two cards that had been set up by hand:

What the playbook found What it should be
Eastern time zone Pacific
No DNS servers Site DNS servers
NTP off (one card’s clock was hours off and on the wrong date) NTP on, pool names
Low battery set to 2 minutes 7 minutes
Default UPS name Name from the inventory
DST off DST on

A third card still had the old NTP IP addresses. All four network cards went from 2.5.3.3 to 3.6.1.2, one at a time, and, after each reboot, the UPS read needed exactly one retry, which the retry logic handled. The UPS units were already on the newest firmware (02.0).

Where it landed
#

Very little of this was really about Ansible. It was about a device that’s difficult in small ways: exit codes that mean nothing, a CLI missing commands for half the checklist, vendor documents that disagree, and an SSH server that goes silent when you ask it two questions at once. Palworld showed me Ansible on hosts that cooperate. This one showed me what’s left when the host doesn’t: an inventory, a vault, a way to run things in order, and a lot of expect.

A new UPS now takes a short session at the serial console, an entry in the inventory, and one command.