Using Cloudformation Sub Function To Create And Pass through Role Arns

Using Cloudformation Sub Function To Create And Pass through Role Arns

Recently I needed to create a role for media convert using Cloudfomration I also needed to pass that role through to my Lamdba NoddeJS fucntion within environmetal varibles.

At first I thought you would need to use the GetAttr function like this.

"CloudfrontUrl": {
    "Description": "Cloudfront Url",
    "Value": {
        "Fn::GetAtt": ["CreateWebsiteCloudFront", "DomainName"]
    }
}

Turns out this is not the case you can simply use the sub function and insert the AWS Account Id like this.

"MediaConvertRole": {
    "Description": "Role Used To Encode Your Media",
    "Value": {
        "Fn::Sub": "arn:aws:iam::${AWS::AccountId}:role/MediaConvertRole"
    }
}

When creating a role with Cloudformation make sure you give it a role name else it will create one with an appended random id.

"MediaConvertRole": {
    "Type": "AWS::IAM::Role",
    "Properties": {
        "RoleName": "MediaConvertRole",
        "AssumeRolePolicyDocument": {
            "Version": "2012-10-17",
            "Statement": [{
                "Effect": "Allow",
                "Principal": {
                    "Service": ["mediaconvert.amazonaws.com"]
                },
                "Action": ["sts:AssumeRole"]
            }]
        },
        "Path": "/",
        "Policies": [{
                "PolicyName": "Media_S3_Full",
                "PolicyDocument": {
                    "Version": "2012-10-17",
                    "Statement": [{
                        "Effect": "Allow",
                        "Action": "s3:*",
                        "Resource": "*"
                    }]
                }
            },
            {
                "PolicyName": "Media_Api_Invoke",
                "PolicyDocument": {
                    "Version": "2012-10-17",
                    "Statement": [{
                        "Effect": "Allow",
                        "Action": ["execute-api:Invoke"],
                        "Resource": "arn:aws:execute-api:*:*:*"
                    }]
                }
            }
        ]
    }
}

Leave a comment