Vous êtes sur la page 1sur 14

def lambda_handler(event, context):

import boto3

import traceback

import sys

import time

import json

#import pdb

AccountId = 802169185211

#AccountId = event['AccountId']

region = 'us-east-1'

user = 'test'

client = boto3.client('sts')

role = 'arn:aws:iam::'+str(AccountId)+':role/OrganizationAccountAccessRole'

print (role)

res = client.assume_role(

RoleArn=role,

RoleSessionName=user

acc_key = res['Credentials']['AccessKeyId']

sec_key = res['Credentials']['SecretAccessKey']

token = res['Credentials']['SessionToken']

print (acc_key)
#create session to user account to create new role

session =
boto3.Session(aws_access_key_id=acc_key,aws_secret_access_key=sec_key,aws_session_to
ken=token,region_name=region)

Servicecatalog_conn_client1 = session.client('servicecatalog')

service_type = 'servicecatalog'

#source_region is the region for Source AWS account and destination_region is the region
for destination AWS account

source_region = 'us-east-1'

destination_region = 'us-east-1'

#access_key = ''

#secret_key = ''

#Servicecatalog_conn_client = boto3.client(service_type, source_region,


aws_access_key_id=access_key,aws_secret_access_key=secret_key)

Servicecatalog_conn_client = boto3.client(service_type, source_region)

# Now create Portfolios share to copy products to SUB-ACCOUNT

response = Servicecatalog_conn_client.list_portfolios()

portfolio_list = []

for ids in response["PortfolioDetails"]:

portfolio_list.append(ids["Id"])

portfoliolist = portfolio_list

for portid in portfoliolist:

response = Servicecatalog_conn_client.create_portfolio_share(

PortfolioId=portid,
AccountId="802169185211"

# Creating service catalog Portfolios at Destination AWS Account

response = Servicecatalog_conn_client1.create_portfolio(

DisplayName="InnovationLab",

Description="This portfolio will hold product for Innovation Lab users.",

ProviderName="Capgemini"

response = Servicecatalog_conn_client1.create_portfolio(

DisplayName="ProfessionalLab",

Description="This Portfolio will hold hold products for Professional Lab Users",

ProviderName="Capgemini"

response = Servicecatalog_conn_client1.create_portfolio(

DisplayName="PartnerLab",

Description="This Portfolio will hold hold products for Partner Sandbox Lab Users.",

ProviderName="Capgemini"

# Copy service catalog Products from Source Account to destination AWS account"

paginator = Servicecatalog_conn_client.get_paginator('search_products_as_admin')
response = paginator.paginate(

PaginationConfig={

'MaxItems': 3000

out = []

for ids in response:

for j in (ids["ProductViewDetails"]):

out.append(j['ProductARN'])

arn = out

for productarn in arn:

print productarn

response = Servicecatalog_conn_client1.copy_product(

SourceProductArn=productarn,

# Copying Product is Asynchronious process, so please wait for a moment !

time.sleep(150)
# Now remove Portfolios share

response = Servicecatalog_conn_client.list_portfolios()

portfolio_list = []

for ids in response["PortfolioDetails"]:

portfolio_list.append(ids["Id"])

portfoliolist = portfolio_list

for portid in portfoliolist:

response = Servicecatalog_conn_client.delete_portfolio_share(

PortfolioId=portid,

AccountId="802169185211"

# Search common Products for innovation and Professional Labs

paginator1 = Servicecatalog_conn_client1.get_paginator('search_products_as_admin')

response = paginator1.paginate(

Filters={'Owner': ['InnoProLab']},

PaginationConfig={

'MaxItems': 3000

)
product_id = []

for ids in response:

for j in (ids["ProductViewDetails"]):

product_id.append(j['ProductViewSummary']['ProductId'])

prodid = product_id

paginator2 = Servicecatalog_conn_client1.get_paginator('search_products_as_admin')

response = paginator2.paginate(

Filters={'Owner': ['InnovationLab']},

PaginationConfig={

'MaxItems': 3000

product_id1 = []

for ids in response:

for j in (ids["ProductViewDetails"]):

product_id1.append(j['ProductViewSummary']['ProductId'])

prodid1 = product_id1

# Search Products for Partner Lab


paginator3 = Servicecatalog_conn_client1.get_paginator('search_products_as_admin')

response = paginator3.paginate(

PaginationConfig={

'MaxItems': 3000

product_id2 = []

for ids in response:

for j in (ids["ProductViewDetails"]):

product_id2.append(j['ProductViewSummary']['ProductId'])

prodid2 = product_id2

# Find out the Portfolio ID of portfolios from Destination AWS account and Associate
products with portfolios"

response = Servicecatalog_conn_client1.list_portfolios()

portfolio_list = []

portfolio_list1 = []

portfolio_list2 = []

for ids in response["PortfolioDetails"]:


if (ids["DisplayName"]) == "ProfessionalLab":

portfolio_list.append(ids["Id"])

portfoliolist = portfolio_list

else:

if (ids["DisplayName"]) == "InnovationLab":

portfolio_list1.append(ids["Id"])

portfoliolist1 = portfolio_list1

else:

(ids["DisplayName"]) == "PartnerLab"

portfolio_list2.append(ids["Id"])

portfoliolist2 = portfolio_list2

#Assocaite Common products to ProfessionalLab Portfolio

for portid in portfoliolist:

for productid in prodid:

response = Servicecatalog_conn_client1.associate_product_with_portfolio(

ProductId=productid,

PortfolioId=portid

#Assocaite common products to Innovation Lab Portfolio

for portid1 in portfoliolist1:


for productid in prodid:

response = Servicecatalog_conn_client1.associate_product_with_portfolio(

ProductId=productid,

PortfolioId=portid1

#Assocaite Innovation Lab products to InnovationLab Portfolio

for portid1 in portfoliolist1:

for productid1 in prodid1:

response = Servicecatalog_conn_client1.associate_product_with_portfolio(

ProductId=productid1,

PortfolioId=portid1

#Assocaite Partner Lab products to PartnerLab Portfolio

for portid2 in portfoliolist2:

for productid2 in prodid2:

response = Servicecatalog_conn_client1.associate_product_with_portfolio(

ProductId=productid2,

PortfolioId=portid2
)

#create session to user account to create new role

session =
boto3.Session(aws_access_key_id=acc_key,aws_secret_access_key=sec_key,aws_session_to
ken=token)

iam = session.client('iam')

my_managed_policy = {

"Version": "2012-10-17",

"Statement": [

"Effect": "Allow",

"Action": [

"catalog-user:*",

"cloudformation:CreateStack",

"cloudformation:DeleteStack",

"cloudformation:DescribeStackEvents",

"cloudformation:DescribeStacks",

"cloudformation:GetTemplateSummary",

"cloudformation:SetStackPolicy",

"cloudformation:ValidateTemplate",

"cloudformation:UpdateStack",

"cloudformation:ListStacks",

"cloudformation:*",
"servicecatalog:DescribeProduct",

"servicecatalog:DescribeProductView",

"servicecatalog:DescribeProvisioningParameters",

"servicecatalog:ListLaunchPaths",

"servicecatalog:ProvisionProduct",

"servicecatalog:SearchProducts",

"s3:*",

"ec2:*",

"rds:*",

"ecs:*",

"es:*",

"kinesis:*",

"firehose:*",

"elasticache:*",

"dynamodb:*",

"elasticmapreduce:*",

"application-autoscaling:*",

"autoscaling:*",

"cloudwatch:*",

"logs:*",

"iam:*",

"elasticloadbalancing:*",

"SNS:*"

],

"Resource": "*"
},

"Effect": "Allow",

"Action": [

"servicecatalog:DescribeProvisionedProduct",

"servicecatalog:DescribeRecord",

"servicecatalog:ListRecordHistory",

"servicecatalog:ScanProvisionedProducts",

"servicecatalog:TerminateProvisionedProduct",

"servicecatalog:UpdateProvisionedProduct"

],

"Resource": "*",

"Condition": {

"StringEquals": {

"servicecatalog:userLevel": "self"

trust_policy = {

"Version": "2012-10-17",

"Statement": {

"Effect": "Allow",
"Principal": {"Service": ["ec2.amazonaws.com", "servicecatalog.amazonaws.com"],

"AWS": ["arn:aws:iam::293952640683:role/Portal",

"arn:aws:iam::293952640683:root"

},

"Action": "sts:AssumeRole"

policy = iam.create_policy(

PolicyName='ServiceCatalogPolicy',

PolicyDocument=json.dumps(my_managed_policy),

create_role = iam.create_role(

RoleName='ServiceCatalogRole',

AssumeRolePolicyDocument=json.dumps(trust_policy)

#print create_role

rolearn = create_role["Role"]["Arn"]

#print (rolearn)

# Attach a role policy

ServiceCatalogRole=iam.attach_role_policy(

PolicyArn='arn:aws:iam::'+str(AccountId)+':policy/ServiceCatalogPolicy',

RoleName='ServiceCatalogRole'

)
# Findout the Portfolio ID of portfolios from Destination AWS account

response = Servicecatalog_conn_client1.list_portfolios()

portfolio_list = []

for ids in response["PortfolioDetails"]:

portfolio_list.append(ids["Id"])

portfoliolist = portfolio_list

for portid in portfoliolist:

#Attach IAM Group to Service Catalog Portfolios

response = Servicecatalog_conn_client1.associate_principal_with_portfolio(

PortfolioId=portid,

PrincipalARN=rolearn,

PrincipalType='IAM'

Vous aimerez peut-être aussi