Provisioning Moodle users and enrolments through web services: when it fits
Web services provisioning lets an HR or identity system push user creation, profile updates, suspensions and course enrolments into Moodle through its REST web services, so the source system stays the single record of who should have access. Choose it when the source system can call an API you control and you need changes to land in Moodle on your schedule, with your own error handling. The alternative approaches pull data into Moodle from a directory or file, which works well for some sites but leaves less room to record why each change happened. Where an identity system already holds accurate records, the sync design decides how often Moodle drifts from that source, not the Moodle feature set.
Compare the options against your own data flow. LDAP authentication and user sync suits organizations whose identity is already in Active Directory or OpenLDAP and whose sign-in should follow directory passwords. External database enrolment suits a student information system that exposes a clean view of enrolments and can tolerate scheduled, batch-style changes. Cohort sync suits enrolment that follows groups of users rather than individual records. Flat file and IMS Enterprise feeds suit legacy systems that can only write files. Web services are usually preferable when you need per-record responses, custom field logic, or a single integration that creates users and enrols them in the same call. They also add an engineering cost, since your team or partner must own the service account, token scope and retry logic. Ask whether your sources are readable through an API or a view, and whether any sync must reverse decisions safely.
Before committing, confirm the exact web service functions and token permissions available on your Moodle version. Each live site publishes its API documentation at Site administration, Server, Web services, API Documentation, which lists the functions each enabled service exposes. Check that list against the release you run, since function names and parameters can change between versions. Plan the integration around that documented surface rather than assumptions about what a function accepts.
Choosing web services over other provisioning methods
When the HR or identity platform exposes a documented API and can push or be polled for changes, Moodle's REST web services are usually the most controllable route. Your integration code calls Moodle functions such as user creation, user update and enrolment, under a dedicated service account with a token limited to the functions it needs. Errors come back as explicit responses from each call, so your sync job can log, retry and report them per record.
- Ownership: Your team or your partner owns the sync code, its schedule and its error queue, so the logic lives outside Moodle.
- Error visibility: Each failed call returns a response you can capture per user, which makes reconciliation straightforward.
- Change control: Web service functions can change between Moodle releases, so the code needs testing during every upgrade.
- Scope control: Tokens and service functions can be narrowed to the operations the sync needs.
- Recurring work: The integration needs monitoring and maintenance for as long as the feed runs.
Before committing, confirm that the HR platform can produce stable unique identifiers and leaver events, and that your Moodle version exposes the functions you need.
When the source of truth is LDAP or Active Directory, Moodle's core LDAP authentication and enrolment plugins are often simpler than custom code. Accounts can be created, updated and suspended by scheduled tasks that read the directory, and group membership can drive course enrolment. Directory teams usually already maintain the groups, so little new process is needed.
- Ownership: Configuration sits in Moodle, while the directory team controls the data, which keeps custom code to a minimum.
- Error visibility: Failures appear in task logs and connection errors, which are less granular than per-record API responses.
- Attribute limits: Only attributes that the directory holds can flow in, so HR fields that live elsewhere need another route.
- Deletion handling: Confirm how removed accounts are suspended, since default behaviour depends on configuration.
- Recurring work: Directory structure changes, such as group redesigns, can silently change course enrolments.
Before committing, confirm whether the directory already carries every attribute and group that Moodle needs.
When the source is a student information system or an HR database, Moodle's external database plugins can read a view directly. This works well for enrolment feeds that already exist as tables, but the database team must maintain the view and its contract with Moodle. The plugin's sync is driven by comparing the view to Moodle's current state, so the view must be stable and complete on every run.
- Ownership: The database owner maintains the view, and the Moodle team owns mapping and scheduling.
- Error visibility: Failed rows are harder to trace than API responses, so reporting needs to be designed in.
- Unenrolment risk: A partial or empty view can trigger mass unenrolment, so safeguards and thresholds should be reviewed.
- Read access: The database account should be read-only and limited to the view.
- Recurring work: Schema changes in the source system must be coordinated with Moodle configuration.
Before committing, ask the database owner how the view behaves when source records are late or missing.
Flat file and IMS Enterprise feeds, and cohort upload or cohort sync, suit legacy systems that can only export files or that already maintain groups inside Moodle. They are easy to inspect by hand, and cron processes them without any API client. The trade-off is that files are batch artefacts, so timing, file permissions and proof that a feed was processed all need deliberate monitoring.
- Ownership: The source system owns the export, while Moodle owns the import and its schedule.
- Error visibility: Errors are written to logs or reports that someone must read, so silent failure is a real risk.
- Data freshness: Changes wait for the next file, which can delay access for new starters or leavers.
- Cohorts as a layer: Cohort sync can reduce direct enrolment logic, but it adds another object to govern.
- Recurring work: Someone must confirm each feed was processed, especially after server or permission changes.
Before committing, confirm who will check that each feed ran and what happens when a file is missing.
Many organisations have an HR system for people data, a directory for sign-in and a separate system for course rosters. In that case, the decision is rarely a single method. Each attribute and each enrolment should have one owning source, and the provisioning method should follow that ownership rather than follow convenience. Identity owns the account, HR owns employment status, and course systems own course membership.
- Single owner per field: Record which system is authoritative for name, email, status and each course role.
- Overlap control: Two methods writing the same field will fight each other, so avoid duplicate paths.
- Shared identifiers: A stable identifier across systems is the basis for matching and idempotent updates.
- Testing combinations: Test a leaver across every path, not just the one you built.
- Recurring work: Each added source adds a reconciliation step to operations.
Before committing, write the ownership table for your own environment and check it against each system's documentation.
Web service design options and when each fits
This table compares the main design choices for a Moodle web service provisioning integration: where the sync logic runs, how much data each run processes, how enrolments are granted and what happens to leavers. Read each row for the condition that favors an option and the trade-off you accept by choosing it.
| Design choice | When it fits | Main trade-off |
|---|---|---|
| Logic inside Moodle (local plugin with scheduled task) | Small or single-source feeds, a team that maintains Moodle code, and no separate scheduler or middleware to operate | Sync logic is tied to Moodle upgrades and plugin reviews, and failures surface mainly in Moodle logs |
| External middleware calling REST endpoints | Several source systems feed Moodle, identity or HR platforms already run a workflow engine, or retry and monitoring must live outside Moodle | Another service to secure, patch and monitor, and the token scope and error handling must be designed on both sides |
| Full sync on each run | Source population is small enough to reconcile completely, or the source cannot reliably report changes | Run time and load grow with the user base, and a bad source extract can change many accounts in one pass |
| Delta sync from changed records | Source system exposes change timestamps or event feeds and the population is large | Missed changes are hard to detect without periodic full reconciliation, so a reconciliation job is usually still needed |
| User-level enrolment | Course memberships are individual and vary by person, such as elective or role-specific access | Each membership is a separate record to manage, which increases API calls and makes bulk group changes harder to audit |
| Cohort-level enrolment | Memberships follow a shared attribute such as department, programme or intake, and many users join the same course together | Membership depends on cohort accuracy, so errors in cohort population spread to every enrolled course |
| Suspend leavers by default | Records may return, audit trails must be preserved, or the HR feed sometimes omits people temporarily | Suspended accounts still count toward licence and data retention questions, so retention rules must be confirmed |
| Delete leavers by default | Policy requires removal of personal data on a set schedule and the data owner has approved deletion rules | Deletion is hard to reverse and removes course history links, so most sites confirm retention policy before enabling it |
Setting up the service account, token and sync sequence
This sequence takes a Moodle site from default settings to a tested, scoped integration that creates, updates, suspends and enrols users from an HR or identity system without duplicating accounts. Each step closes with a check so the integration team can show what is live and what is not.
Enable web services and the REST protocol
A Moodle administrator turns on web services under Site administration, Advanced features, and then enables the REST protocol under Site administration, Server, Web services, Manage protocols. Leave the other protocols off unless a documented need exists, since each enabled protocol adds an attack surface. Done means the REST protocol shows as enabled in the protocol list, and the change is recorded in the site's configuration change log for the change record.
Create a dedicated integration role
Create a separate role for the sync account rather than reusing an administrator or teacher role. Grant only the capabilities the listed functions need, such as the user creation, update and enrolment capabilities, and assign the role at system context only where it is required. Confirm the role with the Check permissions tool against a test user before moving on. Done means a written capability list exists that the security team has reviewed.
Create a service account with a non-login identity
Create a dedicated user for the integration with a strong, unguessable password that is never used for interactive sign-in, and assign it the integration role. Record the owner, purpose and review date for the account in your identity register. Done means the account exists, holds only the integration role, and appears in your access review scope.
Define an external service with an explicit function list
Under Site administration, Server, Web services, External services, add a custom service and select each function the integration calls, and nothing else. Do not select the full function list of the built-in services. Done means the service lists only the agreed functions, and the list is exported and stored with the design record.
Issue a token scoped to that service
Under Manage tokens, create a token for the service account that is bound only to the custom service. Store the token in your secrets manager, restrict who can read it, and set a restriction on the allowed IP addresses where the option is available in your Moodle version. Confirm the function list in the API Documentation page for the site matches the functions you selected, and call one function with the token to see that a call outside the list is refused.
Test read-only calls on a non-production site
Run read-only functions such as looking up users by external identifier and reading course enrolments against a non-production copy of the site with realistic but anonymized data. Log each request and response, and compare the returned fields with the expected HR attributes. Done means every read call returns the expected data, and any function that was not in the agreed list is confirmed as refused.
Implement idempotent create, update, suspend and enrol calls
Build the write operations so each record carries a stable external identifier from the source system, and the sync looks up that identifier before creating anything. Updates change only the mapped fields, suspension sets the account to suspended rather than deleting it, and enrolment calls check for an existing enrolment before adding one. Run the same input file twice in the test site and confirm that the second run creates no duplicates and changes no records. Done means the rerun report shows zero creations and zero enrolment changes.
How to make the sync idempotent so reruns do not duplicate or corrupt accounts
An idempotent sync means a rerun after a partial failure produces the same end state as a clean run, so the first design decision is the matching key. Match every Moodle account to a stable external identifier from the HR or identity system, such as an employee number or a directory object ID, and store that value in a custom user profile field or the idnumber field. Do not match on username or email. Usernames get changed when people marry or are renamed, and email addresses get reassigned. A sync that matches on either can create a second account for the same person, or worse, attach one person's enrolments to another person's account. Confirm with your HR or identity owner that the identifier is never reused after someone leaves.
Store the last-seen source state for each record so the sync can tell what has changed. A common pattern is a small staging table in your integration database that holds the external ID, a hash of the normalized source fields, the Moodle user ID once created, and a timestamp of the last successful apply. On each run, compute the hash from the source record and compare it with the stored value. If they match, skip the call to Moodle entirely. This makes reruns cheap, avoids writing unchanged profile data over fields that users or administrators may have edited in Moodle, and gives you a record to reconcile against when a run stops halfway. Normalize values before hashing (trim whitespace, fix case on emails, sort multi-valued fields) or every run will look like a change.
Treat leavers by suspension, not deletion, and route them through a review queue. When a record disappears from the source or is marked inactive, set the Moodle account to suspended and record the change, but do not call a delete function. Deleted accounts cannot be restored with their grade and submission history, and a temporary HR data gap could otherwise remove a whole cohort. Put suspensions above a threshold you agree in advance into a review queue for a person to approve before they are applied. Confirm with your records and legal owners how long suspended accounts are retained under your policies, since that governs your data retention settings, not the sync code. Also confirm which Moodle web service functions your installed version exposes for suspension and enrolment changes, using the API documentation on your own site.
Securing service accounts, token scope and transport
The web service account that creates and changes users is the most privileged integration in the sync design, so its access, credentials and traffic need the same care as the HR or identity system feeding it. The six controls below cover who the account is, what it can call, how long its credentials live, where it can connect from, how its traffic is protected and how its activity is recorded. Confirm each setting on your Moodle version before go-live, because menu paths and defaults change between releases.
Least-privilege integration role
Create a dedicated role for the sync account and assign only the capabilities the sync needs, such as creating and updating users, suspending accounts and enrolling users in specific courses. Do not reuse the site administrator or a teacher account, because a leaked token would then carry full site rights. Review the role after each Moodle upgrade, since capability names and defaults can change. Ask the partner to produce a written capability list for your version.
External services docsFunction allow list on the service
Attach only the web service functions the sync calls to a dedicated external service, and leave every other function out. An allow list stops a token from calling functions that exist for other integrations, such as deleting content or changing site settings. Keep a record of each function with the reason it is needed, so a reviewer can see why it is enabled. Check the list whenever the sync logic changes.
Token lifetime and rotation
Set a validity period on each token and plan for rotation before it expires, so the sync does not fail silently and teams do not extend tokens indefinitely. Store the token in your secrets manager, not in configuration files or source control. Rotate on a schedule and immediately after any staff change or suspected exposure. Confirm in your Moodle version where token validity is configured and whether tokens can be revoked individually.
Network path restriction
Limit the sync account to requests from the address range of the sync host or its egress gateway, enforced at the firewall or reverse proxy where possible. A token that can only be used from one network path is much harder to abuse from elsewhere. Also restrict who can reach the web services endpoint at all. Document the path so network changes do not break provisioning without review.
HTTPS only transport
Require HTTPS for every call to the REST endpoint, redirect or refuse plain HTTP, and use certificates from a trusted authority that your sync host validates. Tokens sent in clear text on any hop can be captured and replayed. Check that the reverse proxy does not terminate TLS in a way that loses the original scheme, and that the sync client does not disable certificate checks to get past an internal certificate problem.
API call logging and protecting source credentials
Enable Moodle's logging for web service calls and forward those logs to your central log platform, so each user creation, change or suspension can be traced to the sync account and a run. Separately, protect the credentials the sync uses to read the HR or identity source: use a read-only account scoped to the fields it needs, and keep its secrets out of logs. Ask the partner how failed calls are recorded and who reviews them.
Questions teams ask before provisioning Moodle through web services
What drives the cost of provisioning Moodle users through web services?
The cost is driven mainly by how many source systems feed Moodle, how clean the HR or identity data is, and how many rules govern who gets which role in which course. A single HR source with stable employee IDs and a small set of roles is far less work than several feeds with duplicate records, contractors, and multiple campuses or business units. Costs are one-time for design, build and testing, and recurring for monitoring, fixing sync errors and handling changes to the source schema. Ask any provider for a written scope that lists each source, each Moodle function the sync will call, the test environment, the error handling and the handover, because those items set the quote. DeployOpen does not publish prices, and a quote follows from the written scope.
Can our internal team build a Moodle web services sync themselves?
Yes, a team with PHP or integration experience and access to a Moodle test site can build it, provided it understands Moodle's external services model. The work involves creating a dedicated service account, defining an external service with only the functions needed, issuing a token tied to that service, and writing an idempotent sync job that creates, updates, suspends and enrols users. The harder parts are reconciling identifiers, handling partial failures, and proving the job behaves correctly under edge cases such as renamed users and returning staff. Teams without that experience usually benefit from a short review of the design before build. Your own staff can also confirm the API surface on their site under Site administration, Server, Web services, API Documentation.
How long does a Moodle provisioning project take?
Duration depends on source system quality and scope more than on Moodle itself. Clean source data with a stable unique identifier, one feed and a short list of roles can move quickly through design and test. Duplicate accounts, inconsistent job codes, unclear rules for contractors, or several feeds with different update schedules add discovery, data cleansing and test cycles. Ask for a timeline that is tied to named milestones: source data review, design sign-off, build in a test site, a test run with agreed records, and a production cutover with a rollback plan. Any figure a provider gives should come with the assumptions behind it, and you should confirm those assumptions against your own data before accepting it.
What does the HR or identity team need to provide?
The HR or identity team needs to provide an authoritative source of person records, a stable unique identifier for each person, and a clear definition of employment states such as active, on leave, leaver and contractor. They also need to confirm which attributes Moodle should receive, such as email, names, department and manager, and who owns each attribute. A written mapping from each source field to each Moodle field is the most useful artifact to prepare early. Your team should also agree on the change feed: whether the sync reads a full extract each run or only changes, how often it runs, and who receives alerts when a run fails. Without these decisions, the Moodle side cannot be designed with confidence.
How can we test the sync without touching production users?
Build and test against a separate Moodle environment with a copy of the integration configuration and a set of test identities that mirror real cases: new hires, changed names, transfers between departments, leavers and rehires. Use test records in the source system or an extract with masked personal data, so no real person is created or suspended by mistake. Run the sync in a dry-run or report-only mode first, where it logs the actions it would take without making them. Confirm that the service account has only the functions it needs, check the Moodle logs after each run, and rerun the same input to prove the job is idempotent, meaning a second run produces no further changes. Only then should a production run be scheduled, with a small first scope.
How should leavers be handled in a Moodle provisioning sync?
Leavers should be suspended rather than deleted, so that their records, grades and course history remain intact for retention and audit purposes. The sync should suspend the Moodle account when the source marks the person as a leaver, remove or end active enrolments according to a documented rule, and keep a log of each action. Deletion should be a separate, governed process with its own retention rules, because deleting a user can remove records that your institution must keep. Before go-live, confirm the rule for people who return after leaving, since a rehire should reactivate the existing account instead of creating a duplicate. Check with your records and privacy owners how long suspended accounts are kept.
What are the main security risks of the service account and token?
The main risks are a token with broader functions than the sync needs, a token stored in plain text on a shared server, and a service account that a person can log into interactively. The safer pattern is a dedicated service account with a restricted role, an external service limited to the functions the sync calls, a token issued for that service only, and token storage in a secrets manager or protected configuration. Rotate the token on a schedule your security team sets, and monitor the logs for unusual calls. Review the Moodle security report and confirm the web services settings on your own site, because the exact options depend on your Moodle version and configuration.
How the HR-to-Moodle sync flows through the service account
The sync starts when the HR or identity source publishes changes to users and positions. Middleware matches each record to a Moodle account on the external ID, then decides whether to create, update, suspend or enrol. Only that middleware calls Moodle's REST web services, using a dedicated service account and a token limited to the functions it needs. Every call result and error is written to a log and a review queue, so the team can check what changed. The trust boundary sits around the Moodle web service and the token, which is where scope and token handling need the closest review.
Changes flow from HR through middleware into Moodle, with the token boundary marked.
How DeployOpen scopes, builds and supports the Moodle provisioning integration
DeployOpen plans, implements and supports Moodle in infrastructure you control, including the web service layer that provisions users and enrolments from an HR or identity system. Each engagement starts with a written scope that names the source system, the Moodle web service functions, the service account and the sync rules before any code is written.
How we scope
- Map which HR or identity fields create, update, suspend and enrol users in Moodle, and which system owns each field.
- Agree the Moodle web service functions, the dedicated service account and the token scope in writing before build starts.
- Confirm the target Moodle version and its database and PHP requirements, since they shape the integration and the test plan.
How we build
- Build an idempotent sync job that matches users on a stable identifier, so repeated runs create no duplicate accounts.
- Design error handling that logs rejected records, retries transient failures and quarantines bad rows for review.
- Test with a staging Moodle site and representative records, including leavers, name changes and enrolment removals.
How we hand over
- Deliver the sync code, configuration, service account setup and a runbook describing every scheduled job and its failure states.
- Document the token scope, the permitted web service functions and the steps to rotate credentials.
- Walk your administrators and integration engineers through monitoring, log review and the fixes for common rejection messages.
How we support
- Offer ongoing support, Moodle upgrades and continuous testing as retainers after handover, scoped in writing.
- Retest the integration when Moodle or the source system changes, including after each planned upgrade.
- Review service account permissions and web service configuration periodically, so access stays limited to what the sync needs.

