The most common and secure way to access GitHub or Bitbucket repositories from AWS is to use AWS CodeStar connection. You can follow this link to create a connection to your external repositories in GitHub, GitHub Enterprise and Bitbucket. After creating a connection, you get the connection arn in the following format:

arn:aws:codestar-connections:us-east-1:123456789012:connection/ff4ae225-60db-44d3-8d0e-ff6db6360727

Now, using this connection you can access the external repositories and pull/push code changes. We can simply use the git command as per normal. As an example, the following command clones a git repository. We just need to use the AWS CodeStar connection arn for our repositories when cloning.

git clone https://codestar-connections.[Region].amazonaws.com/git-http/[AccountID]/[Region]/[arn's unique identifier]/[github owner's name or organization name]/[repo name].git

For example the following clones one of my git repositories called dotfiles:

git clone https://codestar-connections.us-east-1.amazonaws.com/git-http/123456789012/us-east-1/ff4ae225-60db-44d3-8d0e-ff6db6360727/pooyavahidi/dotfiles.git

The following is an example of buildspec.yml file in a CodeBuild project. In the following example, I used amazonlinux2 image to first clone the repository, then create a change and push that change back to the github repo.

version: 0.2
env:
  git-credential-helper: yes
phases:
  build:
    commands:
      - git clone https://codestar-connections.us-east-1.amazonaws.com/git-http/123456789012/us-east-1/ff4ae225-60db-44d3-8d0e-ff6db6360727/pooyavahidi/dotfiles.git
      - cd dotfiles
      - echo "test" >> file1.txt
      - git config --global user.name "codebuild-test"
      - git config --global user.email "codebuild-test"
      - git add .
      - git commit -m "commit from codebuild"
      - git push

Required IAM Permission

In order to use codestar connection you need to have the required IAM access permission. The following statement gives permission to use all of the AWS CodeStar connections within the specified account. You can add this to the IAM policies where you want to access codestar connection (for example, in the policy for your CodeBuild role).

...
    {
        "Effect": "Allow",
        "Action": [
            "codestar-connections:UseConnection"
        ],
        "Resource": [
            "arn:aws:codestar-connections:us-east-1:123456789012:*"
        ]
    }