Проблема с вызовом AWS Lambda с использованием Cognito Identity Pool (terraform) - PullRequest
0 голосов
/ 02 апреля 2019

У меня проблема с терраформированием статической веб-страницы S3 в инфраструктуре AWS. Проблема в том, что я получаю следующий ответ:

{"__type":"InvalidIdentityPoolConfigurationException","message":"Invalid identity pool configuration. Check assigned IAM roles for this pool."}

В моей попытке создать простую функцию hello world, вызывающую функцию на статической веб-странице. Я почти уверен, что все сделал правильно, и симулятор также успешно прошел проверку с приложенной политикой.

Вот вам hello world index.html (до обработки шаблона для poolid):

    <html>
    <header><title>Hello world</title></header>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/aws-sdk/2.433.0/aws-sdk.js"></script>
    <body>
    Hello world
    <script>
        AWS.config.credentials = new AWS.CognitoIdentityCredentials({ IdentityPoolId: '${poolid}' }),
        AWS.config.region = 'eu-west-1';

        const lambda = new AWS.Lambda({region: 'eu-west-1'});
        const pullParams = {
          FunctionName : 'lambda-function',
          InvocationType : 'RequestResponse',
          LogType : 'None'
        };

        lambda.invoke(pullParams, console.log);
    </script>
    </body>
    </html>

Вот terraform для модели пула идентичности:

resource "aws_cognito_identity_pool" "main" {
  identity_pool_name               = "Some identity pool"
  allow_unauthenticated_identities = true
}

resource "aws_iam_role" "authenticated" {
  name = "cognito_authenticated"

  assume_role_policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": "sts:AssumeRole",
      "Principal": {
        "Federated": "cognito-identity.amazonaws.com"
      },
      "Effect": "Allow",
      "Sid": ""
    }
  ]
}
EOF
}

resource "aws_iam_role" "unauthenticated" {
  name = "cognito_unauthenticated"

  assume_role_policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": "sts:AssumeRole",
      "Principal": {
        "Federated": "cognito-identity.amazonaws.com"
      },
      "Effect": "Allow",
      "Sid": ""
    }
  ]
}
EOF
}

resource "aws_iam_role_policy_attachment" "authenticated" {
  role       = "${aws_iam_role.authenticated.name}"
  policy_arn = "arn:aws:iam::aws:policy/AWSLambdaFullAccess"
}

resource "aws_iam_role_policy_attachment" "unauthenticated" {
  role       = "${aws_iam_role.unauthenticated.name}"
  policy_arn = "arn:aws:iam::aws:policy/AWSLambdaFullAccess"
}


resource "aws_cognito_identity_pool_roles_attachment" "main" {
  identity_pool_id = "${aws_cognito_identity_pool.main.id}"

  roles = {
    "authenticated" = "${aws_iam_role.authenticated.arn}"
    "unauthenticated" = "${aws_iam_role.unauthenticated.arn}"
  }
}

Наконец, терраформа для самой лямбды:

data "archive_file" "lambda_zip" {
    type        = "zip"
    source_dir  = "function"
    output_path = "function.zip"
}

resource "aws_iam_role" "main" {
  name               = "lambda-role"

  assume_role_policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": "sts:AssumeRole",
      "Principal": {
        "Service": "lambda.amazonaws.com"
      },
      "Effect": "Allow",
      "Sid": ""
    }
  ]
}
EOF
}

resource "aws_iam_role_policy_attachment" "lamba_exec_role_eni" {
  role       = "${aws_iam_role.main.name}"
  policy_arn = "arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole"
}

resource "aws_security_group" "lambda_security_group" {
  name          = "lambda_security_group"
  description   = "Security group for lambdas"
  vpc_id        = "${var.vpcid}"
  ingress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

resource "aws_lambda_function" "main" {
  depends_on    = ["aws_iam_role_policy_attachment.lamba_exec_role_eni"]

  filename      = "function.zip"
  function_name = "lambda-function"
  role          = "${aws_iam_role.main.arn}"
  handler       = "handler.hello"
  runtime       = "nodejs8.10"
  source_code_hash = "${data.archive_file.lambda_zip.output_base64sha256}"
  vpc_config {
    subnet_ids         =  ["${split(",", var.subnetids)}"]
    security_group_ids =  ["${aws_security_group.lambda_security_group.id}"]
  }
}

У кого-нибудь есть совет, что я здесь не так делаю?

...