How to set up IAM role to access AWS OpenSearch Service domain through terraform

278 Views Asked by At

I have an OpenSearch domain deployed in AWS and want to manage it through Terraform provider. I have the following provider block. How do I set up an IAM role that can be used to access this domain through Terraform?

provider "opensearch" {
  aws_region = "<region>"
  aws_profile = "<profile>"
  healthcheck = true
  url = "<domain_url>"
  sign_aws_requests = false
  aws_assume_role_arn = "<role_arn>"
}

I have tried by creating a role with the following trust policy and admin privileges, and added this role to the provider.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "Service": "es.amazonaws.com",
                "AWS": "arn:aws:iam::<account_no>:root"
            },
            "Action": "sts:AssumeRole",
            "Condition": {}
        }
    ]
}

But this does not work and gives me │ Error: elastic: Error 401 (Unauthorized) when I do terraform apply.

1

There are 1 best solutions below

0
On

To create an IAM policy for OpenSearch using Terraform, you can use the aws_iam_policy_document data source to define the policy and then attach it to an IAM role using the aws_iam_role_policy resource. This approach allows you to leverage Terraform's error checking and flexibility in managing IAM policies.

Consider this example for your reference:

    data "aws_iam_policy_document" "opensearch_policy" {
 version = "2012-10-17"

 statement {
    actions = [
      "es:ESHttp*",
      "es:Describe*",
      "es:ListDomainNames",
      "es:ListTags"
    ]

    resources = [
      "arn:aws:es:<region>:<account_id>:domain/<domain_name>/*"
    ]

    effect = "Allow"
 }
}

resource "aws_iam_role_policy" "opensearch_role_policy" {
 name   = "opensearch_role_policy"
 role   = aws_iam_role.example_role.id
 policy = data.aws_iam_policy_document.opensearch_policy.json
}