diff --git a/docs/3._Knowledge_Center/02_explanations/04_rundeck.md b/docs/3._Knowledge_Center/02_explanations/04_rundeck.md index 4eb764ab..6f3b87a8 100644 --- a/docs/3._Knowledge_Center/02_explanations/04_rundeck.md +++ b/docs/3._Knowledge_Center/02_explanations/04_rundeck.md @@ -67,7 +67,7 @@ Some actions also do work on cas-ansible-00 itself. `ioc.install` and `ioc.migra ## What can be run -Only the catalogued actions can be run. No `cas` code path accepts a playbook path or an ad-hoc command, and Rundeck denies ad-hoc execution. To add an action, you add a playbook and a catalogue entry, both reviewed in `cas_infrastructure`. +Only the catalogued actions can be run. No `cas` code path accepts a playbook path or an ad-hoc command, and Rundeck denies ad-hoc execution. To add an action, you add a playbook and a catalogue entry, both reviewed in `cas_infrastructure`. How to write, test and add one is in [How-To: Use Ansible](../03_how_to/17_ansible.md). | Action | What it does | Destructive | Check mode | |---|---|---|---| diff --git a/docs/3._Knowledge_Center/03_how_to/17_ansible.md b/docs/3._Knowledge_Center/03_how_to/17_ansible.md new file mode 100644 index 00000000..9da8c59c --- /dev/null +++ b/docs/3._Knowledge_Center/03_how_to/17_ansible.md @@ -0,0 +1,261 @@ +--- +title: Use Ansible +tags: + - SLS + - PROSCAN + - SwissFEL + - HIPA +--- + +# How-To: Use Ansible + +To automate a task you keep doing by hand on several Controls machines, write it as an Ansible playbook, keep it in Git, and test it with check mode on one test host. Once reviewed, it becomes an action in the catalogue and lives in [Rundeck](../02_explanations/04_rundeck.md): it runs from one place, with access control and a record of every run. + +![From a playbook to a Rundeck job: write the playbook in Git, test it with ansible-playbook --check --diff on one test host, review it in a pull request in cas_infrastructure, add a catalogue entry, configure_rundeck.yml imports the job cas/ on cas-ansible-00, and cas run starts it on the hosts as cas-ansible, recorded in the execution history](images/17_ansible_path.svg) + +## What is in place and what is planned + +| | Today | Planned | +|---|---|---| +| Write and test | Ansible is installed on the LC machines and the Controls consoles; you run playbooks as yourself | | +| Catalogue | `catalog.yaml` in `cas_infrastructure`, 11 actions; a new action is a pull request reviewed by Controls IT | A staging and canary step for catalogue changes | +| Into Rundeck | Whoever merges runs `configure_rundeck.yml` by hand | A merge pipeline that imports the jobs | +| Who runs actions | Controls IT, through `cas` on cas-ansible-00 | One pilot expert group, then all expert groups, on their own hosts, with their Kerberos login | +| Login on the hosts | One shared account, `cas-ansible`, on hosts with the Puppet class `cas_access` | Per-user SSH certificates | + +## Ansible or Puppet? + +Ansible on Controls machines is for operations that act **now**. The configuration of a machine is Puppet's job. + +| You want to | Use | +|---|---| +| Restart, deploy, register, check, report something now | An Ansible playbook, then a catalogue action | +| Install or remove a package, add a mount, give someone power-user rights | A pull request on the host's hiera data; Puppet applies it ([request a change](../../2._Services_Portfolio/Services/02_computingandboot.md#request-a-change-to-an-existing-machine)) | + +A playbook that installs packages or edits configuration files on a Puppet-managed host fights Puppet: the next Puppet run puts the old state back. + +## 1. Write a playbook + +### Where you can run Ansible + +The hiera package groups install Ansible on the LC machines (`-lc`, `-lca`) and on the Controls consoles; Rundeck on cas-ansible-00 runs Ansible 9. Use only modules from `ansible.builtin` unless you have agreed with Controls IT that a collection is added on cas-ansible-00. + +### A read-only playbook + +A catalogue playbook is one file at the root of `cas_infrastructure`, next to `catalog.yaml`, `ansible.cfg` and `inventory.py`; its inputs are variables. Start with something that changes nothing. This is the playbook behind the catalogue action `epics.status`, `install_status.yml`: + + --- + # Read-only: report whether an EPICS base package is installed on the + # targeted hosts. + # + # ansible-playbook install_status.yml --limit my-host.psi.ch -e epics_base=epics-base-7.0.8 + - name: Install Status + hosts: all + gather_facts: false + tasks: + - name: Check the request + ansible.builtin.assert: + that: epics_base is defined and epics_base | length > 0 + fail_msg: "epics_base (an RPM package name) is required" + + - name: Check EPICS base package status + ansible.builtin.package_facts: + manager: auto + + - name: Report status + ansible.builtin.debug: + msg: "EPICS base package {{ epics_base }} is {{ 'installed' if epics_base in ansible_facts.packages else 'not installed' }}" + +What makes it a good model: it checks its input first and fails with a clear message, it reads the package database with a module instead of piping `rpm -qa` through `grep`, it needs no root, and `gather_facts: false` saves a round trip per host. + +### A playbook that changes something + +An example, not in the catalogue: restart one systemd service and check that it stays up. Save it as `service_restart.yml`: + + --- + # Restart one systemd service on the targeted hosts and check that it stays up. + # ansible-playbook service_restart.yml -i , -e service_unit= --check --diff + - name: Restart a service + hosts: all + gather_facts: false + vars: + service_unit: "" + service_settle_seconds: 10 + tasks: + - name: Check the request + ansible.builtin.assert: + that: service_unit is match('^[A-Za-z0-9@._-]{1,128}[.]service$') + fail_msg: "service_unit must be a systemd service name, e.g. myapp.service" + + - name: Restart the service + ansible.builtin.systemd: + name: "{{ service_unit }}" + state: restarted + become: true + + - name: Give it time to start + ansible.builtin.pause: + seconds: "{{ service_settle_seconds }}" + when: not ansible_check_mode + + - name: Read its state + ansible.builtin.command: systemctl is-active {{ service_unit }} + register: service_state + changed_when: false + check_mode: false + failed_when: service_state.stdout != "active" and not ansible_check_mode + + - name: Report + ansible.builtin.debug: + msg: "{{ service_unit }} is {{ service_state.stdout }}" + +### The rules that matter here + +- **Idempotent.** Running it twice gives the same result. Describe the state you want (`state: started`, `state: absent`), not the steps to get there. A restart is the exception that is meant to act every time. +- **Modules instead of `shell`.** Use `ansible.builtin.systemd`, `package_facts`, `copy`, `file`, `lineinfile` where one exists. They report "changed" correctly and support check mode; `command` and `shell` do neither by themselves. +- **Make `--check` mean something.** A `command` task is skipped in check mode. If it only reads, give it `check_mode: false` and `changed_when: false`, as the "Read its state" task does. Skip waits and follow-up checks with `when: not ansible_check_mode`. +- **Set `changed_when` and `failed_when`** whenever a command's exit code does not mean what Ansible assumes. The catalogue's Puppet run treats exit code 2 ("changes applied") as success: `changed_when: puppet_result.rc == 2`, `failed_when: puppet_result.rc != 0 and puppet_result.rc != 2`. +- **Variables with defaults, checked with `assert`.** Every input has a default in `vars:` and is checked before anything happens. A missing parameter then stops the run with your message, not halfway through. +- **No secrets in Git**, not in the playbook, not in `vars:`, not in a comment. A credential the action needs is stored on cas-ansible-00 and reaches the job from there (see step 4). +- **`hosts: all`** in a catalogue playbook. The targets come from `--limit`, which `cas` builds from the inventory. +- **`become: true` only on the tasks that need root.** A task that reads, reports or waits runs as the login account. +- **No `vars_prompt`.** Rundeck runs playbooks with standard input closed; a prompt fails at once. Confirmation comes from the catalogue (`destructive: true`). + +## 2. Run it by hand against one test host + +Test as yourself, on a machine where your account has sudo, for example your group's [development machine](../../2._Services_Portfolio/Services/02_computingandboot.md#development-machines). Never test against a production IOC host, a gateway or a console. + +1. Check the syntax; this needs no host: + + ansible-playbook --syntax-check -i localhost, service_restart.yml + +2. Run it in check mode on the one host. The trailing comma after the host name makes it a one-host inventory; `-K` asks for your sudo password: + + ansible-playbook service_restart.yml -i .psi.ch, -K \ + -e service_unit=myapp.service --check --diff + +3. Read the result. Each task prints `ok` (nothing to do), `changed` (would change, or changed), `skipping` or `failed`; the `PLAY RECAP` line counts them per host. In check mode "Restart the service" should say `changed` and nothing should fail. A misspelt unit fails here, before anything was restarted. +4. Run it for real: + + ansible-playbook service_restart.yml -i .psi.ch, -K -e service_unit=myapp.service + +Check that it worked: the real run ends with `failed=0` and reports `myapp.service is active`, and on the host `systemctl status myapp.service` shows a start time from your run. For a playbook that sets a state rather than restarting, run it a second time: it must report `changed=0`. + +Your own account is only for testing. Through Rundeck the same playbook logs in as `cas-ansible`, an account the Puppet class `cas_access` creates on each host together with its sudo rule and the authorised key ([how a task runs](../02_explanations/04_rundeck.md#how-a-task-runs)). + +## 3. Put it in Git and have it reviewed + +Catalogue playbooks live in [cas_infrastructure](https://gitea.psi.ch/controls_it/cas_infrastructure), a private repository: ask Controls IT for access. Work on a branch and open a pull request against `main` ([working with Git and Gitea](12_git_gitea.md)). The pull request holds the playbook and its catalogue entry (step 4) together. + +The repository's CI runs on every pull request: the tests (`pytest`) and `ansible-playbook --syntax-check` for each playbook in a list in `.gitea/workflows/ci.yml`. Add your playbook to that list. To run the tests yourself first: + + pip install -e cas-core -e cas-cli -e cas-server pytest + pytest -q + +What the reviewer looks for: + +- the rules above: idempotent, check mode meaningful, inputs checked, no secrets, `become` only where needed; +- that the description says truthfully what the action changes and what it interrupts; +- that each parameter's `pattern` lets through only what the playbook can handle; +- that it is an operation, not configuration that belongs in hiera. + +Check that it worked: CI is green on the pull request, and a reviewer from Controls IT has approved it. + +## 4. Make it an action in the catalogue + +### The catalogue entry + +Add the entry to `catalog.yaml` **and** to its copy `cas-core/cas_core/data/catalog.yaml`; a test fails while the two differ. The entry for the example, modelled on `epics.status` and `machine.restart`: + + - name: service.restart + title: Restart a service + summary: Restart one systemd service on the targeted hosts and check that it stays up. + description: > + Restarts the named systemd service on every targeted host, waits + ten seconds and fails when it is not active then. It interrupts the + service. Check mode reports which hosts would restart it and changes + nothing. + playbook: service_restart.yml + hosts: all + targetable: true + supports_check: true + destructive: true + risk: high + parameters: + - name: unit + extra_var: service_unit + description: The systemd service to restart, e.g. myapp.service. + required_when_live: true + pattern: '^[A-Za-z0-9@._-]{1,128}[.]service$' + secret: false + requires: + - SSH reachability of the targets with privilege escalation. + - The cas_access Puppet class applied on the targets. + +Field by field: + +- `name`: the action id, `.`. It becomes the Rundeck job `cas/service.restart` with the uuid `cas-service-restart`. Renaming it later breaks everyone who calls it. +- `title`, `summary`, `description`: what `cas catalog` and `cas catalog show service.restart` print, and the job description in Rundeck. +- `playbook`: the file, relative to `catalog.yaml`. That directory is also where the playbook runs, so its `ansible.cfg` applies. +- `hosts`: the play's own `hosts:` value. `targetable: false` only for a play on localhost that ignores `--on`. +- `supports_check`: `true` only if `--check` is meaningful. Without it the job has no check option. +- `destructive`: `true` makes `cas` ask for confirmation (or `--yes`), and the job description starts with `DESTRUCTIVE`. +- `risk`: `low`, `medium` or `high`; without it, `high` for destructive actions, otherwise `low`. +- `parameters`: each becomes a job option and reaches the playbook as the variable `extra_var`. `required_when_live` makes the option required in Rundeck. Rundeck refuses a value that does not match `pattern`, so give every parameter one, anchored with `^…$`. +- `secret: true` with `storage_path: keys/cas/…`: a credential Rundeck reads from its key storage. It is never logged and never typed by the caller. The owner stores it on cas-ansible-00 by hand. +- `requires`: prerequisites in plain words, shown before a run so that a failure can be explained. +- `portal`: leave it out; Controls IT sets it. + +### Into Rundeck + +After the merge, Controls IT runs, from an up-to-date checkout of `main`: + + ansible-playbook -i rundeck/inventory rundeck/configure_rundeck.yml + +It copies the checkout to `/opt/cas_infrastructure` on cas-ansible-00, generates one job per catalogue action, imports them (updating existing ones in place) and deletes jobs the catalogue no longer has ([keeping it current](../02_explanations/04_rundeck.md#keeping-it-current)). Rundeck runs exactly that copy: a change that is merged but not imported does not run yet. + +### Run it + +Today on cas-ansible-00, as a member of `cas-operators` (`sudo cas …`), with `cas` pointed at Rundeck ([using it](../02_explanations/04_rundeck.md#using-it)): + + cas catalog show service.restart + cas run service.restart --on --param unit=myapp.service --check --follow + cas run service.restart --on --param unit=myapp.service --follow + +Check that it worked: the job log starts with the Rundeck execution number and a permalink, `http://cas-ansible-00.psi.ch:4440/project/cas/execution/show/`. Open it: the run is in the execution history of job `cas/service.restart`, with its output and who started it. `cas job show ` shows the same record. + +### Who may do what + +| | Today | Planned | +|---|---|---| +| Propose an action | Anyone with access to `cas_infrastructure`, by pull request | | +| Review, merge, import into Rundeck | Controls IT | Import by a merge pipeline | +| Run actions | Members of `cas-operators` on cas-ansible-00, through `sudo cas` | Expert groups through `cas` and the planned web hub, each on its own hosts, decided by LDAP and Unix groups ([who uses it](../02_explanations/04_rundeck.md#who-uses-it)) | + +## 5. Keep it healthy + +- **Every change is a pull request.** Change the playbook and the entry together, then have the jobs imported again. +- **Keep the `name`.** Add a parameter with a default rather than changing what an existing one means; callers keep working. +- **Remove an action** by deleting its entry from both copies of `catalog.yaml` and its playbook. The next `configure_rundeck.yml` deletes the job. +- **Read your action's runs** in Rundeck now and then. A job that fails on some hosts every time usually points at one of these: + - a host without `cas_access`, or whose `cas_access::control_nodes` does not list cas-ansible-00: `Permission denied (publickey)`, nothing changed; + - a target `cas` cannot find in the inventory: `'' is neither an inventoried host, a group, nor a matching pattern`; + - a value that does not match the parameter's `pattern`: Rundeck refuses the run before Ansible starts. + +## What not to do + +- Do not run a playbook by hand against production hosts. That is what the catalogue is for: one place, one record. +- Do not write playbooks that install packages or change files Puppet manages. That is a hiera change. +- Do not set `host_key_checking = False` in a new repository's `ansible.cfg`. It accepts any machine that answers under the host's name. +- Do not use `state: present` for software you mean to update: it installs once and never upgrades. Use `state: latest` deliberately, or pin a version. +- Do not copy older playbooks from other repositories without reading them. Some are out of date or wrong. +- Do not leave a job's host list empty in the Rundeck web interface. An empty limit means the play's `hosts: all`. + +## When it fails + +- **`Permission denied (publickey)` on the first task:** the host has no `cas_access`, or cas-ansible-00 is not in its `control_nodes`. A hiera pull request and a Puppet run on the host fix it; `cas access verify --on ` tells which link is broken. +- **`sudo: a password is required`:** the host's sudo rule for `cas-ansible` is missing; again `cas_access`. +- **`playbook … could not be found`:** the jobs were imported, but the copy on cas-ansible-00 is older. Run `configure_rundeck.yml` again from an up-to-date checkout. +- **`couldn't resolve module/action`:** the playbook uses a collection that is not installed on cas-ansible-00. Use `ansible.builtin`, or ask Controls IT to add it. +- **Check mode says `ok` but the real run changes things:** a `command` or `shell` task without `check_mode: false` was skipped in check mode. +- **Exit code `1` from `cas` with no detail:** Rundeck does not pass Ansible's own exit code on; read the job log. diff --git a/docs/3._Knowledge_Center/03_how_to/images/17_ansible_path.svg b/docs/3._Knowledge_Center/03_how_to/images/17_ansible_path.svg new file mode 100644 index 00000000..e26105e8 --- /dev/null +++ b/docs/3._Knowledge_Center/03_how_to/images/17_ansible_path.svg @@ -0,0 +1,139 @@ + + From a playbook to a Rundeck job + Step 1, write: a playbook in Git with defaults for its variables and checked inputs, no secrets, modules instead of shell. Step 2, test: ansible-playbook with --limit on one test host, first with --check --diff, as yourself with sudo on that host. Step 3, review: a pull request in cas_infrastructure; CI runs the tests and a syntax check; Controls IT reviews. Step 4, catalogue: an action entry in catalog.yaml with its parameters and their patterns. Step 5, Rundeck: configure_rundeck.yml on cas-ansible-00 imports the job cas/action. Last, on the hosts: cas run action --on host; the job logs in as cas-ansible and every run is in the execution history. + + + + + + + + + + + + + + WRITE, TEST, REVIEW + LIVES IN RUNDECK + + + + + + + + + 1 + 2 + 3 + 4 + 5 + + + + + + + + Write + Playbook in Git + + myaction.yml + vars: defaults + assert inputs + No secrets; + modules, not shell + + + + + + + + Test + One test host + + ansible-playbook + --limit <host> + --check --diff + Your account, + sudo on that host + + + + + + + + Review + Pull request + + cas_infrastructure + CI: tests and + syntax check + Controls IT + reviews and merges + + + + + + + + Catalogue + Action entry + + catalog.yaml + name: res.verb + parameters + pattern + Only catalogued + actions can run + + + + + + + + Rundeck job + cas/<action> + + configure_ + rundeck.yml + imports the jobs + + cas-ansible-00 + + + + + + + + On the hosts + cas run + <action> + --on <host> + Logs in as + cas-ansible + Every run in the + execution history + + diff --git a/zensical.toml b/zensical.toml index 8856ce77..f0f8945a 100644 --- a/zensical.toml +++ b/zensical.toml @@ -471,6 +471,7 @@ logo = "cas_03_sp" "3._Knowledge_Center/03_how_to/14_caqtdm_panels.md", "3._Knowledge_Center/03_how_to/15_ioc_platforms.md", "3._Knowledge_Center/03_how_to/16_configure_MOXA.md", + "3._Knowledge_Center/03_how_to/17_ansible.md", ]}, { "Troubleshooting" = [ "3._Knowledge_Center/04_troubleshooting/index.md",