locals {
{% if workspace != "common" %}
  {{ ms_name }}_role_arn = data.aws_iam_role.{{ ms_name }}_cws.arn
{% else %}
  {{ ms_name }}_role_arn = aws_iam_role.{{ ms_name }}_cws.arn
{% endif %}
}

# ---------------------------------------------------------------------------------------------------------------------
# ROLE
# ---------------------------------------------------------------------------------------------------------------------

{% if workspace != "common" %}
data "aws_iam_role" "{{ ms_name }}_cws" {
  provider = aws.{{ ms_name }}
  name = "{{ ms_name }}_cws_role"
}
{% else %}
resource "aws_iam_role" "{{ ms_name }}_cws" {
  provider = aws.{{ ms_name }}
  name = "{{ ms_name }}_cws_role"

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

resource "aws_iam_role_policy_attachment" "{{ ms_name }}_s3" {
  provider = aws.{{ ms_name }}
  role = aws_iam_role.{{ ms_name }}_cws.name
  policy_arn = "arn:aws:iam::aws:policy/AmazonS3FullAccess"
}

resource "aws_iam_role_policy_attachment" "{{ ms_name }}_cloud_watch" {
  provider = aws.{{ ms_name }}
  role = aws_iam_role.{{ ms_name }}_cws.name
  policy_arn = "arn:aws:iam::aws:policy/service-role/AmazonAPIGatewayPushToCloudWatchLogs"
}

resource "aws_iam_role_policy_attachment" "{{ ms_name }}_xray" {
  provider = aws.{{ ms_name }}
  role = aws_iam_role.{{ ms_name }}_cws.name
  policy_arn = "arn:aws:iam::aws:policy/AWSXrayFullAccess"
}

resource "aws_iam_role_policy" "{{ ms_name }}_vpc" {
  provider = aws.{{ ms_name }}
  name = "{{ ms_name }}_vpc"
  role = aws_iam_role.{{ ms_name }}_cws.name
  policy = jsonencode({
    Version: "2012-10-17",
    Statement: [
      {
        Effect: "Allow",
        Action: [
          "ec2:CreateNetworkInterface",
          "ec2:DescribeNetworkInterfaces",
          "ec2:DeleteNetworkInterface"
        ],
        Resource: "*"
      }
    ]
  })
}
{% endif %}

