---
type: api
title: Create or update role mappings
description: **All methods and paths for this operation:**
url: https://www.elastic.co/elastic/docs-builder/docs/4371/api/doc/elasticsearch/v8/operation/operation-security-put-role-mapping
resource: https://www.elastic.co/elastic/docs-builder/docs/4371/api/doc/elasticsearch/v8/operation/operation-security-put-role-mapping
products:
  - Elasticsearch
---

# Create or update role mappings


Availability: 5.5+

## Paths

- `POST` (also `PUT`) `/_security/role_mapping/{name}`

- [Api key auth](/elastic/docs-builder/docs/4371/api/doc/elasticsearch/v8/authentication#apikeyauth)
- [Basic auth](/elastic/docs-builder/docs/4371/api/doc/elasticsearch/v8/authentication#basicauth)
- [Bearer auth](/elastic/docs-builder/docs/4371/api/doc/elasticsearch/v8/authentication#bearerauth)

#### Path Parameters

- `name` (string Name)
  The distinct name that identifies the role mapping.
The name is used solely as an identifier to facilitate interaction via the API; it does not affect the behavior of the mapping in any way.

## Description

Role mappings define which roles are assigned to each user.
Each mapping has rules that identify users and a list of roles that are granted to those users.
The role mapping APIs are generally the preferred way to manage role mappings rather than using role mapping files. The create or update role mappings API cannot update role mappings that are defined in role mapping files.

NOTE: This API does not create roles. Rather, it maps users to existing roles.
Roles can be created by using the create or update roles API or roles files.

**Role templates**

The most common use for role mappings is to create a mapping from a known value on the user to a fixed role name.
For example, all users in the `cn=admin,dc=example,dc=com` LDAP group should be given the superuser role in Elasticsearch.
The `roles` field is used for this purpose.

For more complex needs, it is possible to use Mustache templates to dynamically determine the names of the roles that should be granted to the user.
The `role_templates` field is used for this purpose.

NOTE: To use role templates successfully, the relevant scripting feature must be enabled.
Otherwise, all attempts to create a role mapping with role templates fail.

All of the user fields that are available in the role mapping rules are also available in the role templates.
Thus it is possible to assign a user to a role that reflects their username, their groups, or the name of the realm to which they authenticated.

By default a template is evaluated to produce a single string that is the name of the role which should be assigned to the user.
If the format of the template is set to "json" then the template is expected to produce a JSON string or an array of JSON strings for the role names.

## Required authorization

* Cluster privileges: `manage_security`

[Read the reference documentation](https://www.elastic.co/guide/en/elasticsearch/reference/8.19/mapping-roles.html)

## Query String Parameters

- `refresh` (enum Refresh)
  If `true` (the default) then refresh the affected shards to make this operation visible to search, if `wait_for` then wait for a refresh to make this operation visible to search, if `false` then do nothing with refreshes.
  Values: `true`, `false`, `wait_for`

## Request Body

`application/json`

- `enabled` (boolean) — optional
  Mappings that have `enabled` set to `false` are ignored when role mapping is performed.
- `metadata` (Metadata) — optional
  Additional metadata that helps define which roles are assigned to each user.
Within the metadata object, keys beginning with `_` are reserved for system usage.
- `roles` ([] string) — optional
  A list of role names that are granted to the users that match the role mapping rules.
Exactly one of `roles` or `role_templates` must be specified.
- `role_templates` ([] RoleTemplate) — optional
  A list of Mustache templates that will be evaluated to determine the roles names that should granted to the users that match the role mapping rules.
Exactly one of `roles` or `role_templates` must be specified.
  - `format` (enum TemplateFormat) — optional
    Values: `string`, `json`
  - `template` (string Script) — required
- `rules` ({} RoleMappingRule) — optional
  The rules that determine which users should be matched by the mapping.
A rule is a logical condition that is expressed by using a JSON DSL.
  - `any` ([] RoleMappingRule) — optional — recursive
    Same fields as `rules`
  - `all` ([] RoleMappingRule) — optional — recursive
    Same fields as `rules`
  - `field` ({} FieldRule) — optional
    - `username` (string Names) — optional
    - `dn` (string Names) — optional
    - `groups` (string Names) — optional
  - `except` ({} RoleMappingRule) — optional — recursive
    Same fields as `rules`
- `run_as` ([] string) — optional

## Response

`application/json`

- `created` (boolean)
- `role_mapping` ({} CreatedStatus)
  - `created` (boolean)
## Code Examples

#### Console

```console
POST /_security/role_mapping/mapping1
{
  "roles": [ "user"],
  "enabled": true, 
  "rules": {
    "field" : { "username" : "*" }
  },
  "metadata" : { 
    "version" : 1
  }
}
```

#### JavaScript

```javascript
const response = await client.security.putRoleMapping({
  name: "mapping1",
  roles: ["user"],
  enabled: true,
  rules: {
    field: {
      username: "*",
    },
  },
  metadata: {
    version: 1,
  },
});
```

#### Python

```python
resp = client.security.put_role_mapping(
    name="mapping1",
    roles=[
        "user"
    ],
    enabled=True,
    rules={
        "field": {
            "username": "*"
        }
    },
    metadata={
        "version": 1
    },
)
```

#### curl

```curl
curl -X POST "$ELASTICSEARCH_URL/_security/role_mapping/mapping1" \
  -H "Authorization: ApiKey $ELASTIC_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "roles": [
      "user"
    ],
    "enabled": true,
    "rules": {
      "field": {
        "username": "*"
      }
    },
    "metadata": {
      "version": 1
    }
  }'
```

#### Java

```java
client.security().putRoleMapping(p -> p
    .enabled(true)
    .metadata("version", JsonData.fromJson("1"))
    .name("mapping1")
    .roles("user")
    .rules(r -> r
        .field(NamedValue.of("username",List.of(FieldValue.of("*"))))
    )
);
```

#### C#

```c#
var response = await client.Security
    .PutRoleMappingAsync(name: "mapping1", d1 => d1
        .Enabled(true)
        .Metadata(new Dictionary<string, object>()
        {
            { "version", 1 }
        })
        .Roles("user")
        .Rules(d2 => d2
            .Field(d3 => d3
                .Username(new[] { "*" })
            )
        )
    );
```

#### PHP

```php
$resp = $client->security()->putRoleMapping([
    "name" => "mapping1",
    "body" => [
        "roles" => array(
            "user",
        ),
        "enabled" => true,
        "rules" => [
            "field" => [
                "username" => "*",
            ],
        ],
        "metadata" => [
            "version" => 1,
        ],
    ],
]);
```

#### Ruby

```ruby
response = client.security.put_role_mapping(
  name: "mapping1",
  body: {
    "roles": [
      "user"
    ],
    "enabled": true,
    "rules": {
      "field": {
        "username": "*"
      }
    },
    "metadata": {
      "version": 1
    }
  }
)
```

## Response Examples

#### Security put role mapping response example1

A successful response from `POST /_security/role_mapping/mapping1`.

```json
{
  "role_mapping" : {
    "created" : true 
  }
}
```

