Esempio n. 1
0
File: iam.py Progetto: ttaub/stacker
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

    """
    role_name = kwargs.get("role_name", "ecsServiceRole")
    client = boto3.client("iam", region_name=region)

    try:
        client.create_role(
            RoleName=role_name,
            AssumeRolePolicyDocument=get_ecs_assumerole_policy().to_json())
    except ClientError as e:
        if "already exists" in e.message:
            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
Esempio n. 2
0
def create_ecs_service_role(provider, context, **kwargs):
    """Create ecsServieRole, which has to be named exactly that currently.

    http://docs.aws.amazon.com/AmazonECS/latest/developerguide/IAM_policies.html#service_IAM_role

    Args:
        provider (:class:`runway.cfngin.providers.base.BaseProvider`): Provider
            instance. (passed in by CFNgin)
        context (:class:`runway.cfngin.context.Context`): Context instance.
            (passed in by CFNgin)

    Keyword Args:
        role_name (str): Name of the role to create.
            (*default: ecsServiceRole*)

    Returns:
        bool: 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 err:
        if "already exists" in str(err):
            pass
        else:
            raise

    policy = Policy(
        Version="2012-10-17",
        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
Esempio n. 3
0
def build_response(*, principal_id, region, acct_id, apig_id, stage):
    resource_arn = \
        f'arn:aws:execute-api:{region}:{acct_id}:{apig_id}/{stage}/*/responses'
    policy = Policy(Version="2012-10-17",
                    Statement=[
                        Statement(Effect=Allow,
                                  Action=[Invoke],
                                  Resource=[resource_arn])
                    ])
    response = {
        'principalId': principal_id,
        'policyDocument': json.loads(policy.to_json())
    }
    return response
Esempio n. 4
0
def create_ecs_service_role(context: CfnginContext,
                            *,
                            role_name: str = "ecsServiceRole",
                            **_: Any) -> bool:
    """Create ecsServiceRole IAM role.

    https://docs.aws.amazon.com/AmazonECS/latest/developerguide/using-service-linked-roles.html

    Args:
        context: Context instance. (passed in by CFNgin)
        role_name: Name of the role to create.

    """
    client = context.get_session().client("iam")

    try:
        client.create_role(
            RoleName=role_name,
            AssumeRolePolicyDocument=get_ecs_assumerole_policy().to_json(),
        )
    except ClientError as err:
        if "already exists" not in str(err):
            raise
    policy = Policy(
        Version="2012-10-17",
        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
Esempio n. 5
0
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
Esempio n. 6
0
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(Version='2012-10-17',
                    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
Esempio n. 7
0
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 = connect_to_region(region)
    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
Esempio n. 8
0
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
Esempio n. 9
0
def temp_cloudformation_policy(awsclient):
    # policy: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-iam-template.html
    '''
    {
        "Version":"2012-10-17",
        "Statement":[{
            "Effect":"Allow",
            "Action":[
                "cloudformation:CreateStack",
                "cloudformation:DescribeStacks",
                "cloudformation:DescribeStackEvents",
                "cloudformation:DescribeStackResources",
                "cloudformation:GetTemplate",
                "cloudformation:ValidateTemplate"
            ],
            "Resource":"*"
        }]
    }
    '''
    client_iam = awsclient.get_client('iam')
    name = 'unittest_%s_cloudformation_policy' % utils.random_string()
    pd = Policy(
        Version="2012-10-17",
        Id=name,
        Statement=[
            Statement(Effect=Allow,
                      Action=[Action('cloudformation', '*')],
                      Resource=['*']),
        ],
    )

    response = client_iam.create_policy(PolicyName=name,
                                        PolicyDocument=pd.to_json())

    yield response['Policy']['Arn']

    # cleanup
    client_iam.delete_policy(PolicyArn=response['Policy']['Arn'])
Esempio n. 10
0
File: sqs.py Progetto: MaWich/awacs
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())
Esempio n. 11
0
File: s3.py Progetto: somcsel/awacs
            s3.S3_ARN("*"),
        ],
    ),
    Statement(
        Action=[s3.ListBucket],
        Effect=Allow,
        Resource=[s3.S3_ARN("myBucket")],
        Condition=Condition(
            StringEquals({
                's3:prefix': ['', 'home/'],
                's3:delimiter': ['/'],
            }), ),
    ),
    Statement(
        Action=[s3.ListBucket],
        Effect=Allow,
        Resource=[s3.S3_ARN("myBucket")],
        Condition=Condition(StringLike("s3:prefix",
                                       ["home/${aws:username}/*"])),
    ),
    Statement(
        Action=[Action("s3", "*")],
        Effect=Allow,
        Resource=[
            s3.S3_ARN("myBucket/home/${aws:username}"),
            s3.S3_ARN("myBucket/home/${aws:username}/*"),
        ],
    ),
], )
print(pd.to_json())
Esempio n. 12
0
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),
        ),
    ],
)
print trust_policy.to_json()

iam_conn = boto.iam.connect_to_region('universal')
iam_utils.update_policy(
Esempio n. 13
0
    # 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:
            ec2_conn.create_tags(instance.id, {'Key': 'Value'})
        except EC2ResponseError, e:
            if e.error_code != 'UnauthorizedOperation':
                raise
            print 'UnauthorizedOperation! Cannot set tags.'


if __name__ == '__main__':
    # Get AWS to give us a set of temporary credentials that act inside of
    # `customer_id`'s account. Here we specify our reduced access policy which
    # does not specify the CreateTags operation. This means that when we call
    # do_tags it will fail.
    assumed_role = sts_conn.assume_role(
        role_arn, 'sec-403-demo', reduced_access_policy.to_json())
    token = iam_utils.Token(assumed_role.credentials)
    print '------------ Trying with reduced privileges'
    do_tags(token)

    # Here we assume role again, this time without the reduced access policy.
    # The tagging will work
    assumed_role = sts_conn.assume_role(role_arn, 'sec-403-demo')
    token = iam_utils.Token(assumed_role.credentials)
    print '------------ Trying with full privileges'
    do_tags(token)
Esempio n. 14
0
    ]
)

instance_profile_trust = Policy(
    Statement=[
        Statement(
            Effect=Allow,
            Action=[sts.AssumeRole],
            Principal=Principal('Service', 'ec2.amazonaws.com'),
        )
    ]
)

iam_utils.update_policy(
    iam_conn,
    'worker',
    'worker-access-policy',
    instance_profile_trust.to_json(),
    worker_access_policy.to_json(),
    profile=True,
)

iam_utils.update_policy(
    iam_conn,
    'apptier',
    'apptier-access-policy',
    instance_profile_trust.to_json(),
    apptier_access_policy.to_json(),
    profile=True,
)
Esempio n. 15
0
       Statement(
           Effect=Allow,
           Action=[sts.AssumeRole],
           Principal=AWSPrincipal(cloud_mgmt_platform_arn),
           Condition=Condition(
               StringEquals(
                   'sts:ExternalId',
                   '2d6012e95f4942b9b5255274430a4ca2'
                )
            )
        ),
    ],
)

iam_conn = boto.iam.connect_to_region('universal')
iam_utils.update_policy(
    iam_conn,
    'ReadonlyPolicy',
    'ReadonlyPolicy',
    cloud_mgmt_platform_trust_policy.to_json(),
    readonly_access_policy.to_json()
)

iam_utils.update_policy(
    iam_conn,
    'ModifyInstancesPolicy',
    'ModifyInstancesPolicy',
    cloud_mgmt_platform_trust_policy.to_json(),
    modifyinstances_access_policy.to_json()
)