Managing OpenSearch with Terraform

A planning guide to managing self-hosted OpenSearch configuration as code with the Terraform OpenSearch provider, covering prerequisites, setup order, security and failure points.

On this page

How the Terraform provider manages OpenSearch configuration

Many teams manage OpenSearch indexes, index templates, ISM policies, roles and role mappings by hand, through the Dashboards Dev Tools console or ad hoc API calls, and then discover that each cluster has drifted from the others. The Terraform OpenSearch provider addresses that gap by declaring these objects as code, so changes can be reviewed, versioned and applied the same way in every environment. It provisions resources through the OpenSearch API, works with OpenSearch clusters running on Kubernetes or other infrastructure you operate, and also supports Amazon OpenSearch Service domains. The OpenSearch documentation for the Terraform provider lists the resource types it supports, and that list is the first thing to check against the features your team actually uses.

The provider manages configuration, not the cluster. It does not create nodes, assign cluster manager, data, ingest or coordinating roles, size storage, or handle TLS certificates for the transport layer. Those belong to the deployment method you choose, whether that is the OpenSearch Kubernetes Operator, Helm, packages or an Ansible playbook, and they should be settled before Terraform touches the cluster. Confirm with your platform team which API endpoint and credentials Terraform will use, and whether the cluster's Security plugin accepts that identity with the permissions the resources require. Keeping the boundary explicit prevents one tool from silently overwriting settings the other owns.

Plan for state before the first apply. Terraform records what it created in a state file, and that file will hold references to indexes, roles and mappings that can carry sensitive detail. Store state in a backend your security team has approved and restrict who can read it. If your organization is weighing OpenTofu as the engine, its documentation describes state and plan encryption at rest with several key providers, and the provider's behavior under OpenTofu should be confirmed in your own test run, since OpenTofu does not guarantee compatibility with future Terraform releases. Ask the team that will run the pipeline which state backend and key provider they will use, and who holds the keys.

What you need before the first plan

Terraform can only plan and apply changes that the cluster, the network and your pipeline already allow. Each prerequisite below is a decision with an owner, and most of them need to be settled before anyone writes the first resource block.

Cluster version and provider compatibility

Confirm which OpenSearch version runs in each environment and that the provider release you pin supports it. Check the provider documentation for its tested versions, then check the OpenSearch releases page for maintenance status, since versions in maintenance get security patches but no new features. A provider that lags a cluster upgrade can fail on resources the old API does not expose. Owner: platform engineering, with the cluster maintainer.

Provider docs

Administrative API identity

Create a dedicated service user for Terraform with only the security plugin rights needed to manage indexes, templates, ISM policies, roles and role mappings. Avoid reusing a human admin account or the built-in admin certificate in pipelines. Record which rights the identity holds so reviewers can see what a plan may change. Owner: security engineering, with the cluster administrator approving the role grant.

TLS trust for the API endpoint

Decide how the runner trusts the cluster certificate: an internal certificate authority bundle distributed to runners, or a pinned chain managed in secrets. Confirm which hostnames appear in the certificate subject alternative names, because a mismatch fails at the first plan rather than during apply. Plan the rotation date for that bundle. Owner: the PKI or certificate team.

Network reachability from the runner

Map the path from the runner to the OpenSearch HTTPS endpoint, including Kubernetes service addresses, ingress rules, load balancers and firewall policy. If the runner sits outside the cluster network, agree on a bastion, a private runner or a VPN, and document it. Confirm that the endpoint is the coordinating path you intend, not a single data node. Owner: network engineering.

Remote and encrypted state backend

Store state and plan files in a remote backend with locking and encryption at rest, not on a developer laptop. State can contain sensitive configuration, so restrict read access to the pipeline and to named reviewers. OpenTofu supports state and plan encryption with several key providers, which you should compare with your key management standard. Owner: platform engineering with the security team choosing the key provider.

State encryption docs

CI runner and secrets handling

Pick a runner that is isolated, ephemeral where possible and able to reach the cluster, then inject the API credentials from your secrets manager at job time. Keep plan output and logs free of passwords, and require review before apply on production clusters. Confirm who can approve applies and how runner images are patched. Owner: DevOps or platform engineering, with the security team reviewing the pipeline.

Terraform or OpenTofu for this work

The OpenSearch Terraform provider is used the same way whether you run Terraform or OpenTofu, so the choice between them is about licensing, governance and long-term compatibility rather than about resource definitions. Your HCL files, provider blocks and plan-apply workflow carry over in either tool. The decision is mostly about which engine your organization is willing to standardize on for the next several years. OpenTofu is licensed under the Mozilla Public License 2.0, is under the stewardship of the Linux Foundation, and was accepted to the CNCF at the Sandbox maturity level on April 23, 2025. The latest release cited for this section is v1.13.1, dated October 1, 2026. Confirm the license terms and current CNCF status with your legal and procurement teams before you write them into a standard.

The OpenTofu FAQ states an aim of feature parity with Terraform, but it does not guarantee compatibility with future Terraform releases. Whichever engine you choose, pin the binary version and the OpenSearch provider version in your configuration and lockfile, and test every upgrade in a non-production workspace against a disposable cluster before it reaches the pipeline that manages production indexes, roles and ISM policies. Treat each engine upgrade as a change with its own review, not as routine tooling maintenance.

State encryption is the decision point that matters most for this work. Role definitions, role mappings and some connection settings can reference sensitive values, and the state file records what was applied. OpenTofu encrypts state and plan files at rest, for local storage and remote backends, using key providers such as PBKDF2, AWS KMS, GCP KMS, OpenBao and Azure Vault. Choose the key provider that matches where your secrets already live, record who holds the keys, and confirm that your backend, CI runners and backup copies all honor the encryption. If you stay on Terraform, plan equivalent protection at the backend level and verify it with your own review.

How to set up OpenSearch configuration as code

This sequence moves OpenSearch indexes, templates, ISM policies, roles and role mappings out of manual console work and into reviewed, versioned Terraform code that can be applied to a self-managed cluster the same way every time.

  1. Create the state backend and encryption

    Your platform or infrastructure team creates a remote state backend in storage you control, with access limited to the people and pipelines that manage the cluster. Turn on state and plan encryption so that secrets and resource details written to state are protected at rest, and choose a key provider that matches your key management standards. Confirm the backend is locked during applies so two runs cannot write state at once. The step is done when a test initialization writes state to the backend and a second user can read it under the same access rules, with no plaintext state left on a laptop.

  2. Define the provider connection with secrets from a store

    Declare the OpenSearch provider with the cluster endpoint, TLS trust settings and client credentials, but do not put passwords or certificates in the code. Pull the admin credentials at run time from your secrets store, using a dedicated automation identity that holds only the permissions the managed resources need. Pin the provider version in the lock file so that every run uses the same release. The check is a read-only call, such as listing existing indexes or roles through the provider, that succeeds from the CI runner and fails cleanly when the credential is removed.

  3. Import existing indexes and templates

    Inventory the indexes, index templates and component templates already on the cluster, then bring them under management with import blocks or import commands so Terraform records the current state rather than recreating it. Compare each declared resource with the live settings, including shard counts, replicas, mappings and analyzers, and correct the code until it matches what production is actually using. Expect some settings to be set by the cluster or by applications at creation time, and decide deliberately which of them the code will own. The check is a plan that shows no changes for imported resources before any new definitions are added.

  4. Add ISM policies for index lifecycle

    Define Index State Management policies as code, covering rollover, retention and deletion for each index pattern, and attach them through the templates or index settings that match the data. Check that each policy references states and actions that exist in the OpenSearch version you run, since behavior can differ between releases. Test the policy against a non-production index with a short test configuration so you see the transitions and deletions before any production data is affected. The check is a policy explain call that shows the expected state for a sample index, plus a plan that shows the policy attachments without touching existing indexes unexpectedly.

  5. Declare roles and role mappings

    Model the Security plugin roles, their index and cluster permissions, and any document-level or field-level restrictions in code. Then map identity provider groups or backend roles to those roles, so access follows the directory groups your organization already manages. Review the permissions with the security team, and keep administrative roles separate from application roles. Confirm that the mappings match the identity backend configured on the cluster, such as SAML, OpenID Connect or LDAP. The check is a read-back of each role and mapping through the API, compared with the code, and a test login from a sample account that gets exactly the access the role grants.

  6. Run plan in CI with review before apply

    Set up a pipeline that runs formatting, validation and a plan on every change, posts the plan output to the merge request and requires a reviewer to approve it before the apply job runs. Restrict the apply job to protected branches and to the automation identity, and record who approved each run. Keep the same code path for non-production and production clusters, with only variables and credentials differing. The check is a plan on a feature branch that reports no unexpected drift, followed by a deliberate test change, such as a replica count or a role permission, applied to a non-production cluster and confirmed by a read-back.

  7. Confirm drift detection and rollback

    Schedule a plan job that runs on the default branch at a regular interval and alerts the owning team when the live cluster differs from the code, so manual console changes are caught rather than silently kept. Document how to revert a change by reverting the commit and applying it through the same pipeline, and test that rollback on the non-production cluster. Agree with the team how manual emergency changes are recorded and then folded back into code. The check is a drift run that reports a deliberately introduced manual change and a rollback that restores the previous configuration without manual edits.

How changes move from Git to the cluster

A change starts as a commit to the Git repository, which triggers a CI pipeline on a runner. The runner executes plan and then apply through Terraform or OpenTofu, which calls the OpenSearch API on the cluster. Two components sit outside the runner: the encrypted state backend that stores the state and plan files, and the secrets store that supplies API credentials at run time. The trust boundary between the CI runner and the cluster network is the point to check: confirm which network path, credentials and roles the runner uses to reach the API, and who can approve an apply.

Change flow from Git through CI and Terraform or OpenTofu to the OpenSearch API.

Mapping configuration objects to Terraform resources

This table maps each OpenSearch configuration object to the provider resource that manages it, the team that approves changes to it, and the check a reviewer runs before merging. Resource and attribute names should be confirmed in the OpenSearch Terraform provider documentation before any module is written, since the names below describe object types rather than exact identifiers.

Configuration objectProvider resource to confirmChange ownerReview check
IndexesIndex resource (confirm name and settings attributes in provider docs)Application or data owner for each indexShard count, replica count and mappings match the agreed sizing; no field is added that bypasses data classification
Index templatesIndex template resource (confirm name and pattern attributes)Platform team with data owner sign-offTemplate pattern does not overlap another template; default settings match retention and storage tier decisions
ISM policiesISM policy resource (confirm state, action and transition attributes)Platform team with operations on-call leadRetention and delete steps match the documented retention requirement; rollover thresholds tested in a non-production cluster
RolesRole resource (confirm index permission and document or field security attributes)Security team, with data owner for index-level accessLeast privilege reviewed; document-level and field-level restrictions present where sensitive fields exist; no wildcard index access without written approval
Role mappingsRole mapping resource (confirm backend role and user attributes)Identity team and security team jointlyEach mapping traces to a named group in the identity provider; no direct user mapping for standing access
Backend identity groups (SAML, OIDC or LDAP)Managed in the identity provider; referenced by name in role mappingsIdentity administratorsGroup names in the mapping match the identity provider exactly; group membership changes follow the joiner, mover and leaver process
Security plugin admin and audit settingsConfirm whether the provider manages these objects or whether they stay in static configuration filesSecurity teamAudit logging remains enabled after each change; admin certificates and credentials are not stored in the repository

Securing the state, credentials and roles

Terraform state, provider credentials and the CI identity are the three places where a configuration-as-code setup can expose a cluster. Each card below covers one control, and each one depends on the OpenSearch Security plugin settings the cluster already enforces.

Encrypt state and plan files

Terraform state records resource attributes, and those can include sensitive values. Plan files carry the same data. OpenTofu can encrypt both at rest for local storage and remote backends, using key providers such as AWS KMS, GCP KMS, OpenBao or Azure Vault. Confirm which key provider your platform team already operates, who holds key rights, and whether the state backend itself restricts read access. Encryption protects the files, but it does not replace access control on the backend.

State encryption docs

Keep API credentials out of code and logs

The provider authenticates to the OpenSearch API, so its credentials can change indexes, templates and security objects. Pass them through a secrets manager or CI secret store, never through committed .tf files or terraform.tfvars. Mark sensitive variables and outputs so they are masked in plan output and CI logs. Ask whether your pipeline prints plan output to shared logs, and whether anyone can read job artifacts that include a saved plan file.

Least-privilege roles for the CI identity

The identity that runs apply should hold only the cluster permissions needed for the resources it manages. Use the Security plugin's role-based access control to map that identity to a backend role with narrow index patterns and cluster permissions, and keep administrative roles out of pipeline mappings. Review role mappings whenever a new resource type is added. Confirm that your audit logs record the CI identity's requests so changes made through the pipeline can be traced.

Separate state and credentials by environment

Development, staging and production should use separate state files, separate backends and separate OpenSearch credentials. A shared state file means a mistake in one workspace can modify production indexes or security objects. Map each environment to its own cluster, its own role mapping and its own secrets path. Ask who can approve production applies, and whether a lower environment's identity can reach production endpoints through network rules.

Require TLS for the API

The provider sends credentials and configuration over the OpenSearch REST API, so that traffic should use TLS. The Security plugin can enforce TLS for node and client traffic. Configure the provider to verify the cluster certificate against your internal certificate authority instead of disabling verification. Confirm certificate rotation dates with the platform team, since an expired certificate will break every pipeline run at once.

Common failures when managing OpenSearch with Terraform

This table lists the failures teams most often hit when they manage OpenSearch configuration as code, with the likely cause and the fix for each. Read it before the first apply against a production cluster, and use it to check your pipeline design. The main takeaway is that most failures come from ownership of changes, identity permissions, and state handling rather than from the provider itself.

FailureLikely causeFix
Plan shows drift on indexes, roles or policiesSomeone changed the object in OpenSearch Dashboards or the API outside TerraformPick one owner per resource, block UI edits to managed objects, and reconcile drift with a reviewed change instead of an ad hoc edit
Apply fails on TLS trust or certificate namesThe CA bundle does not match the cluster certificate chain, or the hostname in the endpoint is not in the certificate subject or SAN listPass the correct CA file, match the endpoint hostname to the certificate names, and confirm the chain with the cluster's own TLS settings before retrying
CI identity lacks permissions on the security indexThe pipeline user can call index APIs but has no role allowing changes to security configurationCreate a dedicated automation role scoped to the security resources it manages, map it to a service identity, and keep it separate from admin accounts
Secrets appear in plain text in stateResources such as user passwords or API keys store sensitive values in the state fileGenerate secrets outside Terraform or inject them from a secrets manager, restrict state access, and encrypt the remote backend
Provider and cluster version mismatch after an upgradeThe cluster moved to a new minor or major version while the provider or resource schema still targets the old APICheck the provider's supported versions before upgrading the cluster, upgrade the provider in a separate reviewed change, and test plans against a staging cluster first
Resources depend on remote state from another stackA stack reads outputs through terraform_remote_state, so moving it to a new tool or layout breaks the referencePlan the migration of the shared state consumers first, confirm the data source behavior in a test run, and cut over one dependent stack at a time

Questions buyers ask about Terraform-managed OpenSearch

What drives the cost and effort of managing OpenSearch with Terraform?

The main drivers are how many clusters you manage, how many roles, role mappings, index templates and ISM policies each cluster needs, how much hand-made configuration already exists, and how the state and CI pipeline are designed. Each cluster adds a set of resources to model and test, so effort grows with the number of environments, not just the number of clusters. Existing drift is often the largest unknown: every setting changed by hand in the OpenSearch API must be found, imported or removed before Terraform can own it. One-time costs cover design, module structure, importing current state and building the pipeline. Recurring costs cover reviewing changes, upgrading the provider and keeping modules aligned with OpenSearch releases. Ask any partner for a quote that lists these items separately, with the cluster and environment count written into the scope.

How long does a first Terraform rollout for OpenSearch take?

The duration depends on the number of clusters, the volume of existing configuration, and how much of the security model must be reproduced in code. A rollout that covers one non-production cluster with a small set of roles and templates is much shorter than one that brings several production clusters under code with existing drift. Plan time for an inventory of current roles, role mappings, index templates and ISM policies, a review of the security plugin settings, a pilot on a non-production cluster, and a controlled cutover. Each step depends on approvals from the security and platform teams. No duration is set in this page's sources, so ask for a dated plan with milestones in any written quote, and ask which steps the partner expects your team to perform.

What does the client team need to provide before the work starts?

The client team needs to provide access and decisions, not just a repository. Typically that includes:

  • Endpoints and credentials for each OpenSearch cluster, with a service account scoped to the Terraform run
  • The identity backend in use, such as SAML, OpenID Connect, LDAP or Active Directory, so role mappings match real groups
  • Naming conventions, environment layout and an owner for each role and policy
  • A state backend you approve, with encryption and access controls
  • A CI system where plans and applies will run, and who approves them
  • Change windows and a non-production cluster for testing

Also name the people who will review pull requests. Without them, the code will reflect the partner's assumptions rather than your access model.

Can an internal team manage OpenSearch with Terraform without a partner?

Yes, an internal team can do it if it has Terraform experience, OpenSearch security knowledge and time to build and test the modules. The harder parts are usually not the syntax but the security model: mapping roles to identity groups, deciding document and field level restrictions, and making sure a plan does not remove access that users depend on. Teams often underestimate the time needed to import existing configuration and to handle drift. A partner can be useful for the first design, the import and the pipeline, after which your team maintains the code. Decide early who owns each cluster's configuration, who reviews changes and how emergency manual changes are recorded and reconciled.

How do we move hand-made OpenSearch configuration into code?

Start with an inventory of what exists on each cluster: indexes, index templates, ISM policies, roles, role mappings, and the security configuration. Export the current definitions through the OpenSearch API, then decide which items Terraform should own. Import resources that are staying, rather than recreating them, because recreating a role can change access for users immediately. Remove or rename nothing until the plan shows no unexpected changes. Run plans against a non-production cluster first, and compare the output with what the cluster reports. Keep a record of every import and of the manual changes you chose to drop. After cutover, block direct edits in production or log them so they can be reconciled into code. Confirm the import behavior for each resource type in the provider documentation before you rely on it.

Can OpenTofu replace Terraform for managing OpenSearch?

OpenTofu is a candidate, and the OpenTofu website describes it as a drop-in replacement for Terraform that preserves existing workflows and configurations. It is licensed under the Mozilla Public License 2.0 and is under the Linux Foundation's stewardship. It was accepted to the CNCF at the Sandbox maturity level on April 23, 2025. Its FAQ states an aim of feature parity with Terraform, but compatibility with future Terraform releases is not guaranteed. Confirm that the OpenSearch provider you plan to use is published and tested for the OpenTofu version you choose, and check the provider's own documentation. The OpenTofu migration guide describes a process of backing up state and code, installing, initializing and verifying, then testing with a small change. It also warns that configurations using the terraform_remote_state data source need extra care. Include the choice of engine in the written scope so the team knows which version to pin.

How should Terraform state and CI be secured for OpenSearch?

State files often hold sensitive values, so treat them as a security asset. OpenTofu documents encryption of state and plan files at rest, for local storage and remote backends, with key providers including PBKDF2, AWS KMS, GCP KMS, OpenBao and Azure Vault. Choose a key provider that matches where your keys are managed, and restrict who can read the state backend. In CI, use short-lived credentials, separate plan and apply permissions, and require review before any change reaches production clusters. Keep the OpenSearch service account limited to the roles it needs. Ask for a written description of how state is stored, encrypted, backed up and accessed in any proposal.

How DeployOpen works on this

DeployOpen plans, implements, documents and supports self-hosted open-source platforms inside your own infrastructure, including the Kubernetes clusters or virtual machines where your OpenSearch runs. For Terraform-managed OpenSearch, we start from a written scope that names the indexes, templates, ISM policies, roles and role mappings your team needs, then build the code and its pipeline in your environment.

How we scope

  • Inventory existing indexes, templates, ISM policies, roles and role mappings that should move into code
  • Confirm whether the target is Amazon OpenSearch Service or self-managed clusters on Kubernetes or VMs
  • Agree which state backend, secrets handling and review workflow the written scope will cover
  • Confirm who owns the Terraform code, the provider version pin and the cluster admin credentials

How we build

  • Write Terraform modules for each resource type, with variables separating environments and clusters
  • Connect the configuration to your state backend and to CI so plans run on every change
  • Test changes against a non-production cluster before any apply reaches production
  • Import existing resources in controlled steps so live settings are not overwritten by surprise

How we hand over

  • Deliver the repository, module documentation and a runbook for planning, applying and rolling back changes
  • Document the security settings for roles and role mappings, so your security team can review them directly
  • Walk your platform and security engineers through the review process and drift detection routine
  • Provide a handover checklist that lists what the scope covered and what remains with your team

How we support

  • Ongoing support, provider version upgrades and continuous testing are available as retainers
  • Retainers can cover updates to modules when the OpenSearch release line or provider version changes
  • Support scope, response expectations and review cadence are written into the retainer before work starts
  • Ask for the retainer terms in writing alongside the fixed-scope quote for the initial build

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.