python-3.x - 如何将 AWS 托管策略附加到 cloudformation 和对流层中的角色

标签 python-3.x amazon-web-services aws-cloudformation troposphere

在我的对流层代码中,我基本上想创建一个 sns 主题和一个 lambda 执行角色,我可以在其中附加一些来自 aws 的托管策略。但问题是我找不到一种方法来引用托管策略的 arn 名称。下面是我的代码,但我在这里复制并粘贴托管策略 json 文档。

还有更好的出路吗?

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())

下面是我的云形成 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

最佳答案

您可以通过为 Role cloudformation 资源指定 ManagedPolicyArns 列表(而不是 Policies)来完成此操作 - Documentation :

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

对于 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: "*

示例:

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

所以,如果我们谈论的是 tropopshere - 它也有单独的 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),
    }

并且您使用 Ref 函数引用它。

关于python-3.x - 如何将 AWS 托管策略附加到 cloudformation 和对流层中的角色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57376216/

相关文章:

python-2.7 - 什么是sys._MEIPASS

mysql - 在 aws 中将 hive 元数据数据库从 derby 更改为 RDS mysql 实例时出现问题

amazon-web-services - AWS 中长期运行的订阅后台服务的最佳位置

amazon-web-services - AWS CodePipeline 仅部署自上次部署以来已更改的文件,而不是简单地替换应用程序

amazon-web-services - 由于 cloudformation 语法错误,Elastic beanstalk 上的部署失败

python - 使用 Selenium 和 Python 禁用 Shockwave Flash 插件

python - matplotlib 不支持生成器作为输入

python - 模块未找到错误: No module named 'bs4' even after installing and re-installing

amazon-web-services - 为什么 Amazon 建议在 AWS IAM 资源名称中包含区域?

amazon-web-services - Cloudformation 蓝/绿部署 HealthCheckGracePeriodSeconds