Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

F/fix partition python #381

Merged
merged 7 commits into from
Nov 8, 2021
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions resources/OrganizationAccountAccessRole.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
AWSTemplateFormatVersion: "2010-09-09"
Description: >
Organizational Account Access Role for Cross-Account automation

Parameters:
RoleName:
Type: String
Description: >-
The name of the Cross-Account role
Default: OrganizationAccountAccessRole
AdministratorAccountId:
Type: String
Description: >-
AWS Account Id of the administrator account
(the account in which StackSets will be created).
MaxLength: 12
MinLength: 12

Resources:
OrganizationAccountAccessRole:
Type: AWS::IAM::Role
Properties:
RoleName: !Ref RoleName
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
AWS:
- !Ref AdministratorAccountId
Action:
- sts:AssumeRole
Path: /
ManagedPolicyArns:
- !Sub arn:${AWS::Partition}:iam::aws:policy/AdministratorAccess

Outputs:
RoleArn:
Description: The ARN of the Organization Account Access Role
Value: !GetAtt OrganizationAccountAccessRole.Arn
Export:
Name: !Sub "${AWS::StackName}-RoleArn"
4 changes: 2 additions & 2 deletions samples/sample-ec2-with-codedeploy/template.yml
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ Resources:
Fn::Sub: ${Environment}-public-subnet-1b
- Fn::ImportValue:
Fn::Sub: ${Environment}-public-subnet-1c
SecurityGroups:
SecurityGroups:
- !Ref 'PublicLoadBalancerSG'
ApplicationLoadBalancerHTTPListener:
Type: "AWS::ElasticLoadBalancingV2::Listener"
Expand Down Expand Up @@ -251,4 +251,4 @@ Outputs:
Description: The url of the external load balancer
Value: !Join ['', ['http://', !GetAtt 'PublicLoadBalancer.DNSName']]
Export:
Name: 'LoadBalancerExternalUrl'
Name: 'LoadBalancerExternalUrl'
24 changes: 12 additions & 12 deletions samples/sample-ecr-repository/template.yml
Original file line number Diff line number Diff line change
@@ -1,22 +1,22 @@
# // Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# // SPDX-License-Identifier: Apache-2.0

AWSTemplateFormatVersion: '2010-09-09'
AWSTemplateFormatVersion: "2010-09-09"
Description: ADF CloudFormation Sample Template (Shared ECR Repository)
Metadata:
License: Apache-2.0
Parameters:
TestingAccountId:
Description: Testing Accound Id that will pull from this repository
Description: Testing Account Id that will pull from this repository
Type: String
ProductionAccountId:
Description: Production Accound Id that will pull from this repository
Description: Production Account Id that will pull from this repository
Type: String
Resources:
SampleAppRepository:
Type: AWS::ECR::Repository
Properties:
RepositoryName: 'sample-node-app'
RepositoryName: "sample-node-app"
LifecyclePolicy:
LifecyclePolicyText: !Sub
- |
Expand Down Expand Up @@ -48,21 +48,21 @@ Resources:
}
- DaysToRetainUntaggedContainerImages: 2
MaxTaggedContainerImagesToRetain: 2
RepositoryPolicyText:
RepositoryPolicyText:
Version: "2012-10-17"
Statement:
Statement:
- Sid: AllowPull
Effect: Allow
Principal:
AWS:
- !Sub "arn:aws:iam::${TestingAccountId}:root"
- !Sub "arn:aws:iam::${ProductionAccountId}:root"
Action:
Principal:
AWS:
- !Sub "arn:${AWS::Partition}:iam::${TestingAccountId}:root"
- !Sub "arn:${AWS::Partition}:iam::${ProductionAccountId}:root"
Action:
- "ecr:Get*"
- "ecr:Describe*"
- "ecr:BatchGetImage"
- "ecr:BatchCheckLayerAvailability"

Outputs:
Outputs:
SampleAppRepository:
Value: !GetAtt SampleAppRepository.Arn
24 changes: 12 additions & 12 deletions samples/sample-expunge-vpc/template.yml
Original file line number Diff line number Diff line change
@@ -1,30 +1,30 @@
AWSTemplateFormatVersion: '2010-09-09'
AWSTemplateFormatVersion: "2010-09-09"
Transform: AWS::Serverless-2016-10-31
Description: Deploys the Custom Resource for deleting the default VPC in all regions
Resources:
LambdaVPCPolicyRole:
Type: 'AWS::IAM::Role'
Type: "AWS::IAM::Role"
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service: 'lambda.amazonaws.com'
Service: "lambda.amazonaws.com"
Action:
- 'sts:AssumeRole'
Path: '/'
- "sts:AssumeRole"
Path: "/"
ManagedPolicyArns:
- 'arn:aws:iam::aws:policy/AmazonVPCFullAccess'
- 'arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole'
- !Sub "arn:${AWS::Partition}:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
- !Sub "arn:${AWS::Partition}:iam::aws:policy/AmazonVPCFullAccess"
Policies:
- PolicyName: ec2
PolicyDocument:
Statement:
- Effect: Allow
Action:
- 'ec2:DescribeRegions'
Resource: '*'
- "ec2:DescribeRegions"
Resource: "*"
DeleteVPCLambda:
Type: AWS::Serverless::Function
Properties:
Expand All @@ -35,8 +35,8 @@ Resources:
Runtime: python3.8
Timeout: 600
Environment:
Variables:
region_name: !Ref "AWS::Region"
Variables:
region_name: !Ref "AWS::Region"
DeleteVPCCustom:
Type: Custom::DeleteVPC
Properties:
Expand Down
16 changes: 8 additions & 8 deletions samples/sample-iam/template.yml
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
# // Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# // SPDX-License-Identifier: Apache-2.0

AWSTemplateFormatVersion: '2010-09-09'
AWSTemplateFormatVersion: "2010-09-09"
Description: ADF CloudFormation Sample Template (IAM)
Metadata:
License: Apache-2.0
Resources:
DevelopersIAMGroup:
Type: AWS::IAM::Group
Properties:
Properties:
GroupName: adf-sample-developers-group
ManagedPolicyArns:
- 'arn:aws:iam::aws:policy/AWSServiceCatalogEndUserFullAccess'
- 'arn:aws:iam::aws:policy/AWSCloud9User'
- 'arn:aws:iam::aws:policy/AWSCloudFormationReadOnlyAccess'
- 'arn:aws:iam::aws:policy/AWSCodeCommitFullAccess'
- 'arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess'
- !Sub "arn:${AWS::Partition}:iam::aws:policy/AWSServiceCatalogEndUserFullAccess"
- !Sub "arn:${AWS::Partition}:iam::aws:policy/AWSCloud9User"
- !Sub "arn:${AWS::Partition}:iam::aws:policy/AWSCloudFormationReadOnlyAccess"
- !Sub "arn:${AWS::Partition}:iam::aws:policy/AWSCodeCommitFullAccess"
- !Sub "arn:${AWS::Partition}:iam::aws:policy/AmazonS3ReadOnlyAccess"
GlobalInstanceProfile:
Type: "AWS::IAM::InstanceProfile"
Properties:
Expand Down Expand Up @@ -75,7 +75,7 @@ Resources:
Action:
- "sts:AssumeRole"
ManagedPolicyArns:
- "arn:aws:iam::aws:policy/service-role/AWSCodeDeployRole"
- !Sub "arn:${AWS::Partition}:iam::aws:policy/service-role/AWSCodeDeployRole"
RoleName: "codedeploy-service-role"
Outputs:
DevelopersIAMGroup:
Expand Down
18 changes: 9 additions & 9 deletions samples/sample-service-catalog-product/productX/template.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,35 +5,35 @@ AWSTemplateFormatVersion: '2010-09-09'
Description: ADF CloudFormation Sample Service Catalog Product
Metadata:
License: Apache-2.0
Parameters:
Parameters:
Environment:
Type: String
Default: testing
AllowedValues:
AllowedValues:
- testing
Description: The environment to use, IDE are only supported in testing
InstanceType:
InstanceType:
Type: String
Default: t3.micro
AllowedValues:
AllowedValues:
- t3.micro
- m5.large
Description: Enter t3.micro or m5.large. Default is t3.micro.
AutomaticStopTimeInMinutes:
AutomaticStopTimeInMinutes:
Type: Number
Default: 480
AllowedValues:
- 480
- 960
Description: The amount of minutes that this Cloud9 Instance should stop after (8 or 16 hours).
InstanceDescription:
InstanceDescription:
Type: String
Default: "Development environment used during office hours"
Description: The Description of the Cloud9 Instance.
InstanceName:
InstanceName:
Type: String
Description: The name of the Cloud9 Instance.
UserName:
UserName:
Type: String
Description: Your IAM UserName that will be used as the OwnerArn in the Cloud9 Instance.
Resources:
Expand All @@ -44,7 +44,7 @@ Resources:
Description: !Ref InstanceDescription
InstanceType: !Ref InstanceType
Name: !Ref InstanceName
OwnerArn: !Sub "arn:aws:iam::${AWS::AccountId}:user/${UserName}" #In this sample case 'sample-developer' from the IAM stack can be used here
OwnerArn: !Sub "arn:${AWS::Partition}:iam::${AWS::AccountId}:user/${UserName}" #In this sample case 'sample-developer' from the IAM stack can be used here
SubnetId:
Fn::ImportValue:
Fn::Sub: ${Environment}-public-subnet-1a # Imported from sample-vpc
34 changes: 23 additions & 11 deletions src/lambda_codebase/account_bootstrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,12 @@
from cloudformation import CloudFormation
from s3 import S3
from sts import STS
from partition import get_partition

# Globals taken from the lambda environment variables
S3_BUCKET = os.environ["S3_BUCKET_NAME"]
REGION_DEFAULT = os.environ["AWS_REGION"]
PARTITION = get_partition(REGION_DEFAULT)
LOGGER = configure_logger(__name__)


Expand All @@ -33,11 +35,13 @@ def configure_generic_account(sts, event, region, role):
are required for the global.yml in all target accounts.
"""
try:
deployment_account_id = event['deployment_account_id']
cross_account_access_role = event['cross_account_access_role']
role_arn = f'arn:{PARTITION}:iam::{deployment_account_id}:role/{cross_account_access_role}'

deployment_account_role = sts.assume_cross_account_role(
'arn:aws:iam::{0}:role/{1}'.format(
event['deployment_account_id'],
event['cross_account_access_role']
), 'configure_generic'
role_arn=role_arn,
role_session_name='configure_generic'
)
parameter_store_deployment_account = ParameterStore(
event['deployment_account_region'],
Expand All @@ -59,6 +63,7 @@ def configure_generic_account(sts, event, region, role):
parameter_store_target_account.put_parameter('bucket_name', bucket_name)
parameter_store_target_account.put_parameter('deployment_account_id', event['deployment_account_id'])


def configure_master_account_parameters(event):
"""
Update the Master account parameter store in us-east-1 with the deployment_account_id
Expand All @@ -69,6 +74,7 @@ def configure_master_account_parameters(event):
parameter_store_deployment_account_region = ParameterStore(event['deployment_account_region'], boto3)
parameter_store_deployment_account_region.put_parameter('deployment_account_id', event['account_id'])


def configure_deployment_account_parameters(event, role):
"""
Applies the Parameters from adfconfig plus other essential
Expand All @@ -83,16 +89,21 @@ def configure_deployment_account_parameters(event, role):
value
)


def is_inter_ou_account_move(event):
return not event["source_ou_id"].startswith('r-') and not event["destination_ou_id"].startswith('r-')


def lambda_handler(event, _):
sts = STS()

account_id = event["account_id"]
cross_account_access_role = event["cross_account_access_role"]
role_arn = f'arn:{PARTITION}:iam::{account_id}:role/{cross_account_access_role}'

role = sts.assume_cross_account_role(
'arn:aws:iam::{0}:role/{1}'.format(
event["account_id"],
event["cross_account_access_role"]
), 'master_lambda'
role_arn=role_arn,
role_session_name='master_lambda'
dsudduth marked this conversation as resolved.
Show resolved Hide resolved
)

if event['is_deployment_account']:
Expand All @@ -112,13 +123,14 @@ def lambda_handler(event, _):
deployment_account_region=event["deployment_account_region"],
role=role,
wait=True,
stack_name=None, # Stack name will be automatically defined based on event
# Stack name will be automatically defined based on event
stack_name=None,
s3=s3,
s3_key_path=event["full_path"],
account_id=event["account_id"]
account_id=account_id
)
if is_inter_ou_account_move(event):
cloudformation.delete_all_base_stacks(True) #override Wait
cloudformation.delete_all_base_stacks(True) # override Wait
cloudformation.create_stack()
if region == event["deployment_account_region"]:
cloudformation.create_iam_stack()
Expand Down
Loading