# CUR (Cost and Usage report) role stack
# This stack is responsible for creating IAM role on the management (or trial) account
# This stack is created by parent CF stack https://cloudfix-templates.s3.amazonaws.com/cloudfix-onboarding.yaml
AWSTemplateFormatVersion: '2010-09-09'
Description: AWS Role to access CUR Report.
Parameters:
  ExternalId:
    Type: String
    Description: ExternalId
  CloudFixAccount:
    Type: String
    Description: CloudFix Account
  CloudFixSnsTopicName:
    Type: String
    Description: CloudFix SNS Topic Name
  TenantId:
    Type: String
    Description: TenantId
  IsTrial:
    Type: String
    AllowedValues: [
        "true",
        "false"
    ]
    Default: "false"
  Version:
    Type: String
    Description: StackVersion
  ResourceSuffix:
    Type: String
    Default: ''
    Description: CloudFormation resource suffix
  CentralizedStackEnabled:
    Type: String
    Description: Centralized Stack Enabled
  DatabaseName:
    Type: String
    Default: 'cloudfixdb'
    Description: Athena Database Name
  MainStackName:
    Type: String
    Default: ''
    Description: Name of the main deployed stack
Resources:
# CloudFix requires to run Athena queries on CUR bucket in order to find savings on the account
# Allows CloudFix AWS account to assume this role.
  CloudfixAthenaQueryExecutionRole:
    Type: 'AWS::IAM::Role'
    Properties:
# IAM definition to allow CloudFix account assume this role by providing correct ExternalId for the tenant
      AssumeRolePolicyDocument:
          Statement:
            - Action: 'sts:AssumeRole'
              Condition:
                StringEquals:
                  'sts:ExternalId': !Ref ExternalId
              Effect: Allow
              Principal:
                AWS: [
                  !Join ['', ['arn:', !Ref 'AWS::Partition', ':iam::', !Ref CloudFixAccount, ':role/cloudfix-finder-role-assume', !Ref ResourceSuffix]],
                  !Join ['', ['arn:', !Ref 'AWS::Partition', ':iam::', !Ref CloudFixAccount, ':role/cloudfix-finder-cur-role-assume', !Ref ResourceSuffix]],
                  !Join ['', ['arn:', !Ref 'AWS::Partition', ':iam::', !Ref CloudFixAccount, ':role/cloudfix-cur-role-assume', !Ref ResourceSuffix]],
                  !Join ['', ['arn:', !Ref 'AWS::Partition', ':iam::', !Ref CloudFixAccount, ':role/cloudfix-monitor-role-assume', !Ref ResourceSuffix]]
                ]
          Version: 2012-10-17
      MaxSessionDuration: 14400
      Policies:
          - PolicyDocument:
              Statement:
# S3 access to create a new CUR bucket and read the content
# cloudfix-cur-<account-id> bucket is created by https://cloudfix-templates.s3.amazonaws.com/cloudfix-cur.yaml
                - Action: 's3:*'
                  Effect: Allow
                  Resource:
                    - !Join
                      - ''
                      - - 'arn:aws:s3:::'
                        - 'cloudfix-cur-'
                        - !Ref 'AWS::AccountId'
                        - !Ref ResourceSuffix

                    - !Join
                      - ''
                      - - 'arn:aws:s3:::'
                        - 'cloudfix-cur-'
                        - !Ref 'AWS::AccountId'
                        - !Ref ResourceSuffix
                        - '/*'
# Allowing cloudfix to be able to detect when an account has been removed
# from an organization and to delete the account from our records.
                - Action:
                    - 'cloudformation:DescribeStacks'
                    - 'organizations:DescribeAccount'
                    - 'organizations:DescribeOrganization'
                    - 'organizations:ListAccounts'
                    - "organizations:ListAccountsForParent"
                    - "organizations:ListRoots"
                    - "organizations:DescribeOrganizationalUnit"
                    - "organizations:ListChildren"
                  Effect: Allow
                  Resource: '*'
# Allowing CloudFix to execute Athena queries using CloudFixWorkspace workgroup
# CloudFixWorkspace workgroup is created by https://cloudfix-templates.s3.amazonaws.com/cloudfix-cur.yaml
                - Action:
                    - 'athena:StartQueryExecution'
                    - 'athena:GetQueryExecution'
                    - 'athena:GetQueryResults'
                  Effect: Allow
                  Resource: !Join
                    - ''
                    - - 'arn:aws:athena:*:'
                      - !Ref 'AWS::AccountId'
                      - ':workgroup/CloudFixWorkspace'
                      - !Ref ResourceSuffix
# CloudFix do not have permission to update CloudFix cloudformation templates.
# Parent CF (https://cloudfix-templates.s3.amazonaws.com/cloudfix-onboarding.yaml) installs StackSet without any target deployment
# CreateStackInstances permission is required to onboard OUs (Organizational Units) from CloudFix UI
                - Action:
                    - 'cloudformation:CreateStackInstances'
                    - 'cloudformation:DescribeStackSetOperation'
                  Effect: Allow
                  Resource:
                    - !Join
                      - ''
                      - - 'arn:aws:cloudformation:*:'
                        - !Ref 'AWS::AccountId'
                        - ':stackset-target/*CloudFixOrgStackSet*'
                    - !Join
                      - ''
                      - - 'arn:aws:cloudformation:*:'
                        - !Ref 'AWS::AccountId'
                        - ':stackset/*CloudFixOrgStackSet*'
                - Action:
                    - 'cloudformation:CreateStackInstances'
                  Effect: Allow
                  Resource:
                    - 'arn:aws:cloudformation:us-east-1::type/resource/AWS-IAM-Role'
                    - 'arn:aws:cloudformation:us-east-1::type/resource/AWS-IAM-Group'
                    - 'arn:aws:cloudformation:us-east-1::type/resource/AWS-IAM-Policy'
                    - 'arn:aws:cloudformation:us-east-1::type/resource/AWS-CloudFormation-CustomResource'
                    - 'arn:aws:cloudformation:us-east-1::type/resource/AWS-S3-Bucket'
                    - 'arn:aws:cloudformation:us-east-1::type/resource/AWS-Lambda-Function'
# Glue permissions are required to create Athena DB from CUR s3 bucket
                - Action: 'glue:*'
                  Effect: Allow
                  Resource:
                    - !Join
                      - ''
                      - - 'arn:aws:glue:'
                        - !Ref 'AWS::Region'
                        - ':'
                        - !Ref 'AWS::AccountId'
                        - ':catalog'
                    - !Join
                      - ''
                      - - 'arn:aws:glue:'
                        - !Ref 'AWS::Region'
                        - ':'
                        - !Ref 'AWS::AccountId'
                        - ':database/'
                        - !Ref DatabaseName
                    - !Join
                      - ''
                      - - 'arn:aws:glue:'
                        - !Ref 'AWS::Region'
                        - ':'
                        - !Ref 'AWS::AccountId'
                        - ':table/'
                        - !Ref DatabaseName
                        - '/*'
                    - !Join
                      - ''
                      - - 'arn:aws:glue:'
                        - !Ref 'AWS::Region'
                        - ':'
                        - !Ref 'AWS::AccountId'
                        - ':userDefinedFunction/'
                        - !Ref DatabaseName
                        - '/*'
# In order to track the savings, CloudFix requires to update tags on CUR report
                - Action: 'ce:UpdateCostAllocationTagsStatus'
                  Effect: Allow
                  Resource: '*'
              Version: 2012-10-17
            PolicyName: core
      RoleName: !Join
        - ''
        - - cloudfix-athena-query-execution-role
          - !Ref ResourceSuffix
# Custom resource that sends the created IAM role and tenant parameters to CloudFix AWS account
# Properties passed to SNS and CloudFix stores these properties
  cloudfixmanagementaccountnotifier:
    Type: 'AWS::CloudFormation::CustomResource'
    Properties:
      ServiceToken: !Join
        - ''
        - - 'arn:'
          - !Ref 'AWS::Partition'
          - ':sns:'
          - !Ref 'AWS::Region'
          - ':'
          - !Ref CloudFixAccount
          - ':'
          - !Ref CloudFixSnsTopicName
      AccountId: !Ref 'AWS::AccountId'
      StackName: !Ref MainStackName
      OrganizationalRoleArn: !GetAtt
        - CloudfixAthenaQueryExecutionRole
        - Arn
      ExternalId: !Ref ExternalId
      TenantId: !Ref TenantId
      IsTrial: !Ref IsTrial
      Version: !Ref Version
      CentralizedStackEnabled: !Ref CentralizedStackEnabled
      StackRegion: !Ref 'AWS::Region'
      StackType: 'Main'
    UpdateReplacePolicy: Delete
