Aller au contenu principal

AWS CodeCommit


1 - Présentation

AWS CodeCommit est un service de contrôle de source entièrement managé qui héberge des repositories Git privés et sécurisés.


2 - Authentification

2.1 Options d'authentification

MéthodeDescriptionRecommandé
HTTPS + Git credentialsUsername/password IAM✅ Simple
SSHClés SSH✅ Développeurs
AWS CLI credential helperUtilise AWS credentialsPour scripts

2.2 Configuration HTTPS

# Générer des credentials Git pour IAM User
# Console AWS > IAM > Users > Security credentials > HTTPS Git credentials

# Configurer Git
git config --global credential.helper '!aws codecommit credential-helper $@'
git config --global credential.UseHttpPath true

# Cloner un repo
git clone https://git-codecommit.eu-west-1.amazonaws.com/v1/repos/mon-repo

2.3 Configuration SSH

# Générer une clé SSH
ssh-keygen -t rsa -b 4096 -f ~/.ssh/codecommit_rsa

# Uploader la clé publique dans IAM
# Console AWS > IAM > Users > Security credentials > SSH keys

# Configurer ~/.ssh/config
cat >> ~/.ssh/config << EOF
Host git-codecommit.*.amazonaws.com
User APKA... # SSH Key ID from IAM
IdentityFile ~/.ssh/codecommit_rsa
EOF

# Tester la connexion
ssh git-codecommit.eu-west-1.amazonaws.com

# Cloner avec SSH
git clone ssh://git-codecommit.eu-west-1.amazonaws.com/v1/repos/mon-repo

3 - Gestion des repositories

3.1 Créer un repository

# Via CLI
aws codecommit create-repository \
--repository-name mon-application \
--repository-description "Application principale" \
--tags Project=MonProjet,Environment=Development

# Lister les repos
aws codecommit list-repositories

# Détails d'un repo
aws codecommit get-repository --repository-name mon-application

3.2 Via CloudFormation

# codecommit.yaml
AWSTemplateFormatVersion: '2010-09-09'
Description: CodeCommit Repository

Resources:
ApplicationRepository:
Type: AWS::CodeCommit::Repository
Properties:
RepositoryName: mon-application
RepositoryDescription: Application principale
Tags:
- Key: Project
Value: MonProjet

Outputs:
RepositoryCloneUrlHttp:
Value: !GetAtt ApplicationRepository.CloneUrlHttp
RepositoryCloneUrlSsh:
Value: !GetAtt ApplicationRepository.CloneUrlSsh
RepositoryArn:
Value: !GetAtt ApplicationRepository.Arn

4 - Branches et protections

4.1 Créer une branche

# Créer une branche
aws codecommit create-branch \
--repository-name mon-application \
--branch-name feature/nouvelle-fonctionnalite \
--commit-id abc123...

# Lister les branches
aws codecommit list-branches --repository-name mon-application

# Informations sur une branche
aws codecommit get-branch \
--repository-name mon-application \
--branch-name main

4.2 Approval Rules (Protection)

# Créer un template d'approbation
aws codecommit create-approval-rule-template \
--approval-rule-template-name "RequireTwoApprovals" \
--approval-rule-template-description "Require 2 approvals for PRs" \
--approval-rule-template-content '{
"Version": "2018-11-08",
"DestinationReferences": ["refs/heads/main"],
"Statements": [{
"Type": "Approvers",
"NumberOfApprovalsNeeded": 2,
"ApprovalPoolMembers": ["*"]
}]
}'

# Associer au repository
aws codecommit associate-approval-rule-template-with-repository \
--approval-rule-template-name "RequireTwoApprovals" \
--repository-name mon-application

5 - Pull Requests

5.1 Créer une Pull Request

# Créer une PR
aws codecommit create-pull-request \
--title "Ajout nouvelle fonctionnalité" \
--description "Cette PR ajoute..." \
--targets repositoryName=mon-application,sourceReference=feature/ma-feature,destinationReference=main

# Lister les PRs
aws codecommit list-pull-requests \
--repository-name mon-application \
--pull-request-status OPEN

# Détails d'une PR
aws codecommit get-pull-request --pull-request-id 1

5.2 Commenter et approuver

# Ajouter un commentaire
aws codecommit post-comment-for-pull-request \
--pull-request-id 1 \
--repository-name mon-application \
--before-commit-id abc123 \
--after-commit-id def456 \
--content "LGTM! Quelques suggestions..."

# Approuver la PR
aws codecommit update-pull-request-approval-state \
--pull-request-id 1 \
--revision-id abc123... \
--approval-state APPROVE

# Merger la PR
aws codecommit merge-pull-request-by-fast-forward \
--pull-request-id 1 \
--repository-name mon-application

6 - Triggers et notifications

6.1 Triggers vers Lambda

# Créer un trigger
aws codecommit put-repository-triggers \
--repository-name mon-application \
--triggers '[
{
"name": "TriggerOnPush",
"destinationArn": "arn:aws:lambda:eu-west-1:123456789:function:OnCodePush",
"customData": "custom-data",
"branches": ["main", "develop"],
"events": ["all"]
}
]'

6.2 Lambda pour traitement

# lambda_function.py
import json

def lambda_handler(event, context):
# Extraire les informations du push
for record in event['Records']:
codecommit_event = record['codecommit']
references = codecommit_event['references']

for ref in references:
branch = ref['ref'].replace('refs/heads/', '')
commit_id = ref['commit']

print(f"Push to {branch}: {commit_id}")

# Déclencher des actions personnalisées
if branch == 'main':
# Notifier, démarrer des tests, etc.
pass

return {
'statusCode': 200,
'body': json.dumps('Processed successfully')
}

6.3 Notifications avec SNS

# Via CloudFormation
NotificationRule:
Type: AWS::CodeStarNotifications::NotificationRule
Properties:
Name: codecommit-notifications
DetailType: FULL
Resource: !GetAtt Repository.Arn
EventTypeIds:
- codecommit-repository-pull-request-created
- codecommit-repository-pull-request-merged
- codecommit-repository-comments-on-pull-requests
Targets:
- TargetType: SNS
TargetAddress: !Ref NotificationTopic

7 - Bonnes pratiques

7.1 Structure de branches

7.2 Politique IAM restrictive

{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowReadOnAllRepos",
"Effect": "Allow",
"Action": [
"codecommit:Get*",
"codecommit:List*",
"codecommit:GitPull"
],
"Resource": "*"
},
{
"Sid": "AllowPushToDevelop",
"Effect": "Allow",
"Action": [
"codecommit:GitPush"
],
"Resource": "arn:aws:codecommit:*:*:mon-application",
"Condition": {
"StringEqualsIfExists": {
"codecommit:References": [
"refs/heads/develop",
"refs/heads/feature/*"
]
}
}
},
{
"Sid": "DenyPushToMain",
"Effect": "Deny",
"Action": "codecommit:GitPush",
"Resource": "*",
"Condition": {
"StringEqualsIfExists": {
"codecommit:References": ["refs/heads/main"]
},
"Null": {
"codecommit:References": "false"
}
}
}
]
}

Résumé

Dans ce chapitre, nous avons appris :

  • La configuration de l'authentification (HTTPS, SSH)
  • La gestion des repositories
  • Les branches et règles d'approbation
  • Les Pull Requests
  • Les triggers et notifications

Prochaine étape

Dans le prochain chapitre, nous explorerons AWS CodeBuild pour automatiser les builds.

→ Chapitre suivant : AWS CodeBuild


← Retour à la table des matières