How to integrate AWS CodeCommit and Slack with AWS CDK

You are working in a company with multiple development teams, building micro-services on AWS. Almost every month, there is a new project where your team need to build a new service in AWS. Probably, one of you first steps of the process is creating a repository on any of the remote version control systems (Github, Bitbucket or AWS CodeCommit) you may use. Your teams has embed in their culture the principle of automating any repetitive task possible. You want that all the services includes the same set of artifacts and skeleton, because is the way you can reduce the cognitive load and onboard new engineers really easy. So, your team has built a CLI tool or small admin panel where you can scaffold a new service. That tool is able to create locally the project with all the necessary scripts and tools including the ones related with the deployment. The owner of the service can go from local to test or even prod really easy and quick. 

Why not also automate with infrastructure as code the way you create the repository that host your code as the same way that you do with project scaffolding?

On this article we will use AWS CDK (in Python) to create a repository in AWS CodeCommit and we will use AWS Chatbot integration to send a notification to specific Slack channel when a pull request is created.

Lego pieces that we will use:

  • AWS CodeCommit
  • AWS CDK
  • Slack
  • Behind the scenes AWS CodeStar notifications and Amazon SNS topic

Identifying Slack details and activate AWS Chatbot app

Our infrastructure will use Slack as target notification consumer. This communication will be done by the web-hook created once we install the AWS Chatbot app in slack. That application will able to send requests with the desire notification. But to set this up, we will need to the gather the following information:

  • Channel name and id that we would like to use to send the notifications of the creation of the pull requests. For instance, you can have a channel for specific repository and add your team to it. We can automate that using Slack API.
  • Workspace id.

Tip: get channel id and workspace id manually

To get channel id and workspace id quickly, open your slack in the browser, the url consist on the following elements: https://app.slack.com/client/{workspaceId}/{channelId} The workspace id will be always the same, so you only need to navigate to the channel that you are interested and grab the id of the channel from the last element path

Next step is to give access to AWS ChatBot to our Slack workspace:

  • Go the AWS ChatBot console > select slack client
  • This will trigger the OAuth page to grant access operations between AWS and Slack. After grant the AWS Chatbot app you will have added in the list of slack apps installed.

Infrastructure as code setup with an AWS CDK app

Now we can start a CDK project with in Python, start a virtual environment and install all the dependencies. Our infra will be provision under one stack. Let’s zoom into the project main stack code:

  1. Create a repository with AWS CodeCommit:
# import aws_cdk.aws_codecommit as codecommit

# Create a repository
repo = codecommit.Repository(
    self,
    'Repository',
    repository_name='my-example-repository',
    description='Example of repository'
)

The Repository class is expecting the following parameters:

  • The identifier of the construct
  • The repository name
  • And the description we may want to give to the repository

In CDK, all consumers of notification are defined as targets, therefore in our case we need to create a target which will be Slack and we will use the details information of above to inject those values in our provision infra, so our services can interact with channels and create messages. It’s important notice, that the CDK implements this target because AWS Chatbot includes the ability of integrate Slack as client. Because this integration is done via SDK and API requests, CDK was able to enable this on its interface.

# import aws_cdk.aws_chatbot as chatbot

# Create slack target
target = chatbot.SlackChannelConfiguration(
    self,
    "MySlackChannel",
    slack_channel_configuration_name="{TARGET_CHANNEL}",
    slack_workspace_id="{WORKSPACE_ID}",
    slack_channel_id="{CHANNEL_ID}"
)

The repository object include a list of events that can trigger notifications according to some repository actions, like for instance: creating a pull request, comments in a pull request, merge code in certain branch. So the next thing in our CDK project is to add the slack target to the event of creating a pull request

repo.notify_on_pull_request_created(
    "NotifyOnPullRequestCreated",
    target
)

That’s it!. This is all the code that we need in our CDK project. We can now deploy it. If we know create a pull request in our repository we will receive in the designated slack channel the following message:

But how is the architecture behind this? which is the infrastructure provisioned by our CDK project? As you now CDK is creating a CloudFormation template behind the scenes, so what is the main components that our template is deploying? Let’s see in detail

System components and interactions

Our CDK app creates the following infrastructure components:

  • Repository in AWS CodeCommit. Nothing fancy so far.
Repository22E53BBD:
    Type: AWS::CodeCommit::Repository
    Properties:
      RepositoryName: my-example-repository
      RepositoryDescription: Example of repository
    Metadata:
      aws:cdk:path: AwsCodeCommitStack/Repository/Resource
  • AWS ChatBot slack channel configuration on the previously created Slack client created:
MySlackChannelA8E0B56C:
    Type: AWS::Chatbot::SlackChannelConfiguration
    Properties:
      ConfigurationName: pull-requests
      IamRoleArn:
        Fn::GetAtt:
          - MySlackChannelConfigurationRole1D3F23AE
          - Arn
      SlackChannelId: YOUR_OWN_CHANNEL_ID
      SlackWorkspaceId: YOUR_OWN_WORKSPACE_ID
    Metadata:
      aws:cdk:path:AwsCodeCommitStack/MySlackChannel/Resource
  • An AWS CodeStar notification. But what is CodeStart notifications?. The notifications feature in the Developer Tools console is a notifications manager for subscribing to events in AWS CodeBuild, AWS CodeCommit, AWS CodeDeploy and AWS CodePipeline. It has its own API, AWS CodeStar Notifications. Behind this subscription is a managed Amazon SNS topic that integrate the notification from the developer tools to be consumed by other services. So the CDK will generate for us the CF to create that link:
RepositoryNotifyOnPullRequestCreated145B6237:
    Type: AWS::CodeStarNotifications::NotificationRule
    Properties:
      DetailType: FULL
      EventTypeIds:
        - codecommit-repository-pull-request-created
      Name: AwsCodeCommitStackRepositoryNotifyOnPullRequestCreatedBE573B5E
      Resource:
        Fn::GetAtt:
          - Repository22E53BBD
          - Arn
      Targets:
        - TargetAddress:
            Ref: MySlackChannelA8E0B56C
          TargetType: AWSChatbotSlack
    Metadata:
      aws:cdk:path: AwsCodeCommitStack/Repository/NotifyOnPullRequestCreated/Resource

The final system design diagram will look something like this. For sake of simplicity I do not include on the article all the IAM roles created to provide access to the services to interact to each other.

Other version control systems also have integration apps to receive notifications in Slack or email, but if you are working fully on AWS and you want to leverage the full potential of the development tools, can be an option for your team.

You can find the code example on the code repository dedicated for the blog: https://github.com/cesiztel/cesarcodecrafter/tree/main/aws-code-commit-cdk-slack

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: