简体   繁体   English

如何将AWS托管策略附加到云形成和对流层中的角色

[英]How to attach an AWS managed policy to a role in cloudformation and troposphere

In my troposphere code i basically want to create an sns topic and a lambda execution role to which i can attach a few managed policy from aws. 在对流层代码中,我基本上想创建一个sns主题和一个lambda执行角色,可以将一些来自AWS的托管策略附加到该角色。 But the issue is i cannot find a way to just reference the arn name of the managed policy. 但是问题是我无法找到一种方法来仅引用托管策略的名称。 Below is my code but here i am copying and pasting the managed policy json document. 下面是我的代码,但是在这里我要复制并粘贴托管策略json文档。

Is there a better way out ? 有更好的出路吗?

from troposphere import FindInMap, GetAtt, Join, Output, Template, Ref, ImportValue
from troposphere.sns import Topic
from troposphere.iam import Role, Policy


t = Template()

t.set_version("2010-09-09")

sns_topic = Topic(TopicName='IngestStateTopic', title='IngestStateTopic')

t.add_resource(sns_topic)

LambdaExecutionRole = t.add_resource(
    Role(
        "LambdaExecutionRole",
        Path="/",
        Policies=[
            Policy(PolicyName="CloudWatchLogsFullAccess",
                   PolicyDocument={
                       "Version":
                       "2012-10-17",
                       "Statement": [{
                           "Action": ["logs:*"],
                           "Effect": "Allow",
                           "Resource": "*"
                       }]
                   }),
            Policy(PolicyName="SnsReadOnlyAccess",
                   PolicyDocument={
                       "Version":
                       "2012-10-17",
                       "Statement": [{
                           "Effect":
                           "Allow",
                           "Action": ["sns:GetTopicAttributes", "sns:List*"],
                           "Resource":
                           "*"
                       }]
                   }),
            Policy(PolicyName="LambdaBasicExecutionRole-Test",
                   PolicyDocument={
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "logs:CreateLogGroup",
            "Resource": "arn:aws:logs:eu-west-1:498129003450:*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "logs:CreateLogStream",
                "logs:PutLogEvents"
            ],
            "Resource": [
                "arn:aws:logs:eu-west-1:498129003450:log-group:/aws/lambda/lambda_layers_test:*"
            ]
        }
    ]
})
        ],
        AssumeRolePolicyDocument={
            "Version":
            "2012-10-17",
            "Statement": [{
                "Action": ["sts:AssumeRole"],
                "Effect": "Allow",
                "Principal": {
                    "Service": ["lambda.amazonaws.com"]
                }
            }]
        },
    ))

t.add_output(
    Output(
    "IngestServiceArn",
    Description="ARN of the sns topic",
    Value=Ref(sns_topic),
))

t.add_output(
    Output(
    "LambdaExcecutionRole",
    Description="ARN of the lambda plocy document",
    Value=GetAtt(LambdaExecutionRole, "Arn"),
))

with open('sns_lambda_role.yaml', 'w') as s:
    s.write(t.to_yaml())

And below is my cloud formation yaml file name: 以下是我的云形成yaml文件名:

AWSTemplateFormatVersion: '2010-09-09'
Outputs:
  IngestServiceArn:
    Description: ARN of the sns topic
    Value: !Ref 'IngestStateTopic'
  LambdaExcecutionRole:
    Description: ARN of the lambda plocy document
    Value: !GetAtt 'LambdaExecutionRole.Arn'
Resources:
  IngestStateTopic:
    Properties:
      TopicName: IngestStateTopic
    Type: AWS::SNS::Topic
  LambdaExecutionRole:
    Properties:
      AssumeRolePolicyDocument:
        Statement:
          - Action:
              - sts:AssumeRole
            Effect: Allow
            Principal:
              Service:
                - lambda.amazonaws.com
        Version: '2012-10-17'
      Path: /
      Policies:
        - PolicyDocument:
            Statement:
              - Action:
                  - logs:*
                Effect: Allow
                Resource: '*'
            Version: '2012-10-17'
          PolicyName: CloudWatchLogsFullAccess
        - PolicyDocument:
            Statement:
              - Action:
                  - sns:GetTopicAttributes
                  - sns:List*
                Effect: Allow
                Resource: '*'
            Version: '2012-10-17'
          PolicyName: SnsReadOnlyAccess
        - PolicyDocument:
            Statement:
              - Action: logs:CreateLogGroup
                Effect: Allow
                Resource: arn:aws:logs:eu-west-1:498129003450:*
              - Action:
                  - logs:CreateLogStream
                  - logs:PutLogEvents
                Effect: Allow
                Resource:
                  - arn:aws:logs:eu-west-1:498129003450:log-group:/aws/lambda/lambda_layers_test:*
            Version: '2012-10-17'
          PolicyName: LambdaBasicExecutionRole-Test
    Type: AWS::IAM::Role

You might want to look at the awacs project which allows for policy definition. 您可能需要查看允许策略定义的awacs项目。

Also, likely you need to just Ref() your policy to get the name of it. 同样,可能您只需要使用Ref()即可获取其名称。

You can do this by specifying a list of ManagedPolicyArns for Role cloudformation resource, but not the Policies - Documentation : 您可以通过指定的列表为此ManagedPolicyArns的角色cloudformation资源,而不是Policies - 文档

{
  "Type" : "AWS::IAM::Role",
  "Properties" : {
      "AssumeRolePolicyDocument" : Json,
      "ManagedPolicyArns" : [ String, ... ],
      "MaxSessionDuration" : Integer,
      "Path" : String,
      "PermissionsBoundary" : String,
      "Policies" : [ Policy, ... ],
      "RoleName" : String
    }
}

For ManagedPolicy CloudFormation has separate resource type - AWS::IAM::ManagedPolicy : 对于ManagedPolicy,CloudFormation具有单独的资源类型-AWS :: IAM :: ManagedPolicy

SampleManagedPolicy:
    Type: AWS::IAM::ManagedPolicy
    Properties:
      PolicyDocument:
        Version: "2012-10-17"
        Statement:
          -
            Sid: AllowAllUsersToListAccounts
            Effect: Allow
            Action:
              - iam:ListAccountAliases
              - iam:ListUsers
              - iam:GetAccountSummary
            Resource: "*

Examle: 考试:

RootRole:
    Type: 'AWS::IAM::Role'
    Properties:
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - ec2.amazonaws.com
            Action:
              - 'sts:AssumeRole'
      Path: /
      ManagedPolicyArns:
        - !Ref awsExampleManagedPolicyParameterOne            
        - !Ref awsExampleManagedPolicyParameterTwo

So, if we are talking about the tropopshere - it also has separate class for ManagedPolicy: 因此,如果我们在这里谈论tropops-它也具有ManagedPolicy的单独类:

class ManagedPolicy(AWSObject):
    resource_type = "AWS::IAM::ManagedPolicy"

    props = {
        'Description': (basestring, False),
        'Groups': ([basestring], False),
        'ManagedPolicyName': (basestring, False),
        'Path': (iam_path, False),
        'PolicyDocument': (policytypes, True),
        'Roles': ([basestring], False),
        'Users': ([basestring], False),
    }

And you refer to it using Ref function. 您可以使用Ref函数来Ref它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 boto3 列出附加到角色的 AWS 托管策略 - How to list AWS managed policy attached to a role using boto3 如何在 python boto3 中获取 iam 用户的 aws 托管策略的策略文档? - How to get policy document for aws managed policy of a iam user in python boto3? 如何为 python3 安装对流层? - How to install troposphere for python3? 无法删除 AWS 角色策略 - 使用 Boto3 的 NoSuchEntity - Unable to delete AWS Role Policy - NoSuchEntity with Boto3 嗨,我已经编写了一个代码来使用对流层创建 CloudFormation 模板在运行代码时出现语法错误 - Hi , i have written a code to create CloudFormation template using troposphere Getting Syntax error while running the code AWS cloudformation package 在 python - AWS cloudformation package in python 如何自定义AWS Codestar / Cloudformation模板以创建特定的代码构建项目? - How to customize AWS Codestar / Cloudformation template to create specific codebuild project? 如何从 AWS 策略文档中获取操作值并将其存储为列表? - How to fetch the action value from AWS policy document and store it as list? 如何通过 AWS CDK 将基于资源的策略添加到使用 AWS SAM 创建的 Lambda function? - How to add a resource based policy to a Lambda function created using AWS SAM via AWS CDK? 如何将HTTP请求中的文件附加到电子邮件? (Python / AWS Lambda) - How can I attach a file from an HTTP request to an email? (Python/ AWS Lambda)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM