Home > other >  AWS-CDK Pipelines Cross Account Stack Removal
AWS-CDK Pipelines Cross Account Stack Removal

Time:12-18

I am using pipelines in aws-cdk to automate builds / deployments for a number of different accounts but when destroying the pipeline / stacks in the pipeline, the stacks are not removed in the target account. Is there a destroy / removal setting for the pipeline to remove destroyed stacks? I see things removed in the account where the pipeline is run from, but not in other accounts.

CodePudding user response:

This is not available in CDK. You have to do it manually with CloudFormation afterwards. It also doesn't destroy the deleted stacks in the same environment, not only in cross-account scenarios. Can you clarify where you're seeing the pipeline remove the stack in the same account? This shouldn't happen.

To automate this, you'd have to implement it yourself as part of the pipeline.

CodePudding user response:

Your Pipeline cannot automatically delete its deployed stacks for you, neither in CDK nor in with the CodePipeline APIs.

With some effort, though, you can script pipeline stack deletion with the SDKs. Here's a script to get a list a Pipeline's deployed stack ARNs from the Pipeline's state. The CloudFormation SDK has a delete_stack command, which you can use actually delete the stacks.

import re
import boto3
from mypy_boto3_codepipeline.type_defs import ActionStateTypeDef

session = boto3.Session(profile_name='pipeline', region_name='us-east-1')
client = session.client('codepipeline')

# get a list of the pipeline stages and actions
res = client.get_pipeline_state(name="QueenbPipeline")

stack_arns = []

# helper to extract the arn from an action type
def extract_arn(a: ActionStateTypeDef) -> str:
  url = a['latestExecution']['externalExecutionUrl']
  return re.match(r'^.*stackId=(.*)(?:/[a-f0-9-]{36})$', url).group(1)

# extract the arns
deploy_states = [s for s in res['stageStates'] if ".Deploy" in s['stageName']]

for state in deploy_states:
  actions = [extract_arn(a) for a in state['actionStates'] if ".Deploy" in a['actionName']]
  stack_arns.extend(actions)

print(stack_arns)

Output - the Pipeline's deployed stacks

[
  'arn:aws:cloudformation:us-west-1:123456789012:stack/ReplicationStack',
  'arn:aws:cloudformation:us-central-1:123456789012:stack/CoreStack',
  'arn:aws:cloudformation:us-central-1:123456789012:stack/ApiStack'
]
  • Related