CloudFormation template to update the IAM Role's policy - aws-cloudformation

Is it possible to create a CloudFormation template that takes the IAM role's ARN as the input and updates its policy assigned to it to add more privileges?I tried to work with the CloudFormation designer but it is very confusing and not straightforward,

Yes, you can do this with a template such as this:
Description: Add policy to existing role
Parameters:
MyExistingRoleName:
Type: String
Description: Name of the Role you want to add a policy to
Resources:
MyNewPolicy:
Type: AWS::IAM::Policy
Properties:
PolicyName: "my-new-policy"
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- "s3:ListAllMyBuckets"
Resource:
- "*"
Roles:
- !Ref MyExistingRoleName

Related

Cloudformation Template - IAM Roles and Lambda Resource

I want to create a cloudformation stackset with resources like IAM and lambda in different regions. when I tried to deploy these resources, it failed because IAM roles are global and it is trying to create again in second region and whole stackset is failed.
Is there anyway I can mention the stackset to deploy GLobal Resources in one region and resources like lambda in all other regions?
Is there anyway I can mention the stackset to deploy GLobal Resources in one region and resources like lambda in all other regions?
Sadly there is not. You have to split your template, so that global resource are created as normal regional stacks.
I went through many resources and finally found a solution. If we split the template in stacksets then my dependent resources will break because creation is parallel in cloudformation. i.e. before global role gets created, lambda will try to get deployed and it will fail because the role is not available(required by lambda).
Hence we can add a condition to each of the global resources like below
Conditions:
RegionCheck: !Equals
- !Ref "AWS::Region"
- us-east-1
And, add the condition in the resources section as below,
Resources:
GlobalRolelambda:
Type: 'AWS::IAM::Role'
Condition: RegionCheck
Properties:
RoleName: !Ref LambdaExecutionRole
ManagedPolicyArns:
- 'arn:aws:iam::aws:policy/ReadOnlyAccess'
- 'arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole'
Path: /
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- 'sts:AssumeRole'
Policies:
- PolicyName: lambda-policy
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- 'glue:GetConnections'
- 'mediastore:ListContainers'
- 'mediastore:GetContainerPolicy'
Resource: '*'
But, after doing this, the problem would still exist because, if you add lambda resource with depends on attribute, role would get created in one region but not in the second region, lambda will fail to create in second region. We need to add a wait condition in the template to handle this as below Conditions:
CreateLambdaRole: !Equals [ !Ref LambdaRoleName, 'false' ]
CreateLamdaRoleRegion: !And
- !Condition RegionCheck
- !Condition CreateLambdaRole
and, add below resources after Role Resource,
CreateRoleWaitHandle:
Condition: CreateLamdaRoleRegion
DependsOn: GlobalRolelambda
Type: "AWS::CloudFormation::WaitConditionHandle"
#added, since DependsOn: !If is not possible, trigger by WaitCondition if CreateLamdaRoleRegion is false
WaitHandle:
Type: "AWS::CloudFormation::WaitConditionHandle"
#added, since DependsOn: !If is not possible
WaitCondition:
Type: "AWS::CloudFormation::WaitCondition"
Properties:
Handle: !If [CreateLamdaRoleRegion, !Ref CreateRoleWaitHandle, !Ref WaitHandle]
Timeout: "1"
Count: 0
and now, refer this in lambda resource,
lambdaProcessorFunction:
Type: AWS::Lambda::Function
Properties:
FunctionName: Lambda-processor
Description: ''
Handler: index.handler
Role:
Fn::Sub: 'arn:aws:iam::${AWS::AccountId}:role/LambdaExecutionRole'
Runtime: python3.6
Timeout: 600
MemorySize: 1024
Code:
S3Bucket: !Ref SourceBucketName
S3Key: !Ref SourceBucketKey
DependsOn: WaitCondition
Refer to the below source links, which might help
https://garbe.io/blog/2017/07/17/cloudformation-hacks/
CloudFormation, apply Condition on DependsOn

Run a crawler using CloudFormation template

This CloudFormation template works as expected and creates all the resources required by this article:
Data visualization and anomaly detection using Amazon Athena and Pandas from Amazon SageMaker | AWS Machine Learning Blog
But the WorkflowStartTrigger resource does not actually run the crawler. How do I run a crawler using the CloudFormation template?
Resources:
MyRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
-
Effect: "Allow"
Principal:
Service:
- "glue.amazonaws.com"
Action:
- "sts:AssumeRole"
Path: "/"
Policies:
-
PolicyName: "root"
PolicyDocument:
Version: "2012-10-17"
Statement:
-
Effect: "Allow"
Action: "*"
Resource: "*"
MyDatabase:
Type: AWS::Glue::Database
Properties:
CatalogId: !Ref AWS::AccountId
DatabaseInput:
Name: "dbcrawler123"
Description: "TestDatabaseDescription"
LocationUri: "TestLocationUri"
Parameters:
key1 : "value1"
key2 : "value2"
MyCrawler2:
Type: AWS::Glue::Crawler
Properties:
Description: example classifier
Name: "testcrawler123"
Role: !GetAtt MyRole.Arn
DatabaseName: !Ref MyDatabase
Targets:
S3Targets:
- Path: 's3://nytaxi162/'
SchemaChangePolicy:
UpdateBehavior: "UPDATE_IN_DATABASE"
DeleteBehavior: "LOG"
TablePrefix: test-
Configuration: "{\"Version\":1.0,\"CrawlerOutput\":{\"Partitions\":{\"AddOrUpdateBehavior\":\"InheritFromTable\"},\"Tables\":{\"AddOrUpdateBehavior\":\"MergeNewColumns\"}}}"
WorkflowStartTrigger:
Type: AWS::Glue::Trigger
Properties:
Description: Trigger for starting the Crawler
Name: StartTrigger
Type: ON_DEMAND
Actions:
- CrawlerName: "testcrawler123"
You should be able to do that by creating a custom resource attached to a lambda whereby the lambda actually does the action of starting the crawler. You should be able to even make it wait for the crawler to complete its execution
CloudFormation directly doesn't run crawlers, it just create them.
But you can create a schedule in order to run a crawler while defining trigger:
ScheduledJobTrigger:
Type: 'AWS::Glue::Trigger'
Properties:
Type: SCHEDULED
StartOnCreation: true
Description: DESCRIPTION_SCHEDULED
Schedule: cron(5 * * * ? *)
Actions:
- CrawlerName: "testcrawler123"
Name: ETLGlueTrigger
If needed to run crawler as part of CloudFormation stack creation, Lambda could be used.

How to call a resource from one yaml template to another yaml template using cloudformation

I need some guidance on cloudformation templates.
I have a stack called test1.yaml, there i created an IAM role called S3Role.
Now I have another stack called test2.yaml, there i created a managed policy to attach to existing iam role.
Now i want to call test1.yml file S3Role in test2.yml file of managed policy.
Can anyone help me with the script?
Can anyone help me with the script.
Obviously due to lack of details in your question, its not possible to provide any script. But I can provide general psudo-code.
test1.yaml
You will have to export the S3Role Arn or Name
Resources:
S3Role:
Type: IAM::ROLE
<rest of role definition>
Outputs:
RoleArn:
Value: !GetAtt S3Role.Arn
Exports:
Name: RoleArn
test2.yml
You will have to import the role exported Arn (or name) from test1.yaml:
Resources:
SomeResouce:
Properties:
Role: !ImportValue RoleArn
Hope this helps.
You need export the role from stack 1 and then import it in stack 2
https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-stack-exports.html
https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-importvalue.html
Providing the complete script for cross-referencing an AWS resource in CloudFormation template.
test1.yaml has an IAM role (logical ID: IAMRole) which we export through the Outputs block. Also notice that the indentation of Outputs block is same as that of Resources block.
The Outputs block serves many purposes. From the AWS Documentation
The optional Outputs section declares output values that you can
import into other stacks (to create cross-stack references), return in
response (to describe stack calls), or view on the AWS CloudFormation
console.
test1.yaml
Resources:
IAMRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Sid: TrustPolicy
Effect: Allow
Principal:
Service:
- ec2.amazonaws.com
Action: sts:AssumeRole
ManagedPolicyArns:
- arn:aws:iam::aws:policy/AmazonS3FullAccess
Path: /
RoleName: IAMRole
Outputs:
ExportIAMRole:
Description: Export the IAMRole to use in test2.yaml
Value: !Ref IAMRole
Export:
Name: IAMRole
In test2.yaml we import the value by referencing the name we have given under Export in Outputs block.
test2.yaml
Resources:
IAMPolicy:
Type: AWS::IAM::ManagedPolicy
Properties:
ManagedPolicyName: IAMPolicy
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- kms:ListAliases
- kms:Encrypt
- kms:Decrypt
Resource: "*"
Roles:
- !ImportValue IAMRole

ARN of the role that is automatically created with an Lambda function

In a SAM template, is there a way to reference the ARN of the role that is automatically created with an Lambda function?
I would need to use that ARN somewhere else in the template.
# this is the role
Role:
Type: AWS::IAM::Role
Properties:
RoleName: client-role
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: sts:AssumeRole
- Effect: Allow
Principal:
AWS: "arn:aws:iam::xxxx:role/xxxxxxx-ApiHandlerRole-12UWXALxxxxx"
Action: sts:AssumeRole
ManagedPolicyArns:
- arn:aws:iam::aws:policy/AmazonS3FullAccess
# this is the lambda
ApiHandler:
Type: AWS::Serverless::Function
Properties:
FunctionName: api-handler
......
Policies:
- DynamoDBCrudPolicy:
TableName: !Ref Table
- S3ReadPolicy:
BucketName: !Ref Bucket
- S3WritePolicy:
BucketName: !Ref Bucket
- Version: "2012-10-17"
Statement:
- Effect: Allow
Action: sts:AssumeRole
Resource: !GetAtt Role.Arn
I think what you do is separate the Resource build of the Role.
Then you can use the !Ref Role anywhere you need it, including in your lambda Role.
You can construct the ARN of the role yourself. It has fixed format. From docs:
If a role isn't specified, one is created for you with a logical ID of function-logical-idRole.
For example using Sub:
!Sub "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/function-logical-idRole"
where function-logical-id is your lambda function logical id.
Something like...
# this is the lambda
ApiHandler:
Type: AWS::Serverless::Function
Properties:
FunctionName: api-handler
Policies:
......
# this is the role
Role:
Type: AWS::IAM::Role
Properties:
RoleName: client-role
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: sts:AssumeRole
- Effect: Allow
Principal:
AWS: !GetAtt ApiHandlerRole.Arn
Action: sts:AssumeRole
ManagedPolicyArns:
- arn:aws:iam::aws:policy/AmazonS3FullAccess
Assuming that you have not specified the "AssumeRolePolicyDocument" for your function.
(code above based on the pastebin), the SAM cli will generate a role called "ApiHandlerRole" for you.
from the docs:
If this property isn't specified, AWS SAM adds a default assume role
for this function.
Which from the looks of it you may want to just explore that property some more. I'm new to AWS SAM but there has got to be way to plug "arn:aws:iam::aws:policy/AmazonS3FullAccess" at it. :)
Hope this helps all
docs link : https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-resource-function.html#sam-function-assumerolepolicydocument
SOLUTION:
So, I bumped into this situation today.
Suppose your Resource Lambda is named MyLambda, then use
!Ref MyLambdaRole.Arn
Tried and tested, works like a charm.
Reason why it works: If you expand the processed template, the IAM Role resource is named using the following nomenclature
<lambda-logical-id>Role
Don't forget to upvote! :D
What worked for me is refer the ARN Attribute of the autogenerated role like
SomeLambdaFunction:
Type: AWS::Serverless::Function
Properties:
...other properties...
Policies:
... Some sam policies...
.... different resource reference Lambda autogenerate role...
- Action: //some actions here
Effect: Allow
Principal:
AWS: !GetAtt SomeLambdaFunctionRole.Arn
Resource: "*"
.... More template code...

cross-referencing cloudformation not working

I have created a policy template and outputted the ARN:
Resources:
# Codebuild Policies
CodeBuildServiceRolePolicy1:
Type: AWS::IAM::ManagedPolicy
Properties:
Description: 'This service role enables AWS CodePipeline to interact with other AWS services, including AWS CodeBuild, on your behalf'
Path: "/"
PolicyDocument:
Version: "2012-10-17"
Statement:
- Resource: "*"
Effect: "Allow"
Action:
...
Outputs:
StackName:
Value: !Ref AWS::StackName
CodeBuildServiceRolePolicy:
Description: The ARN of the ManagedPolicy1
Value: !Ref CodeBuildServiceRolePolicy1
Export:
Name: !Sub '${EnvironmentName}-CodeBuildServiceRolePolicy1'
Now I want o import these Policy into a template with Roles and
# Codebuilding service role
CodeBuildRole:
Type: AWS::IAM::Role
Properties:
RoleName: !Sub ${EnvironmentName}-CodeBuildRole
AssumeRolePolicyDocument:
Statement:
- Action: ["sts:AssumeRole"]
Effect: Allow
Principal:
Service: [codebuild.amazonaws.com]
Version: "2012-10-17"
Path: /
Policies:
- PolicyDocument:
Fn::ImportValue:
!Sub ${EnvironmentName}-CodeBuildServiceRolePolicy1'
But this fails. I'm getting an error, what is wrong?
merci in advance
A
Have you tried to reference the Managed Policy you created with your first stack, using the !Ref function?
The CF for the policy:
AWSTemplateFormatVersion: "2010-09-09"
Resources:
CodeBuildServiceRolePolicy1:
Type: AWS::IAM::ManagedPolicy
Properties:
Path: "/"
PolicyDocument:
...
Outputs:
CodeBuildServiceRolePolicy:
Value: !Ref CodeBuildServiceRolePolicy1.Arn
The CF for the role:
AWSTemplateFormatVersion: "2010-09-09"
Parameters:
PolicyName:
Type: String
Resources:
CodeBuildRole:
Type: "AWS::IAM::Role"
Properties:
Path: "/"
Policies: !Ref PolicyName
Also checkout the docs for Cloudformation IAM an CloudFormation Functions
The solution is to use the AWS resource Type: AWS::IAM::ManagedPolicy instead of AWS::IAM::Policy .
If you use AWS::IAM::ManagedPolicy you can export the policy ARN like this
CodeBuildServiceRolePolicy:
Description: ARN of the managed policy
Value: !Ref CodeBuildServiceRolePolicy
and import it into another template with fn::ImportValue or fn::GetAtt
Using AWS::IAM::Policy only allows to create inline policies which cannot be referenced.