Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an ec2 instance along with IAM roles using cloud formation

I'm very new to Amazon cloudformation technique. I'm trying to launch an ec2 instance along with the IAM roles.

I have cloudformation script for this. But the problem I face is the IAM roles and Ec2 instances are created, but they aren't tied with each other.

I did create the IAM-roles using AWS::IAM::Role and AWS::IAM::InstanceProfile.

Is there any other command that I should use?

Thanks in advance.

like image 631
sriram Avatar asked Dec 04 '22 00:12

sriram


1 Answers

Had to dig to get the final result, but here's an example of

  1. Defining an access role (this will allow the EC2 instance to step into / assume to role),
  2. Defining a policy for the role (i.e. when the EC2 assumes the role, what resources does it have access to),
  3. Defining the instance profile (that is referenced by the EC2 instance, and has the access role mapped in)

    "S3AccessRole" : {
        "Type"  : "AWS::IAM::Role",
        "Properties" : {
            "AssumeRolePolicyDocument" : {
                "Statement" : [ {
                    "Effect" : "Allow",
                    "Principal" : {
                        "Service" : [ "ec2.amazonaws.com" ]
                    },
                    "Action" : [ "sts:AssumeRole" ]
                } ]
            },
            "Path" : "/"
        }
    },
    
    "S3RolePolicies" : {
        "Type" : "AWS::IAM::Policy",
        "Properties" : {
            "PolicyName" : "s3access",
            "PolicyDocument" : {
                "Statement" : [ {
                    "Effect" : "Allow",
                    "Action" : "s3:*",
                    "Resource" : "*"
                }]
            },
            "Roles" : [ { "Ref" : "S3AccessRole" } ]
        }
    },
    
    "S3InstanceProfile" : {
        "Type" : "AWS::IAM::InstanceProfile",
        "Properties" : {
            "Path" : "/",
            "Roles" : [ { "Ref" : "S3AccessRole" } ]
        }
    }
    

The policy above allows all access to s3 resources. Adjust according to your needs. The IamInstanceProfile reference in the EC2 instance properties would refer be { "Ref" : "S3InstanceProfile" }

Note that as of May 2015, when you creating a stack that creates IAM roles, you need to check a box acknowledging such creation, otherwise you'll get a "Stack creation error: Requires capabilities : [CAPABILITY_IAM]" error.

like image 114
Brett Avatar answered May 15 '23 12:05

Brett