# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# Permission is hereby granted, free of charge, to any person obtaining a copy of this
# software and associated documentation files (the "Software"), to deal in the Software
# without restriction, including without limitation the rights to use, copy, modify,
# merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

AWSTemplateFormatVersion: '2010-09-09'
Description: Create an IAM role needed for the cur-automator and server-ids automator solution.

Resources:

# CUR Automator IAM
  CostAndUsageIAMRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: map-cur-automator
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - lambda.amazonaws.com
            Action:
              - sts:AssumeRole
      Description: IAM Role for cost and usage report lambda function
      ManagedPolicyArns:
        - !Sub arn:${AWS::Partition}:iam::aws:policy/job-function/Billing
        - !Sub arn:${AWS::Partition}:iam::aws:policy/AWSOrganizationsReadOnlyAccess
      Path: /
      Policies:
        # Allow GetObject for all files in the CUR bucket
        - PolicyName: AmazonS3ReadOnlyAccessCostAndUsageS3Bucket
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Effect: Allow
                Action:
                  - s3:GetObject
                  - s3:ListBucket
                Resource:
                  - !Sub 'arn:${AWS::Partition}:s3:::cur-bucket-map-${AWS::AccountId}/*'
                  - !Sub 'arn:${AWS::Partition}:s3:::cur-bucket-map-${AWS::AccountId}'
        # Allow GetBucketTagging on all S3 buckets for the account which could be existing buckets selected for CUR
        - PolicyName: AmazonS3GetBucketTagging
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Effect: Allow
                Action: 
                  - s3:GetBucketTagging
                Resource:
                  - !Sub 'arn:${AWS::Partition}:s3:::*'
        # Allow Lambda to write to its specific log group
        - PolicyName: LambdaExecutionRoleForLogGroup
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Effect: Allow
                Action:
                  - logs:CreateLogStream
                  - logs:PutLogEvents
                Resource:
                  - !Sub 'arn:${AWS::Partition}:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/mapAutomator-CostAndUsageSetup:*'

# Server Ids Automator IAM
  ServerIdsAutomatorIAMRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: map-server-ids-automator
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - lambda.amazonaws.com
            Action:
              - sts:AssumeRole
      Description: IAM Role for the Server IDs automator lambda function
      Path: /
      Policies:
        # Allow Lambda to write to its specific log group
        - PolicyName: LambdaExecutionRoleForLogGroup
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Effect: Allow
                Action: 
                  - logs:CreateLogStream
                  - logs:PutLogEvents
                Resource:
                  - !Sub 'arn:${AWS::Partition}:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/mapAutomator-ServerIdsAutomator:*'
        # Allow GetObject for all files in the Originating IDs bucket
        - PolicyName: MapServerIdsAutomatorMigrationHubInOutS3BucketAccess
          PolicyDocument: 
            Version: '2012-10-17'
            Statement:
            - Effect: Allow
              Action: 
              - s3:PutObject
              - s3:GetObject
              Resource:
              - !Sub arn:${AWS::Partition}:s3:::migration-hub-inventory-bucket-${AWS::AccountId}/*

        # Allow GetBucketTagging for all files in the CUR bucket
        - PolicyName: MapServerIdsAutomatorCURS3BucketAccess
          PolicyDocument: 
            Version: '2012-10-17'
            Statement:
            - Effect: Allow
              Action: 
              - s3:GetBucketTagging
              - s3:PutBucketTagging
              Resource:
              - !Sub arn:${AWS::Partition}:s3:::cur-bucket-map-${AWS::AccountId}

        # Allow the Originating IDs Automator to upload the server inventory and download the inventory.
        # The Application Discovery Services does not support specifying a specific ARN in the resource section of the policy.
        # See: https://docs.aws.amazon.com/application-discovery/latest/userguide/security_iam_service-with-iam.html
        - PolicyName: MapServerIdsAutomatorMigrationHubAccess
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
            - Effect: Allow
              Action: 
              - discovery:DescribeExportTasks
              - discovery:StartImportTask
              - discovery:StartExportTask
              - discovery:GetDiscoverySummary
              - discovery:CreateTags
              - mgh:GetHomeRegion
              - mgh:CreateHomeRegionControl
              - discovery:ListConfigurations
              - discovery:CreateApplication
              - discovery:UpdateApplication
              - discovery:AssociateConfigurationItemsToApplication
              - discovery:DisassociateConfigurationItemsFromApplication
              Resource:
              - '*'

Outputs:
  CostAndUsageIAMRoleArn:
    Value: !GetAtt CostAndUsageIAMRole.Arn

  ServerIdsAutomatorIAMRoleArn:
    Value: !GetAtt ServerIdsAutomatorIAMRole.Arn
  