def create_ecs_service_role(provider, context, **kwargs): """Used to create the ecsServieRole, which has to be named exactly that currently, so cannot be created via CloudFormation. See: http://docs.aws.amazon.com/AmazonECS/latest/developerguide/IAM_policies.html#service_IAM_role Args: provider (:class:`stacker.providers.base.BaseProvider`): provider instance context (:class:`stacker.context.Context`): context instance Returns: boolean for whether or not the hook succeeded. """ role_name = kwargs.get("role_name", "ecsServiceRole") client = get_session(provider.region).client('iam') try: client.create_role( RoleName=role_name, AssumeRolePolicyDocument=get_ecs_assumerole_policy().to_json() ) except ClientError as e: if "already exists" in str(e): pass else: raise policy = Policy( Statement=[ Statement( Effect=Allow, Resource=["*"], Action=[ecs.CreateCluster, ecs.DeregisterContainerInstance, ecs.DiscoverPollEndpoint, ecs.Poll, ecs.Action("Submit*")] ) ]) client.put_role_policy( RoleName=role_name, PolicyName="AmazonEC2ContainerServiceRolePolicy", PolicyDocument=policy.to_json() ) return True
def create_ecs_service_role(region, namespace, mappings, parameters, **kwargs): """ Used to create the ecsServieRole, which has to be named exactly that currently, so cannot be created via CloudFormation. See: http://docs.aws.amazon.com/AmazonECS/latest/developerguide/IAM_policies.html#service_IAM_role """ conn = ConnectionManager(region).iam policy = Policy( Statement=[ Statement( Effect=Allow, Resource=["*"], Action=[ecs.CreateCluster, ecs.DeregisterContainerInstance, ecs.DiscoverPollEndpoint, ecs.Poll, ecs.ECSAction("Submit*")] ) ]) conn.put_role_policy("ecsServiceRole", "AmazonEC2ContainerServiceRole", policy.to_json()) return True
def create_policy(self, name): statements = self.generate_policy_statements() if not statements: return t = self.template policy = t.add_resource( iam.PolicyType( "{}Policy".format(name), PolicyName=Sub("${AWS::StackName}-${Name}-policy", Name=name), PolicyDocument=Policy(Statement=statements, ), Roles=[Ref(role) for role in self.roles], )) t.add_output(Output(name + "PolicyName", Value=Ref(policy))) self.policies.append(policy)
def attach_ssm_key_policy(self, myrole): return super(NCTemplate, self).add_resource( iam.PolicyType( 'policyssmkey', PolicyName='ssmkeypolicy', PolicyDocument=Policy( Version='2012-10-17', Statement=[ Statement( Effect=Allow, Action=[Action("kms", "Decrypt")], Resource=[ ImportValue( Sub("${EncryptLambdaStack}-KmsKeyArn")) ]) ]), Roles=[Ref(myrole)]))
def s3_write_policy(bucket): statements = [ Statement( Effect=Allow, Action=[ awacs.s3.AbortMultipartUpload, awacs.s3.GetBucketLocation, awacs.s3.GetObject, awacs.s3.ListBucket, awacs.s3.ListBucketMultipartUploads, awacs.s3.PutObject, ], Resource=[s3_arn(bucket), s3_arn(Join("/", [bucket, "*"]))], ), ] return Policy(Statement=statements)
def gen_iam_role(): LambdaExecutionRole = Role( "LambdaExecutionRole", Path="/", Policies=[ Policy( PolicyName="CloudformationCleanerLambdaPolicy", PolicyDocument={ "Version": "2012-10-17", "Statement": [{ "Action": [ "cloudformation:DeleteStack", "cloudformation:ListStacks", "cloudformation:DescribeStacks", "iam:DeleteRolePolicy", "iam:DeleteRole", "iam:DeleteInstanceProfile", "iam:RemoveRoleFromInstanceProfile", "ec2:DescribeInstances", "ec2:DeleteSecurityGroup", "ec2:TerminateInstances", "sns:DeleteTopic", "sns:GetTopicAttributes", "sns:ListSubscriptionsByTopic", "sns:Unsubscribe", "logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents", "lambda:RemovePermission" ], "Resource": "*", "Effect": "Allow" }] }) ], AssumeRolePolicyDocument={ "Version": "2012-10-17", "Statement": [{ "Action": ["sts:AssumeRole"], "Effect": "Allow", "Principal": { "Service": ["lambda.amazonaws.com"] } }] }, ) return LambdaExecutionRole
def create_policy(self): t = self.template policy_prefix = self.context.get_fqn(self.name) self.policy = t.add_resource( iam.PolicyType( "Policy", PolicyName="%s-policy" % policy_prefix, PolicyDocument=Policy( Statement=self.generate_policy_statements() ), Roles=[Ref(self.role)], ) ) t.add_output( Output("PolicyName", Value=Ref(self.policy)) )
def create_iam_policy(stack, policy_name, actions, groups=[], roles=[], users=[], resources=['*']): """Add IAM policy resource.""" return stack.stack.add_resource( ManagedPolicy(policy_name, ManagedPolicyName=policy_name, Groups=groups, Roles=roles, Users=users, PolicyDocument=Policy( Version="2012-10-17", Statement=[ Statement( Effect=Allow, Action=[Action('{0}'.format(action.split(':')[0]), "{0}".format(action.split(':')[1])) for action in actions], Resource=resources )])))
def create_policy(self): t = self.template ns = self.context.namespace policy_name = 'ServerlessPolicy' statements = [ Statement( Effect=Allow, Action=[awacs.awslambda.InvokeFunction], Resource=[Everybody], ), ] t.add_resource( iam.PolicyType( policy_name, PolicyName='{}-{}'.format(ns, policy_name), PolicyDocument=Policy(Statement=statements), Roles=[Ref('Role')], ))
def logs_writer(name=None, template=None): name = (name or '').title() + 'LogsWriter' return iam.Policy( PolicyName=name, PolicyDocument=Policy( Statement=[ Statement( Effect=Allow, Action=[ CreateLogGroup, CreateLogStream, PutLogEvents, ], Resource=[BaseARN('logs', '*', '*', '*')], ), ] ) )
def create_template(self): t = self.template t.add_description("Acceptance Tests for cumulus scaling groups") # TODO fix # instance = self.name + self.context.environment['env'] instance = "someinstance" # TODO: give to builder the_chain = chain.Chain() the_chain.add( ingress_rule.IngressRule(port_to_open="22", cidr="10.0.0.0/8")) instance_profile_name = "InstanceProfile" + self.name the_chain.add( InstanceProfileRole( instance_profile_name=instance_profile_name, role=iam.Role( "SomeRoleName1", AssumeRolePolicyDocument=Policy(Statement=[ Statement(Effect=Allow, Action=[AssumeRole], Principal=Principal("Service", [ "ec2.amazonaws.com", "s3.amazonaws.com" ])) ]), ))) the_chain.add( launch_config.LaunchConfig(meta_data=self.get_metadata())) the_chain.add( block_device_data.BlockDeviceData( ec2.BlockDeviceMapping( DeviceName="/dev/xvda", Ebs=ec2.EBSBlockDevice(VolumeSize="40")))) the_chain.add(scaling_group.ScalingGroup()) chain_context = chaincontext.ChainContext(template=t, instance_name=instance) the_chain.run(chain_context)
def add_resources(self): """Create template (main function called by Stacker).""" template = self.template variables = self.get_variables() # Resources # build the CFN template with the specified permissions iam_policy_statements = [] iam_policy_statements.append( Statement(Sid='AllowReadAccessToS3Bucket', Action=[ Action('iam', 'ListRoles'), Action('iam', 'PassRole'), Action('sts', 'AssumeRole'), Action('s3', 'GetObject'), Action('s3', 'ListBucket'), ], Effect=Allow, Resource=[variables['S3BucketArn'].ref])) # allow Admin role to list, pass and assume Cloudformation service role iam_policy_statements.append( Statement(Sid='AllowListPassAssumeToRole', Action=[ Action('iam', 'ListRoles'), Action('iam', 'PassRole'), Action('sts', 'AssumeRole'), ], Effect=Allow, Resource=[variables['AssumeRoleArn'].ref])) template.add_resource( iam.PolicyType( 'IamPolicy', PolicyName=variables['PolicyName'].ref, PolicyDocument=Policy( Version='2012-10-17', Statement=iam_policy_statements, ), # pick one of the 3 below (Groups, Roles or Users) #Groups=variables['Groups'].ref Roles=variables['Roles'].ref #Users=variables['Users'].ref ))
def bucket_full_access(bucket, name=None, template=None): name = (name or '').title() + bucket.title + 'S3BucketFullAccess' return iam.Policy( PolicyName=name, PolicyDocument=Policy( Statement=[ Statement( Effect=Allow, Action=[ Action('s3', '*'), ], Resource=[ Join('', ['arn:aws:s3:::', Ref(bucket)]), Join('', ['arn:aws:s3:::', Ref(bucket), '/*']), ], ), ] ) )
def dynamodb_autoscaling_policy(tables): """Policy to allow AutoScaling a list of DynamoDB tables.""" return Policy(Statement=[ Statement(Effect=Allow, Resource=dynamodb_arns(tables), Action=[ dynamodb.DescribeTable, dynamodb.UpdateTable, ]), Statement(Effect=Allow, Resource=['*'], Action=[ cloudwatch.PutMetricAlarm, cloudwatch.DescribeAlarms, cloudwatch.GetMetricStatistics, cloudwatch.SetAlarmState, cloudwatch.DeleteAlarms, ]), ])
def create_iam_policy(template, role_name, policy_name, role_path, policy_document, profile_name): cfnrole = template.add_resource( Role(role_name, AssumeRolePolicyDocument=Policy(Statement=[ Statement(Effect=Allow, Action=[AssumeRole], Principal=Principal("Service", ["ec2.amazonaws.com"])) ]), Path=role_path, Policies=[ tPolicy(PolicyName=policy_name, PolicyDocument=json.loads(policy_document)) ])) cfninstanceprofile = template.add_resource( InstanceProfile(profile_name, Roles=[Ref(cfnrole)])) return cfninstanceprofile
def _create_cfn_deploy_role(self): cfn_deploy_role = iam.Role( 'CFNDeployRole', AssumeRolePolicyDocument=self._allow_assume_role_service( 'cloudformation'), Policies=[ iam.PolicyProperty(PolicyName='DeployAccess', PolicyDocument=Policy( Version='2012-10-17', Statement=[ Statement( Action=[Action('*')], Resource=['*'], Effect=Allow, ) ])) ]) self._t.add_resource(cfn_deploy_role) return cfn_deploy_role
def vpc_flow_log_cloudwatch_policy(log_group_arn): return Policy(Statement=[ Statement( Effect="Allow", Action=[logs.DescribeLogGroups], Resource=["*"], ), Statement( Effect="Allow", Action=[ logs.CreateLogStream, logs.DescribeLogStreams, logs.PutLogEvents, ], Resource=[ log_group_arn, Join('', [log_group_arn, ":*"]), ], ), ])
def make_role(name, template, assume_to, *policies): def _policy(p): if callable(p): return p(name=name, template=template) return p if not isinstance(assume_to, list): assume_to = [assume_to] return iam.Role( name + 'Role', template, Path='/', AssumeRolePolicyDocument=Policy(Statement=[ Statement( Effect=Allow, Action=[AssumeRole], Principal=Principal('Service', assume_to) ) ]), Policies=[_policy(p) for p in policies] )
def empire_policy(): p = Policy(Statement=[ Statement(Effect=Allow, Resource=["*"], Action=[ ecs.CreateService, ecs.DeleteService, ecs.DeregisterTaskDefinition, ecs.ECSAction("Describe*"), ecs.ECSAction("List*"), ecs.RegisterTaskDefinition, ecs.RunTask, ecs.StartTask, ecs.StopTask, ecs.SubmitTaskStateChange, ecs.UpdateService ]), Statement( Effect=Allow, # TODO: Limit to specific ELB? Resource=["*"], Action=[ elb.DeleteLoadBalancer, elb.CreateLoadBalancer, elb.DescribeLoadBalancers, elb.DescribeTags, elb.ConfigureHealthCheck, elb.ModifyLoadBalancerAttributes ]), Statement(Effect=Allow, Resource=["*"], Action=[ec2.DescribeSubnets, ec2.DescribeSecurityGroups]), Statement(Effect=Allow, Action=[ iam.GetServerCertificate, iam.UploadServerCertificate, iam.DeleteServerCertificate, iam.PassRole ], Resource=["*"]), Statement( Effect=Allow, Action=[ Action("route53", "ListHostedZonesByName"), route53.ChangeResourceRecordSets, route53.ListHostedZones, route53.GetHostedZone ], # TODO: Limit to specific zones Resource=["*"]) ]) return p
def create_role(self): t = self.template statements = [ Statement( Principal=Principal('Service', ['firehose.amazonaws.com']), Effect=Allow, Action=[sts.AssumeRole], Condition=Condition( StringEquals('sts:ExternalId', Ref('AWS::AccountId')), ), ), ] firehose_role_policy = Policy(Statement=statements) t.add_resource( iam.Role( FIREHOSE_ROLE, AssumeRolePolicyDocument=firehose_role_policy, Path='/', Policies=self.generate_iam_policies(), ), ) t.add_output(Output('Role', Value=Ref(FIREHOSE_ROLE)))
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), ) ], ), ), )
def s3_write_policy(bucket): def s3_arn(bucket): return Join(':', ['arn:aws:s3::', bucket]) statements = [ Statement( Effect=Allow, Action=[ awacs.s3.AbortMultipartUpload, awacs.s3.GetBucketLocation, awacs.s3.GetObject, awacs.s3.ListBucket, awacs.s3.ListBucketMultipartUploads, awacs.s3.PutObject, ], Resource=[ s3_arn(bucket), s3_arn(Join('/', [bucket, '*'])), ], ), ] return Policy(Statement=statements)
def create_policy(t, domain): policy_name = 'ESDomainReadAccess' statements = [ Statement( Effect=Allow, Action=[ awacs.es.Action('HttpGet'), awacs.es.Action('HttpHead'), awacs.es.Action('HttpPost'), awacs.es.Action('HttpDelete'), ], Resource=[Join('/', [GetAtt('Domain', 'DomainArn'), '*'])], ), ] t.add_resource( iam.PolicyType( policy_name, PolicyName=policy_name, PolicyDocument=Policy(Statement=statements), Roles=[Ref('Role')], ), )
def ecs_agent_policy(): p = Policy(Statement=[ Statement(Effect=Allow, Resource=["*"], Action=[ ecs.CreateCluster, ecs.RegisterContainerInstance, ecs. DeregisterContainerInstance, ecs.DiscoverPollEndpoint, ecs.Action("Submit*"), ecs.Poll, ecs.Action("StartTelemetrySession") ]), Statement( Effect=Allow, Action=[ ecr.GetAuthorizationToken, ecr.BatchCheckLayerAvailability, ecr.GetDownloadUrlForLayer, ecr.BatchGetImage, ], Resource=["*"], ), ]) return p
def create_role(self): t = self.template self.role = t.add_resource( iam.Role("Role", AssumeRolePolicyDocument=get_lambda_assumerole_policy())) if self.get_variables()["VpcConfig"]: # allow this Lambda to modify ENIs to allow it to run in our VPC. self.role.Policies = [ iam.Policy( PolicyName=Sub("${AWS::StackName}-vpc-policy"), PolicyDocument=Policy( Statement=lambda_vpc_execution_statements()), ) ] t.add_output(Output("RoleName", Value=Ref(self.role))) role_arn = self.role.GetAtt("Arn") self.role_arn = role_arn t.add_output(Output("RoleArn", Value=role_arn))
def create_policy(self, name): statements = self.generate_policy_statements() if not statements: return t = self.template policy_prefix = self.context.get_fqn(self.name) policy = t.add_resource( iam.PolicyType( "{}Policy".format(name), PolicyName="{}-{}-policy".format(policy_prefix, name), PolicyDocument=Policy( Statement=statements, ), Roles=[Ref(role) for role in self.roles], ) ) t.add_output( Output(name + "PolicyName", Value=Ref(policy)) ) self.policies.append(policy)
def _instance_iam_role_policy(self): return PolicyType( "InstanceIamRolePolicy", PolicyName="AppInstanceIamRolePolicy", PolicyDocument=Policy(Statement=[ Statement(Effect=Allow, Action=[GetObject], Resource=[ "arn:aws:s3:::%s/*" % self.config['elb_logging_bucket'], "arn:aws:s3:::%s/*" % self.config['app_bucket'], "arn:aws:s3:::%s/*" % self.config['config_bucket'] ]), Statement(Effect=Allow, Action=[ListBucket], Resource=[ "arn:aws:s3:::%s" % self.config['elb_logging_bucket'], "arn:aws:s3:::%s" % self.config['app_bucket'], "arn:aws:s3:::%s" % self.config['config_bucket'] ]) ]), Roles=[Ref(self.instance_iam_role)])
readonly_role_arn = 'arn:aws:iam::*:role/ReadonlyPolicy' modifyinstances_role_arn = 'arn:aws:iam::*:role/ModifyInstancesPolicy' cloudwatch_role_arn = iam.ARN('*', 'role/brkt-cloudwatch') sqs_arn = sqs.ARN('us-west-2', my_aws_account_id, 'theQueueName') worker_access_policy = Policy( Statement=[ Statement( Effect=Allow, Action=[ sqs.ChangeMessageVisibility, sqs.DeleteMessage, sqs.GetQueueAttributes, sqs.GetQueueUrl, sqs.ReceiveMessage, ], Resource=[sqs_arn], ), Statement( Effect=Allow, Action=[sts.AssumeRole], Resource=[modifyinstances_role_arn], ), ] ) apptier_access_policy = Policy( Statement=[ Statement( Effect=Allow, Action=[
SecurityGroups=[Ref("LoadBalancerSecurityGroup")], )) ud = Base64( Join('\n', [ "#!/bin/bash", "yum install --enablerepo=epel -y git", "pip install ansible", AnsiblePullCmd, "echo '*/10 * * * * {}' > /etc/cron.d/ansible-pull".format( AnsiblePullCmd) ])) t.add_resource( Role("Role", AssumeRolePolicyDocument=Policy(Statement=[ Statement(Effect=Allow, Action=[AssumeRole], Principal=Principal("Service", ["ec2.amazonaws.com"])) ]))) t.add_resource( InstanceProfile("InstanceProfile", Path="/", Roles=[Ref("Role")])) t.add_resource( IAMPolicy( "Policy", PolicyName="AllowS3", PolicyDocument=Policy(Statement=[ Statement(Effect=Allow, Action=[Action("s3", "*")], Resource=["*"]) ]), Roles=[Ref("Role")]))
from awacs.sts import AssumeRole import ec2_mappings t = Template() t.add_description("Creates resources for viewing CloudFormation logs of EC2 instances.") t = ec2_mappings.attachMappings(t) policy = Policy( Version="2012-10-17", Id="Logs Permissions", Statement=[ Statement( Sid="1", Effect=Allow, Principal=Principal("Service", FindInMap("Region2Principal", Ref("AWS::Region"), "EC2Principal")), Action=[ Action("logs", "CreateLogGroup"), Action("logs", "CreateLogStream"), Action("logs", "PutLogEvents"), Action("logs", "DescribeLogStreams"), ], Resource=[Join("", [FindInMap("Region2ARNPrefix", Ref("AWS::Region"), "ARNPrefix"), "logs:*:*:*"])], ), ], ) logrole = t.add_resource(Role( "logrole", AssumeRolePolicyDocument=policy, ) )
ud = Base64( Join('\n', [ "#!/bin/bash", "sudo yum install -y https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm", "sudo yum install --enablerepo=epel -y git", "sudo yum install --enablerepo=epel -y ansible", AnsiblePullCmd, "echo '*/10 * * * * {}' > /etc/cron.d/ansible-pull".format( AnsiblePullCmd) ])) t.add_resource( Role("Role", AssumeRolePolicyDocument=Policy(Statement=[ Statement(Effect=Allow, Action=[AssumeRole], Principal=Principal("Service", ["ec2.amazonaws.com"])) ]))) t.add_resource( InstanceProfile("InstanceProfile", Path="/", Roles=[Ref("Role")])) t.add_resource( ec2.Instance( "instance", ImageId="ami-0ebe657bc328d4e82", InstanceType="t2.micro", SecurityGroups=[Ref("SecurityGroup")], KeyName=Ref("KeyPair"), UserData=ud, IamInstanceProfile=Ref("InstanceProfile"),
], )) ud = Base64( Join('\n', [ "#!/bin/bash", "yum install --enablerepo=epel -y git", "pip install ansible", AnsiblePullCmd, "echo '*/10 * * * * {}' > /etc/cron.d/ansible-pull".format( AnsiblePullCmd) ])) t.add_resource( Role("Role", AssumeRolePolicyDocument=Policy(Statement=[ Statement(Effect=Allow, Action=[AssumeRole], Principal=Principal("Service", ["ec2.amazonaws.com"])) ]))) t.add_resource( InstanceProfile("InstanceProfile", Path="/", Roles=[Ref("Role")])) t.add_resource( ec2.Instance( "instance", ImageId="ami-0ff8a91507f77f867", InstanceType="t2.micro", SecurityGroups=[Ref("SecurityGroup")], KeyName=Ref("KeyPair"), UserData=ud, IamInstanceProfile=Ref("InstanceProfile"),
def __init__( self, stack, paco_ctx, grp_id=None, topics=None, ): enabled_topics = False config = stack.resource # this template is used as both SNSTopics by global resources and a # single SNSTopic for an application resource. if topics == None: if grp_id == None: topics = [stack.resource] enabled_topics = stack.resource.is_enabled() else: topics = config.values() for topic in topics: if topic.is_enabled(): enabled_topics = True else: if len(topics) > 0: enabled_topics = True super().__init__( stack, paco_ctx, enabled=enabled_topics, ) if grp_id == None: self.set_aws_name('SNSTopics', self.resource_group_name, self.resource_name) else: self.set_aws_name('SNSTopics', grp_id) # Troposphere Template Initialization self.init_template('SNS Topics') template = self.template # Topic Resources and Outputs topics_ref_cross_list = [] topic_policy_cache = [] for topic in topics: if not topic.is_enabled(): continue statement_list = [] topic_logical_id = self.create_cfn_logical_id(topic.name) # Do not specify a TopicName, as then updates cannot be performed that require # replacement of this resource. cfn_export_dict = {} if topic.display_name: cfn_export_dict['DisplayName'] = topic.display_name # Subscriptions if len(topic.subscriptions) > 0: cfn_export_dict['Subscription'] = [] for subscription in topic.subscriptions: sub_dict = {} if references.is_ref(subscription.endpoint): param_name = 'Endpoint{}'.format(topic_logical_id) parameter = self.create_cfn_parameter( param_type='String', name=param_name, description='SNSTopic Endpoint value', value=subscription.endpoint, ) endpoint = parameter else: endpoint = subscription.endpoint sub_dict['Endpoint'] = endpoint sub_dict['Protocol'] = subscription.protocol cfn_export_dict['Subscription'].append(sub_dict) topic_resource = troposphere.sns.Topic.from_dict( 'Topic' + topic_logical_id, cfn_export_dict) topic.topic_resource = topic_resource template.add_resource(topic_resource) if topic.codestar_notification_access: statement = Statement( Effect=Allow, Sid='CodeStarNotificationAccess', Principal=Principal( "Service", 'codestar-notifications.amazonaws.com'), Action=[awacs.sns.Publish], Resource=[troposphere.Ref(topic_resource)], ) statement_list.append(statement) # Add CloudWatch service statement = Statement( Effect=Allow, Sid='CloudWatchService', Principal=Principal("Service", 'cloudwatch.amazonaws.com'), Action=[awacs.sns.Publish], Resource=[troposphere.Ref(topic_resource)], ) statement_list.append(statement) if topic.cross_account_access: account_id_list = [ account.account_id for account in self.paco_ctx.project.accounts.values() ] for account_id in account_id_list: if account_id in topic_policy_cache: continue topic_policy_cache.append(account_id) statement = Statement( Effect=Allow, Sid=self.create_cfn_logical_id_join(account_id), Principal=Principal("AWS", f'arn:aws:iam::{account_id}:root'), Action=[awacs.sns.Publish, awacs.sns.Subscribe], Resource=[troposphere.Ref(topic_resource)], ) statement_list.append(statement) if len(statement_list) > 0: topic_policy_resource = troposphere.sns.TopicPolicy( f'Paco{topic_logical_id}TopicPolicy', Topics=[troposphere.Ref(topic_resource)], PolicyDocument=Policy(Version='2012-10-17', Id="PacoSNSTopicPolicy", Statement=statement_list)) template.add_resource(topic_policy_resource) # Topic Outputs if grp_id == None: output_ref = stack.resource.paco_ref_parts else: output_ref = '.'.join( [stack.resource.paco_ref_parts, topic.name]) self.create_output(title='SNSTopicArn' + topic_logical_id, value=troposphere.Ref(topic_resource), ref=output_ref + '.arn') self.create_output( title='SNSTopicName' + topic_logical_id, value=troposphere.GetAtt(topic_resource, "TopicName"), ref=output_ref + '.name', )
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.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())
Condition, Policy, Statement, StringEquals, ) import iam_utils cloud_mgmt_platform_arn = 'arn:aws:iam::032298565451:root' readonly_access_policy = Policy( Statement=[ Statement( Effect=Allow, Action=[ec2.DescribeInstances], Resource=['*'], ), ] ) modifyinstances_access_policy = Policy( Statement=[ Statement( Effect=Allow, Action=[ec2.StartInstances, ec2.StopInstances], Resource=['*'], ), ] )
role_name = 'easy-describe' role_arn = 'arn:aws:iam::%s:role/%s' % (customer_id, role_name,) sts_conn = boto.sts.STSConnection() now_plus_60 = datetime.datetime.utcnow() + datetime.timedelta(seconds=60) big_iso_time = now_plus_60.isoformat() iso_time = big_iso_time[:big_iso_time.rfind('.')] + 'Z' reduced_access_policy = Policy( Statement=[ Statement( Effect=Allow, Action=[ec2.DescribeInstances], Resource=['*'], # This reduction of policy knocks our creds down to only working # until iso_time. Kind of useful to work around the minimum # validity period of STS creds is 15 minutes. Condition=Condition(DateLessThan('aws:CurrentTime', iso_time)), ), ] ) def do_tags(token): # Using the temporary creds, run DescribeInstances ec2_conn = boto.ec2.connect_to_region('us-west-2', **token.to_boto_dict()) instances = ec2_conn.get_only_instances() for instance in instances: print instance.id, instance.tags try:
Allows the role to be assumed by `cmp_account_id`. """ import boto.iam import iam_utils from awacs.aws import Allow, Policy, Statement, AWSPrincipal from awacs import ec2, iam, sts cmp_account_id = '032298565451' access_policy = Policy( Statement=[ Statement( Effect=Allow, Action=[ec2.DescribeInstances, ec2.CreateTags], Resource=['*'], ), ] ) print access_policy.to_json() cloud_mgmt_platform_arn = 'arn:aws:iam::%s:root' % (cmp_account_id,) trust_policy = Policy( Statement=[ Statement( Effect=Allow, Action=[sts.AssumeRole], Principal=AWSPrincipal(cloud_mgmt_platform_arn), ), ],