Why it was slow
Two Ansible roles in my infrastructure tool, one that audits an AWS
account and one that remediates what the audit finds, were written
when not every service had a mature Ansible module. Where a module
was missing, the task shelled out to the aws CLI, usually with a
--query JMESPath expression to cut the JSON down, then
parsed stdout with from_json. That was reasonable at
the time, and it spread. By the time I counted, fourteen task files
held 61 command: and shell: tasks. Every
one was a process spawn and at least one API call, run serially. An
audit of one account took three to five minutes, and I audit
several.
An earlier pass over the whole repository had converted eight
shell-outs elsewhere and deferred these two roles on purpose, with
the note "heavy --query usage; separate effort". This
was the separate effort.
The recipe
I converted three files as a pilot, wrote down what the conversion looked like, then did the other eleven the same way. Five steps per shell-out.
1. Identify the API call. The cmd:
line reads aws SERVICE OPERATION ... --query '...'.
That is a service and an operation: s3api
get-bucket-encryption is S3 GetBucketEncryption,
cloudtrail describe-trails is CloudTrail DescribeTrails.
2. Find the module. amazon.aws first,
community.aws second. Reads usually have an
_info module. Look in the installed collections
directory on the machine that runs the role, not in documentation
or memory: a module can live in a different namespace than you
remember, and a module you remember can be missing. If nothing
exists, the shell-out stays, with a comment saying why.
3. Move the filter into Jinja. The module returns a structured result, so the JMESPath projection becomes a filter on the register.
JMESPath in --query | Jinja on the module result |
|---|---|
Reservations[].Instances[] | result.instances (most EC2 modules flatten already) |
[?State.Name=='running'] | | selectattr('state', 'equalto', 'running') |
[*].{name:Name} | | map(attribute='name') |
length(@) | | length |
4. Reshape the register. cmd.stdout |
from_json becomes result.<key>, and the
key varies per module, so check the actual return data.
cmd.rc goes away; the module handles failure. A check
on cmd.stderr becomes failed_when on a
module-specific key, or disappears because the module is
idempotent.
5. Keep guards only where the module is not idempotent.
A shell-out that creates a thing needs an "already exists" guard. A
module with state: present does not; the guard is dead
weight and a second place for a bug. Then run the changed tag
against a template account before merging, because the finding
tasks downstream compare the gathered data, and if the gather shape
changed they quietly do nothing.
One before and after
The account password policy remediation was one shell-out. In shape, the old task was this.
- name: Set account password policy
ansible.builtin.command:
cmd: >-
aws iam update-account-password-policy
--minimum-password-length {{ pw_min_length }}
--require-symbols --require-numbers
--require-uppercase-characters --require-lowercase-characters
--allow-users-to-change-password
--max-password-age {{ pw_max_age }}
--password-reuse-prevention {{ pw_reuse_prevent }}
register: pw_cmd
changed_when: pw_cmd.rc == 0
The new task is the module, with the same inputs under the module's names.
- name: Set account password policy
amazon.aws.iam_password_policy:
region: "{{ region }}"
state: present
min_pw_length: "{{ pw_min_length }}"
require_symbols: true
require_numbers: true
require_uppercase: true
require_lowercase: true
allow_pw_change: true
pw_max_age: "{{ pw_max_age }}"
pw_reuse_prevent: "{{ pw_reuse_prevent }}"
register: pw_policy
The argument names changed: min_pw_length,
pw_max_age, pw_reuse_prevent. The
module reports changed itself, so the summary task
reads pw_policy.changed instead of inferring it from a
return code.
Where the calls collapsed
The count went from 61 to 3. Some of that was one for one. More of it was collapse, because a module often returns in one call what the CLI needed several for.
- S3 audit: three calls per bucket (public access block, policy, encryption) became one
s3_bucket_infocall withbucket_factson. - CloudTrail audit: three calls became one
cloudtrail_info, which already returns the logging state, the KMS key, log file validation and the CloudWatch log group. - The two CloudTrail remediation files: eight and ten shell-outs became zero, and one
cloudtrail_inforesult is shared across three sub-tags instead of fetched three times. - Default security group: four calls became two module calls, and eighty lines became thirty-two.
- One shell-out turned out to be dead code that referenced a variable nothing defined. Deleted, not converted.
Net across sixteen files: about three hundred fewer lines. The three that remain have no module: the read of the IAM account password policy, and two Inspector v2 calls. Each carries a comment that says so.
Then read from the cache
Module conversion made the audit simpler and more correct. It did
not make it quick. The remaining time was API latency, serial, per
finding. The second half of the work was to stop asking the API
during an audit at all. My describe and list targets were already
cache-first: an inventory cache per account, kept hourly fresh, with
live=1 to bypass it. I extended the cache schema to
carry the fields the audit needs, added one task file that refreshes
the needed slices, reads the cache file and parses it into a fact,
and pointed every finding task at that fact. That is what moved the
audit from minutes to ten to thirty seconds. The modules were the
correctness change. The cache was the speed change, and it only
pays once the gather step produces structured data.
The module that did not exist
One of the three pilot files was the GuardDuty detector remediation.
I converted it to amazon.aws.guardduty_detector, wrote
"direct mapping, module is idempotent" in my notes, and merged it.
There is no such module in any installed collection. The target
failed with "couldn't resolve module/action" from that day on, and
because a remediation tag only runs when an audit finds something
for it to fix, the failure sat unnoticed for a while before a run
that needed it errored before it started.
It went back to command tasks, with a block comment at the top
saying not to try again, and a pointer to the two
other tasks in the role that carry the same note. Step two of my own
recipe says to list the installed modules directory rather than
trust memory. I wrote that step and skipped it once. The password
policy module taught the smaller version of the same lesson: I first
wrote it as community.aws, and it lives in
amazon.aws.
If you are holding a role like this
- Count the shell-outs first. The number is the argument.
- Pilot three, write the recipe, then do the rest. Do not improvise file by file.
- Verify every module name against the installed collections, by listing the directory.
- Expect return shapes to differ from the raw API:
idinstead ofvolume_id,attachment_setinstead ofattachments. Test against real return data. - Convert, then cache. The modules fix the code; the cache fixes the clock.