コード例 #1
0
    def create_template(self):
        """Create template (main function called by Stacker)."""
        template = self.template
        # variables = self.get_variables()
        template.add_version('2010-09-09')
        template.add_description('Static Website - Dependencies')

        # Resources
        awslogbucket = template.add_resource(
            s3.Bucket('AWSLogBucket',
                      AccessControl=s3.Private,
                      VersioningConfiguration=s3.VersioningConfiguration(
                          Status='Enabled')))
        template.add_output(
            Output('AWSLogBucketName',
                   Description='Name of bucket storing AWS logs',
                   Value=awslogbucket.ref()))

        template.add_resource(
            s3.BucketPolicy(
                'AllowAWSLogWriting',
                Bucket=awslogbucket.ref(),
                PolicyDocument=Policy(
                    Version='2012-10-17',
                    Statement=[
                        Statement(
                            Action=[awacs.s3.PutObject],
                            Effect=Allow,
                            Principal=AWSPrincipal(
                                Join(':',
                                     ['arn:aws:iam:', AccountId, 'root'])),
                            Resource=[
                                Join('', [
                                    'arn:aws:s3:::',
                                    awslogbucket.ref(), '/*'
                                ])
                            ])
                    ])))
        artifacts = template.add_resource(
            s3.Bucket(
                'Artifacts',
                AccessControl=s3.Private,
                LifecycleConfiguration=s3.LifecycleConfiguration(Rules=[
                    s3.LifecycleRule(NoncurrentVersionExpirationInDays=90,
                                     Status='Enabled')
                ]),
                VersioningConfiguration=s3.VersioningConfiguration(
                    Status='Enabled')))
        template.add_output(
            Output('ArtifactsBucketName',
                   Description='Name of bucket storing artifacts',
                   Value=artifacts.ref()))
コード例 #2
0
ファイル: admin_role.py プロジェクト: onicagroup/runway
 def assume_role_policy(self) -> PolicyDocument:
     """Assume role policy document."""
     policy_doc = PolicyDocument(Statement=[], Version="2012-10-17")
     if self.variables.get("CrossAccountAccessAccountIds"):
         policy_doc.Statement.append(
             Statement(
                 Action=[awacs.sts.AssumeRole],
                 Effect=Allow,
                 Principal=AWSPrincipal(
                     self.variables["CrossAccountAccessAccountIds"]
                 ),
             )
         )
     return policy_doc
コード例 #3
0
def kms_key_root_statements():
    root_arn = Join(":", ["arn:aws:iam:", Ref("AWS::AccountId"), "root"])

    return [
        Statement(
            Sid="Enable IAM User Permissions",
            Effect=Allow,
            Principal=AWSPrincipal(root_arn),
            Action=[
                awacs.kms.Action("*"),
            ],
            Resource=["*"]
        )
    ]
コード例 #4
0
    def add_ecr_repository(self, title, repo_name):
        '''
        Add ECR repository to template

        Args:
            title: logical resources name
            repo_name: target repository name
        '''
        self.cfn_template.add_resource(
            Repository(title=title,
                       RepositoryName=Ref(repo_name),
                       RepositoryPolicyText=PolicyDocument(
                           Version='2012-10-17',
                           Statement=[
                               Statement(Sid='AllowPushPull',
                                         Effect=Allow,
                                         Action=[Action('ecr', '*')],
                                         Principal=AWSPrincipal('*'))
                           ])))
        return self.cfn_template
コード例 #5
0
 def create_s3_bucket(self):
     t = self.template
     bucket_name = self.local_parameters['BucketName']
     t.add_resource(s3.Bucket(
         BUCKET,
         BucketName=bucket_name,
     ), )
     t.add_resource(
         s3.BucketPolicy(
             BUCKET_POLICY,
             Bucket=Ref(BUCKET),
             PolicyDocument=Policy(Statement=[
                 Statement(
                     Effect=Allow,
                     Action=[awacs.s3.GetObject],
                     Resource=[
                         awacs.s3.ARN(os.path.join(bucket_name, '*'))
                     ],
                     Principal=AWSPrincipal(Everybody),
                 )
             ], ),
         ), )
コード例 #6
0
ファイル: firehose.py プロジェクト: lecole/stacker_blueprints
def kms_key_policy(key_use_arns, key_admin_arns):
    """ Creates a key policy for use of a KMS Key.

    key_use_arns is a list of arns that should have access to use the KMS
    key.
    """

    root_arn = Join(":", ["arn:aws:iam:", Ref("AWS::AccountId"), "root"])

    statements = []
    statements.append(
        Statement(Sid="Enable IAM User Permissions",
                  Effect=Allow,
                  Principal=AWSPrincipal(root_arn),
                  Action=[
                      Action("kms", "*"),
                  ],
                  Resource=["*"]))
    statements.append(
        Statement(Sid="Allow use of the key",
                  Effect=Allow,
                  Principal=AWSPrincipal(key_use_arns),
                  Action=[
                      awacs.kms.Encrypt,
                      awacs.kms.Decrypt,
                      awacs.kms.ReEncrypt,
                      awacs.kms.GenerateDataKey,
                      awacs.kms.GenerateDataKeyWithoutPlaintext,
                      awacs.kms.DescribeKey,
                  ],
                  Resource=["*"]))
    statements.append(
        Statement(Sid="Allow attachment of persistent resources",
                  Effect=Allow,
                  Principal=AWSPrincipal(key_use_arns),
                  Action=[
                      awacs.kms.CreateGrant,
                      awacs.kms.ListGrants,
                      awacs.kms.RevokeGrant,
                  ],
                  Resource=["*"],
                  Condition=Condition(Bool("kms:GrantIsForAWSResource",
                                           True))))
    statements.append(
        Statement(
            Sid="Allow access for Key Administrators",
            Effect=Allow,
            Principal=AWSPrincipal(key_admin_arns),
            Action=[
                Action("kms", "Create*"),
                Action("kms", "Describe*"),
                Action("kms", "Enable*"),
                Action("kms", "List*"),
                Action("kms", "Put*"),
                Action("kms", "Update*"),
                Action("kms", "Revoke*"),
                Action("kms", "Disable*"),
                Action("kms", "Get*"),
                Action("kms", "Delete*"),
                Action("kms", "ScheduleKeyDeletion"),
                Action("kms", "CancelKeyDeletion"),
            ],
            Resource=["*"],
        ))

    return Policy(Version="2012-10-17",
                  Id="key-default-1",
                  Statement=statements)
t.add_resource(
    Queue(
        "JsonNotificationDLQ",
        QueueName=Sub("${LambdaEnv}-json-notification-inbound-dlq"),
    ))

t.add_resource(
    QueuePolicy(
        "JsonNotificationReceiveQueuePolicy",
        Queues=[Ref("JsonNotificationReceiveQueue")],
        PolicyDocument=Policy(Statement=[
            Statement(Effect=Allow,
                      Action=[SendMessage],
                      Resource=[GetAtt("JsonNotificationReceiveQueue", "Arn")],
                      Principal=AWSPrincipal("*"),
                      Condition=Condition([
                          ArnLike("aws:SourceArn", Ref("GalileoBabelTopicArn"))
                      ]))
        ])))

t.add_resource(
    Bucket("NotificationsToBeIngested",
           BucketName=Sub("${LambdaEnv}-editorial-search-galileo-babel"),
           DeletionPolicy="Retain",
           NotificationConfiguration=NotificationConfiguration(
               TopicConfigurations=[
                   TopicConfigurations(Event="s3:ObjectCreated:*",
                                       Topic=ImportValue(
                                           Sub("${LambdaEnv}-JsonTopicArn")))
               ])))
コード例 #8
0
### -- Resources
ECRRepo = t.add_resource(
    Repository(
        'ECRRepo',
        RepositoryName=Ref("ECRRepoName"),
        RepositoryPolicyText=Policy(
            Version='2008-10-17',
            Statement=[
                Statement(
                    Sid='AllowPushPull',
                    Effect=Allow,
                    Principal=AWSPrincipal([
                        Join("", [
                            "arn:aws:iam::",
                            Ref(AWS_ACCOUNT_ID),
                            ":user/",
                            Ref("IAMAllowedUser"),
                        ]),
                    ]),
                    Action=[
                        ecr.GetDownloadUrlForLayer,
                        ecr.BatchGetImage,
                        ecr.BatchCheckLayerAvailability,
                        ecr.PutImage,
                        ecr.InitiateLayerUpload,
                        ecr.UploadLayerPart,
                        ecr.CompleteLayerUpload,
                    ],
                ),
            ]),
    ))
コード例 #9
0
from awacs.aws import Allow, AWSPrincipal, Condition
from awacs.aws import Policy, Statement
from awacs.aws import DateGreaterThan, DateLessThan, IpAddress
import awacs.sqs as sqs

region = 'us-east-1'
account = '444455556666'

pd = Policy(
    Id="Queue1_Policy_UUID",
    Statement=[
        Statement(
            Sid="Queue1_SendMessage",
            Effect=Allow,
            Principal=[
                AWSPrincipal("111122223333"),
            ],
            Action=[sqs.SendMessage],
            Resource=[
                sqs.SQS_ARN(region, account, "queue1"),
            ],
            Condition=Condition([
                DateGreaterThan("aws:CurrentTime", "2010-08-16T12:00:00Z"),
                DateLessThan("aws:CurrentTime", "2010-08-16T15:00:00Z"),
                IpAddress("aws:SourceIp", ["192.0.2.0/24", "203.0.113.0/24"]),
            ]),
        ),
    ],
)
print(pd.to_json())
コード例 #10
0
    def create_template(self):
        """Create template (main function called by Stacker)."""
        template = self.template
        variables = self.get_variables()
        template.set_version('2010-09-09')
        template.set_description('Static Website - Dependencies')

        # Resources
        awslogbucket = template.add_resource(
            s3.Bucket('AWSLogBucket',
                      AccessControl=s3.Private,
                      VersioningConfiguration=s3.VersioningConfiguration(
                          Status='Enabled')))
        template.add_output(
            Output('AWSLogBucketName',
                   Description='Name of bucket storing AWS logs',
                   Value=awslogbucket.ref()))

        template.add_resource(
            s3.BucketPolicy(
                'AllowAWSLogWriting',
                Bucket=awslogbucket.ref(),
                PolicyDocument=Policy(
                    Version='2012-10-17',
                    Statement=[
                        Statement(
                            Action=[awacs.s3.PutObject],
                            Effect=Allow,
                            Principal=AWSPrincipal(
                                Join(':',
                                     ['arn:aws:iam:', AccountId, 'root'])),
                            Resource=[
                                Join('', [
                                    'arn:aws:s3:::',
                                    awslogbucket.ref(), '/*'
                                ])
                            ])
                    ])))
        artifacts = template.add_resource(
            s3.Bucket(
                'Artifacts',
                AccessControl=s3.Private,
                LifecycleConfiguration=s3.LifecycleConfiguration(Rules=[
                    s3.LifecycleRule(NoncurrentVersionExpirationInDays=90,
                                     Status='Enabled')
                ]),
                VersioningConfiguration=s3.VersioningConfiguration(
                    Status='Enabled')))
        template.add_output(
            Output('ArtifactsBucketName',
                   Description='Name of bucket storing artifacts',
                   Value=artifacts.ref()))

        if variables['AuthAtEdge']:
            callbacks = self.context.hook_data['aae_callback_url_retriever'][
                'callback_urls']

            if variables['CreateUserPool']:
                user_pool = template.add_resource(
                    cognito.UserPool("AuthAtEdgeUserPool"))

                user_pool_id = user_pool.ref()

                template.add_output(
                    Output('AuthAtEdgeUserPoolId',
                           Description=
                           'Cognito User Pool App Client for Auth @ Edge',
                           Value=user_pool_id))
            else:
                user_pool_id = self.context.hook_data[
                    'aae_user_pool_id_retriever']['id']

            client = template.add_resource(
                cognito.UserPoolClient(
                    "AuthAtEdgeClient",
                    AllowedOAuthFlows=['code'],
                    CallbackURLs=callbacks,
                    UserPoolId=user_pool_id,
                    AllowedOAuthScopes=variables['OAuthScopes']))

            template.add_output(
                Output(
                    'AuthAtEdgeClient',
                    Description='Cognito User Pool App Client for Auth @ Edge',
                    Value=client.ref()))
コード例 #11
0
# Create an `ECR` docker repository
repository = Repository(
    "ApplicationRepository",
    template=template,
    RepositoryName=Ref(AWS_STACK_NAME),
    # Allow all account users to manage images.
    RepositoryPolicyText=Policy(Version="2008-10-17",
                                Statement=[
                                    Statement(
                                        Sid="AllowPushPull",
                                        Effect=Allow,
                                        Principal=AWSPrincipal([
                                            Join("", [
                                                arn_prefix,
                                                ":iam::",
                                                Ref(AWS_ACCOUNT_ID),
                                                ":root",
                                            ]),
                                        ]),
                                        Action=[
                                            ecr.GetDownloadUrlForLayer,
                                            ecr.BatchGetImage,
                                            ecr.BatchCheckLayerAvailability,
                                            ecr.PutImage,
                                            ecr.InitiateLayerUpload,
                                            ecr.UploadLayerPart,
                                            ecr.CompleteLayerUpload,
                                        ],
                                    ),
                                ]),
)
コード例 #12
0
AWSCloudTrailBucket = t.add_resource(Bucket(
    'AWSCloudTrailBucket'
))

# Generate a ECR Repository
DockerStaticWebsiteRepo = t.add_resource(
    Repository(
        'DockerStaticWebsiteRepo',
        RepositoryName=Ref(RepoName),
        RepositoryPolicyText=awacs.aws.Policy(
            Version=VERSION,
            Statement=[
                awacs.aws.Statement(
                    Sid='AllowPushPull',
                    Effect=Allow,
                    Principal=AWSPrincipal('*'),
                    Action=[
                        ecr.GetDownloadUrlForLayer,
                        ecr.BatchGetImage,
                        ecr.BatchCheckLayerAvailability,
                        ecr.PutImage,
                        ecr.InitiateLayerUpload,
                        ecr.UploadLayerPart,
                        ecr.CompleteLayerUpload,
                    ],
                ),
            ]
        ),
    )
)
コード例 #13
0
ファイル: dependencies.py プロジェクト: onicagroup/runway
    def create_template(self) -> None:
        """Create template (main function called by Stacker)."""
        template = self.template
        template.set_version("2010-09-09")
        template.set_description("Static Website - Dependencies")

        # Resources
        awslogbucket = template.add_resource(
            s3.Bucket(
                "AWSLogBucket",
                AccessControl=s3.Private,
                VersioningConfiguration=s3.VersioningConfiguration(
                    Status="Enabled"),
            ))
        template.add_output(
            Output(
                "AWSLogBucketName",
                Description="Name of bucket storing AWS logs",
                Value=awslogbucket.ref(),
            ))

        template.add_resource(
            s3.BucketPolicy(
                "AllowAWSLogWriting",
                Bucket=awslogbucket.ref(),
                PolicyDocument=Policy(
                    Version="2012-10-17",
                    Statement=[
                        Statement(
                            Action=[awacs.s3.PutObject],
                            Effect=Allow,
                            Principal=AWSPrincipal(
                                Join(":",
                                     ["arn:aws:iam:", AccountId, "root"])),
                            Resource=[
                                Join("", [
                                    "arn:aws:s3:::",
                                    awslogbucket.ref(), "/*"
                                ])
                            ],
                        )
                    ],
                ),
            ))
        artifacts = template.add_resource(
            s3.Bucket(
                "Artifacts",
                AccessControl=s3.Private,
                LifecycleConfiguration=s3.LifecycleConfiguration(Rules=[
                    s3.LifecycleRule(NoncurrentVersionExpirationInDays=90,
                                     Status="Enabled")
                ]),
                VersioningConfiguration=s3.VersioningConfiguration(
                    Status="Enabled"),
            ))
        template.add_output(
            Output(
                "ArtifactsBucketName",
                Description="Name of bucket storing artifacts",
                Value=artifacts.ref(),
            ))

        if self.variables["AuthAtEdge"]:
            userpool_client_params = {
                "AllowedOAuthFlows": ["code"],
                "AllowedOAuthScopes": self.variables["OAuthScopes"],
            }
            if self.variables["Aliases"]:
                userpool_client_params[
                    "AllowedOAuthFlowsUserPoolClient"] = True
                userpool_client_params[
                    "SupportedIdentityProviders"] = self.variables[
                        "SupportedIdentityProviders"]

                redirect_domains = [
                    add_url_scheme(x) for x in self.variables["Aliases"]
                ] + [
                    add_url_scheme(x)
                    for x in self.variables["AdditionalRedirectDomains"]
                ]
                redirect_uris = get_redirect_uris(
                    redirect_domains,
                    self.variables["RedirectPathSignIn"],
                    self.variables["RedirectPathSignOut"],
                )
                userpool_client_params["CallbackURLs"] = redirect_uris[
                    "sign_in"]
                userpool_client_params["LogoutURLs"] = redirect_uris[
                    "sign_out"]
            else:
                userpool_client_params[
                    "CallbackURLs"] = self.context.hook_data[
                        "aae_callback_url_retriever"]["callback_urls"]

            if self.variables["CreateUserPool"]:
                user_pool = template.add_resource(
                    cognito.UserPool("AuthAtEdgeUserPool"))

                user_pool_id = user_pool.ref()

                template.add_output(
                    Output(
                        "AuthAtEdgeUserPoolId",
                        Description=
                        "Cognito User Pool App Client for Auth @ Edge",
                        Value=user_pool_id,
                    ))
            else:
                user_pool_id = self.context.hook_data[
                    "aae_user_pool_id_retriever"]["id"]
            userpool_client_params["UserPoolId"] = user_pool_id

            client = template.add_resource(
                cognito.UserPoolClient("AuthAtEdgeClient",
                                       **userpool_client_params))

            template.add_output(
                Output(
                    "AuthAtEdgeClient",
                    Description="Cognito User Pool App Client for Auth @ Edge",
                    Value=client.ref(),
                ))
コード例 #14
0
    def create_template(self):
        """Create template (main function called by Stacker)."""
        template = self.template
        variables = self.get_variables()
        template.set_version("2010-09-09")
        template.set_description("Static Website - Dependencies")

        # Resources
        awslogbucket = template.add_resource(
            s3.Bucket(
                "AWSLogBucket",
                AccessControl=s3.Private,
                VersioningConfiguration=s3.VersioningConfiguration(Status="Enabled"),
            )
        )
        template.add_output(
            Output(
                "AWSLogBucketName",
                Description="Name of bucket storing AWS logs",
                Value=awslogbucket.ref(),
            )
        )

        template.add_resource(
            s3.BucketPolicy(
                "AllowAWSLogWriting",
                Bucket=awslogbucket.ref(),
                PolicyDocument=Policy(
                    Version="2012-10-17",
                    Statement=[
                        Statement(
                            Action=[awacs.s3.PutObject],
                            Effect=Allow,
                            Principal=AWSPrincipal(
                                Join(":", ["arn:aws:iam:", AccountId, "root"])
                            ),
                            Resource=[
                                Join("", ["arn:aws:s3:::", awslogbucket.ref(), "/*"])
                            ],
                        )
                    ],
                ),
            )
        )
        artifacts = template.add_resource(
            s3.Bucket(
                "Artifacts",
                AccessControl=s3.Private,
                LifecycleConfiguration=s3.LifecycleConfiguration(
                    Rules=[
                        s3.LifecycleRule(
                            NoncurrentVersionExpirationInDays=90, Status="Enabled"
                        )
                    ]
                ),
                VersioningConfiguration=s3.VersioningConfiguration(Status="Enabled"),
            )
        )
        template.add_output(
            Output(
                "ArtifactsBucketName",
                Description="Name of bucket storing artifacts",
                Value=artifacts.ref(),
            )
        )

        if variables["AuthAtEdge"]:
            callbacks = self.context.hook_data["aae_callback_url_retriever"][
                "callback_urls"
            ]

            if variables["CreateUserPool"]:
                user_pool = template.add_resource(
                    cognito.UserPool("AuthAtEdgeUserPool")
                )

                user_pool_id = user_pool.ref()

                template.add_output(
                    Output(
                        "AuthAtEdgeUserPoolId",
                        Description="Cognito User Pool App Client for Auth @ Edge",
                        Value=user_pool_id,
                    )
                )
            else:
                user_pool_id = self.context.hook_data["aae_user_pool_id_retriever"][
                    "id"
                ]

            client = template.add_resource(
                cognito.UserPoolClient(
                    "AuthAtEdgeClient",
                    AllowedOAuthFlows=["code"],
                    CallbackURLs=callbacks,
                    UserPoolId=user_pool_id,
                    AllowedOAuthScopes=variables["OAuthScopes"],
                )
            )

            template.add_output(
                Output(
                    "AuthAtEdgeClient",
                    Description="Cognito User Pool App Client for Auth @ Edge",
                    Value=client.ref(),
                )
            )
コード例 #15
0
from troposphere.ecr import Repository

t = Template()

t.add_resource(
    Repository(
        "MyRepository",
        RepositoryName="test-repository",
        RepositoryPolicyText=PolicyDocument(
            Version="2008-10-17",
            Statement=[
                Statement(
                    Sid="AllowPushPull",
                    Effect=Allow,
                    Principal=AWSPrincipal([
                        iam.ARN(account="123456789012", resource="user/Bob"),
                        iam.ARN(account="123456789012", resource="user/Alice"),
                    ]),
                    Action=[
                        ecr.GetDownloadUrlForLayer,
                        ecr.BatchGetImage,
                        ecr.BatchCheckLayerAvailability,
                        ecr.PutImage,
                        ecr.InitiateLayerUpload,
                        ecr.UploadLayerPart,
                        ecr.CompleteLayerUpload,
                    ],
                ),
            ],
        ),
    ))
コード例 #16
0
ファイル: mock_blueprints.py プロジェクト: zaro0508/stacker
    def create_template(self):
        t = self.template

        bucket_arn = Sub("arn:aws:s3:::${StackerBucket}*")
        cloudformation_scope = Sub(
            "arn:aws:cloudformation:*:${AWS::AccountId}:"
            "stack/${StackerNamespace}-*")
        changeset_scope = "*"

        # This represents the precise IAM permissions that stacker itself
        # needs.
        stacker_policy = iam.Policy(
            PolicyName="Stacker",
            PolicyDocument=Policy(
                Statement=[
                    Statement(
                        Effect="Allow",
                        Resource=[bucket_arn],
                        Action=[
                            awacs.s3.ListBucket,
                            awacs.s3.GetBucketLocation,
                            awacs.s3.CreateBucket]),
                    Statement(
                        Effect="Allow",
                        Resource=[bucket_arn],
                        Action=[
                            awacs.s3.GetObject,
                            awacs.s3.GetObjectAcl,
                            awacs.s3.PutObject,
                            awacs.s3.PutObjectAcl]),
                    Statement(
                        Effect="Allow",
                        Resource=[changeset_scope],
                        Action=[
                            awacs.cloudformation.DescribeChangeSet,
                            awacs.cloudformation.ExecuteChangeSet,
                            awacs.cloudformation.DeleteChangeSet,
                        ]),
                    Statement(
                        Effect="Deny",
                        Resource=[Ref("AWS::StackId")],
                        Action=[
                            awacs.cloudformation.Action("*")]),
                    Statement(
                        Effect="Allow",
                        Resource=[cloudformation_scope],
                        Action=[
                            awacs.cloudformation.GetTemplate,
                            awacs.cloudformation.CreateChangeSet,
                            awacs.cloudformation.DeleteChangeSet,
                            awacs.cloudformation.DeleteStack,
                            awacs.cloudformation.CreateStack,
                            awacs.cloudformation.UpdateStack,
                            awacs.cloudformation.SetStackPolicy,
                            awacs.cloudformation.DescribeStacks,
                            awacs.cloudformation.DescribeStackEvents])]))

        principal = AWSPrincipal(Ref("AWS::AccountId"))
        role = t.add_resource(
            iam.Role(
                "FunctionalTestRole",
                AssumeRolePolicyDocument=Policy(
                    Statement=[
                        Statement(
                            Effect="Allow",
                            Action=[
                                awacs.sts.AssumeRole],
                            Principal=principal)]),
                Policies=[
                    stacker_policy]))

        assumerole_policy = iam.Policy(
            PolicyName="AssumeRole",
            PolicyDocument=Policy(
                Statement=[
                    Statement(
                        Effect="Allow",
                        Resource=[GetAtt(role, "Arn")],
                        Action=[
                            awacs.sts.AssumeRole])]))

        user = t.add_resource(
            iam.User(
                "FunctionalTestUser",
                Policies=[
                    stacker_policy,
                    assumerole_policy]))

        key = t.add_resource(
            iam.AccessKey(
                "FunctionalTestKey",
                Serial=1,
                UserName=Ref(user)))

        t.add_output(Output("User", Value=Ref(user)))
        t.add_output(Output("AccessKeyId", Value=Ref(key)))
        t.add_output(
            Output(
                "SecretAccessKey",
                Value=GetAtt("FunctionalTestKey", "SecretAccessKey")))
        t.add_output(
            Output(
                "FunctionalTestRole",
                Value=GetAtt(role, "Arn")))
コード例 #17
0
ファイル: ecr.py プロジェクト: skyer9/CloudFormationForPython
template = Template()

repository = template.add_resource(
    Repository(
        "ApplicationRepository",
        RepositoryName=repository_name,
        RepositoryPolicyText=Policy(
            Version="2008-10-17",
            Statement=[
                Statement(
                    Sid="AllowPushPull",
                    Effect=Allow,
                    Principal=AWSPrincipal([
                        Join("", [
                            "arn:aws:iam::",
                            Ref(AWS_ACCOUNT_ID),
                            ":root",
                        ]),
                    ]),
                    Action=[
                        ecr.GetDownloadUrlForLayer,
                        ecr.BatchGetImage,
                        ecr.BatchCheckLayerAvailability,
                        ecr.PutImage,
                        ecr.InitiateLayerUpload,
                        ecr.UploadLayerPart,
                        ecr.CompleteLayerUpload,
                    ],
                ),
            ]),
    ))
コード例 #18
0
from awacs.aws import Allow, ArnEquals, AWSPrincipal, Condition
from awacs.aws import Policy, Statement
import awacs.sns as sns
import awacs.sqs as sqs

region = 'us-east-1'
account = '012345678891'

pd = Policy(Statement=[
    Statement(
        Effect=Allow,
        Principal=[
            AWSPrincipal("210987654321"),
        ],
        Action=[sqs.SendMessage],
        Resource=[
            sqs.SQS_ARN(region, account, "your_queue_xyz"),
        ],
        Condition=Condition(
            ArnEquals(
                "aws:SourceArn",
                sns.SNS_ARN(region, '123456789012',
                            'your_special_topic_1')), ),
    ),
], )
print(pd.to_json())
コード例 #19
0

t = Template()

t.add_resource(
    Repository(
        'MyRepository',
        RepositoryName='test-repository',
        RepositoryPolicyText=Policy(
            Version='2008-10-17',
            Statement=[
                Statement(
                    Sid='AllowPushPull',
                    Effect=Allow,
                    Principal=AWSPrincipal([
                        iam.ARN(account='123456789012', resource='user/Bob'),
                        iam.ARN(account='123456789012', resource='user/Alice'),
                    ]),
                    Action=[
                        ecr.GetDownloadUrlForLayer,
                        ecr.BatchGetImage,
                        ecr.BatchCheckLayerAvailability,
                        ecr.PutImage,
                        ecr.InitiateLayerUpload,
                        ecr.UploadLayerPart,
                        ecr.CompleteLayerUpload,
                    ],
                ),
            ]
        ),
    )
)
コード例 #20
0
def generate_queues_template(QueueNamePrefix, Environment):
    QueueName = f'{QueueNamePrefix}-{Environment}'
    DLQQueueName = f'{QueueNamePrefix}DLQ-{Environment}'

    t = Template(Description='A template for a messaging queue')
    t.version = '2010-09-09'

    KMSKey = t.add_resource(
        Key('KMSKey',
            Description=f'KMS Key for encrypting {QueueName}',
            Enabled=True,
            EnableKeyRotation=True,
            KeyPolicy=Policy(
                Version='2012-10-17',
                Statement=[
                    Statement(Sid='Enable IAM User Permissions',
                              Effect=Allow,
                              Principal=AWSPrincipal(
                                  Sub('arn:aws:iam::${AWS::AccountId}:root')),
                              Action=[KmsAction(All)],
                              Resource=AllResources),
                    Statement(Sid='Allow access for Key Administrators',
                              Effect=Allow,
                              Principal=AWSPrincipal([
                                  Sub(f'{USER}/frank'),
                                  Sub(f'{USER}/moonunit')
                              ]),
                              Action=[
                                  KmsAction('Create*'),
                                  KmsAction('Describe*'),
                                  KmsAction('Enable*'),
                                  KmsAction('List*'),
                                  KmsAction('Put*'),
                                  KmsAction('Update*'),
                                  KmsAction('Revoke*'),
                                  KmsAction('Disable*'),
                                  KmsAction('Get*'),
                                  KmsAction('Delete*'),
                                  KmsAction('ScheduleKeyDeletion'),
                                  KmsAction('CancelKeyDeletion')
                              ],
                              Resource=AllResources)
                ])))

    t.add_resource(
        Alias('KMSKeyAlias',
              AliasName=f'alias/{QueueName}',
              TargetKeyId=Ref(KMSKey)))

    dlq = t.add_resource(
        Queue(
            'DeadLetterQueue',
            QueueName=DLQQueueName,
            MaximumMessageSize=262144,  # 256KiB
            MessageRetentionPeriod=1209600,  # 14 days
            VisibilityTimeout=30))

    t.add_resource(
        Queue(
            'PrimaryQueue',
            QueueName=QueueName,
            MaximumMessageSize=262144,  # 256KiB
            MessageRetentionPeriod=1209600,  # 14 days
            VisibilityTimeout=30,
            RedrivePolicy=RedrivePolicy(deadLetterTargetArn=GetAtt(
                dlq.title, 'Arn'),
                                        maxReceiveCount=10),
            KmsMasterKeyId=Ref(KMSKey),
            KmsDataKeyReusePeriodSeconds=300))

    t.add_output([
        Output('QueueArn',
               Description=f'ARN of {QueueName} Queue',
               Value=GetAtt('PrimaryQueue', 'Arn'),
               Export=Export(Name(Sub('${AWS::StackName}:PrimaryQueueArn')))),
        Output('KmsKeyArn',
               Description=f'KMS Key ARN for {QueueName} Queue',
               Value=GetAtt('KMSKey', 'Arn'),
               Export=Export(Name(Sub('${AWS::StackName}:KmsKeyArn'))))
    ])

    return t