AWSTemplateFormatVersion: '2010-09-09'
Description: >
  Adds read-only AWS Sustainability permissions to an existing OneLens IAM role,
  so that OneLens can read your estimated carbon emissions and water withdrawals.
  Deploy this in the same AWS account that holds the OneLens role. For consolidated
  reporting across an organization, that is your management (payer) account.
  IAM is a global service, so the region you deploy in does not matter.

Metadata:
  AWS::CloudFormation::Interface:
    ParameterGroups:
      - Label:
          default: "Existing OneLens role"
        Parameters:
          - OneLensRoleName
    ParameterLabels:
      OneLensRoleName:
        default: "OneLens IAM role name"

Parameters:
  OneLensRoleName:
    Type: String
    Description: >
      The name of the IAM role you created when you connected this account to OneLens.
      Use the role name only, not the full ARN. For example: OneLens-A1B2C3D4E5
    MinLength: 1
    MaxLength: 64
    AllowedPattern: "[\\w+=,.@-]+"
    ConstraintDescription: >
      Must be an IAM role name, not an ARN. Allowed characters are letters, numbers
      and the symbols _ + = , . @ -

Resources:
  OneLensSustainabilityPolicy:
    Type: 'AWS::IAM::ManagedPolicy'
    Properties:
      ManagedPolicyName: !Sub 'OneLensSustainabilityPolicy-${AWS::StackName}'
      Description: 'Read-only access to AWS Sustainability carbon emissions and water withdrawals data for OneLens'
      PolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Sid: 'AllowSustainabilityRead'
            Effect: Allow
            Action:
              - sustainability:GetEstimatedCarbonEmissions
              - sustainability:GetEstimatedCarbonEmissionsDimensionValues
              - sustainability:GetEstimatedWaterAllocation
              - sustainability:GetEstimatedWaterAllocationDimensionValues
            Resource: '*'
      Roles:
        - !Ref OneLensRoleName

Outputs:
  ManagedPolicyArn:
    Description: 'ARN of the managed policy created and attached to the OneLens role'
    Value: !Ref OneLensSustainabilityPolicy
  AttachedToRole:
    Description: 'The IAM role the policy was attached to'
    Value: !Ref OneLensRoleName
