Have to destroy and re-deploy pipeline stack after replacing Github token - amazon-web-services

I uses CDK to create and deploy pipeline(with AWS CodePipeline https://aws.amazon.com/codepipeline/), and today Source stage stopped working, complaining about insufficient permission, which turns out to be that the Github token is expired. Error:
"Could not access the GitHub repository: "pandaWebsite". The access token might be invalid or has been revoked. Edit the pipeline to reconnect with GitHub."
So I re-genereate the Github token, and updated it in AWS Secrets Manager. And click "Retry" button in pipeline, and it still failed. Eventually I have to run cdk destroy to destroy the pipeline, and run cdk deploy to re-deploy the pipeline, and then it works.
My question is, why I have to destroy and re-deploy the pipeline? I was expecting that once I updated the token in Secrets Manager, it should just work.
More context
AWS Secrets Manager is where I stored the Github token, and my CDK code fetch from it. See code here:
// Add Source stage to fetch code from GitHub repository.
private addSourceStage(
pipeline: codepipeline.Pipeline,
sourceCode: codepipeline.Artifact
) {
pipeline.addStage({
stageName: "Source",
actions: [
new codepipeline_actions.GitHubSourceAction({
actionName: "Checkout",
owner: "yangliu",
repo: "pandaWebsite",
branch: "main",
// read the value from Secrets Manager
oauthToken: CDK.SecretValue.secretsManager(
"github-token"
),
output: sourceCode,
trigger: codepipeline_actions.GitHubTrigger.WEBHOOK,
}),
],
});
}

Related

AWS CodePipeline CDK TypeScript

The install commands in the Build Step of the AWS CodePipeline do not update when there are changes made in the AWS CDK Code (TypeScript) and are pushed to the repository. The Buildspec section under the Build details of the project has the same configuration as when it was created.
Is there a way to fix it? We've made some changes to the BuildStep CDK but does not take effect on the AWS CodeBuild configuration details. I'm only new to AWS CodeBuild and CodePipeline. Any answer/suggestion would be a great help.
Sample Code
const pipeline = new CodePipeline(this, 'SamplePipeline', {
pipelineName: 'SamplePipeline',
synth: new CodeBuildStep('BuildSynthStep', {
input: source,
buildEnvironment: {
buildImage: codebuild.LinuxBuildImage.STANDARD_5_0
},
installCommands: [
'install_command_1',
'install_command_2',
...
'install_command_n'
],
commands: [
'command_2',
...
'command_n'
],
}
)
});
Artifact Provider: Amazon S3
The self-mutation of a CDK Pipeline is only applied, when you change something on an application stage (precisely CDK Stage) or other phases after the synth codebuild job.
If you have something running before, e.g. unit tests, then you won't get into the self-update job.
So, what are your options now?
Well, changes according to a pipeline itself are mostly done manually.
So you have to re-run a cdk deploy PipelineStack on your local machine with your changes committed to the source branch aside.

How to provide Docker Credentials for AWS CodeBuild automatic image pull

I have a CodeBuild project that pulls an image from a public Docker repository. I'm running into the known issue of too many pulls, so I want to login to Docker and pull the image because I have a valid Docker license.
However, I can't seem to find any documentation on how to set my credentials in CodeBuild. The only examples I see, are logging in via the buildspec.yml and then pulling the docker image. This does not work for me because I'm setting the docker image in the CodeBuild configuration.
I'm using CDK and this is my current CodeBuild configuration:
const myCodeBuild = new codeBuild.Project(this, 'myCodeBuild', {
source: githubsrc,
secondarySources: [ githubsrc2 ],
role: new BuildRole(this, 'myCodeBuildRole').role,
buildSpec: codeBuild.BuildSpec.fromObject(buildSpec),
environment: {
buildImage: codeBuild.LinuxBuildImage.fromDockerRegistry('salesforce/salesforcedx:latest-rc-full'
},
});
This creates a CodeBuild project that will automatically use the provided Docker Image. There is never a chance to login before it is pulled.
fromDockerRegistry supports authentication. To use it, create a Secrets Manager secret that contains the username and password fields with your Docker Hub credentials and pass it to the function. (Documentation reference for the secret format)
Using the example from the docs:
environment: {
buildImage: codebuild.LinuxBuildImage.fromDockerRegistry('my-registry/my-repo', {
secretsManagerCredentials: secrets,
}),
},
secrets is your Secrets Manager secret here.

Trigger an aws-amplify build via aws-cdk

I am creating a aws-amplify app via aws-cdk and everything works fine except it doesn't start a build automatically. If I do a git commit (I have enabled continuous deploys) it will build and run just fine. But on a new aws account with a cdk deploy I have to start the first commit manually...
I had this issue as well while working on the deployment of an amplify hosted application.
After going through the AWS CLI documentation for Amplify, I found the start-job command. This command allows you to start an amplify job for a specific branch.
You can then create an AwsCustomResource that makes an SDK call to start-job.
This is what I ended up with.
const build_trigger = new customResource.AwsCustomResource(this, 'triggerAppBuild', {
policy: customResource.AwsCustomResourcePolicy.fromSdkCalls({
resources: customResource.AwsCustomResourcePolicy.ANY_RESOURCE
}),
onCreate: {
service: 'Amplify',
action: 'startJob',
physicalResourceId: customResource.PhysicalResourceId.of('app-build-trigger'),
parameters: {
appId: amplifyApp.appId,
branchName: master.branchName,
jobType: 'RELEASE',
jobReason: 'Auto Start build',
}
},
});
Note that you should replace amplifyApp.apiId and master.branchName with your own app ID and branch name. I am using the amplify-alpha, so you may need to get the App ID and branch name another way.
Amplify app builds are triggered by push events. Use a CDK Custom Resource or its simpler cousin Trigger to generate a push event during the CDK stack creation.
For a github repo, for instance, your Trigger construct's lambda would call the Github webhook test API, which will trigger the hook with the latest push to the current repository. Both Custom Resources and Triggers can be configured to run only on stack creation. Remember to give your lambda any necessary repo credentials (e.g. set environment variables via a secret).

How to connect github repo with aws using cdk?

Im learning aws cdk and trying to make a code pipeline.
i created personal access key on github and saved it on aws secret manager.
then in my cdk stack i wrote`
pipeline.addStage({
stageName:"Source",
actions:[
new CodePipelineAction.GitHubSourceAction({
actionName: 'CheckOut',
owner: 'Mahmood787',
repo: "aws-pipeline",
oauthToken: cdk.SecretValue.secretsManager('github2'),
output:sourceOutput,
branch:"master"
})
]
});
on cdk deploy im getting this error
Webhook could not be registered with GitHub. Error cause: Invalid credentials [StatusCode: 401, Body: {"message":"Bad credentials","documentation_url":"https://docs.github.com/rest"}]
is there anything im missing?

AWS Codepipeline Github Webhook not being registered through cloudformation

I am trying to set AWS codepipeline and use github as the source by using cloudformation. The github repository is owned by an organization and I have admin access to it.
I was able to create webhook and successfully create entire service through codepipeline UI. But when I am trying to do same thing through Cloudformation Document, it returns error
Webhook could not be registered with GitHub. Error cause: Not found [StatusCode: 404, Body: {"message":"Not Found","documentation_url":"https://developer.github.com/v3/repos/hooks/#create-a-hook"}]
I used same credential both times (OAuth token in cloudformation and actual login popups in codepipeline UI), but when I do it through Cloudformation it failed.
I suspected my cloudformation document was the issue. But when I create my own repository, cloudformation successfully create webhook and created full codepipeline service.
Below is the summary of tests I did to understand where it went wrong.
Codepipeline UI. Organization Github Repo. It asked to login the github. Logged in with my admin credential => successfully created webhook and services.
Cloudformation. Organization Github Repo. Used OAuth Token from admin credential with repo and admin:repo_hook enabled. => Gave out error above
Cloudformation. Personal Github Repo. Used Oauth Token from admin credential with repo and admin:repo_hook enabled => successfully created webhook and services
The following is portion of cloudformation document where I create Webhook.
AppPipelineWebhook:
Type: 'AWS::CodePipeline::Webhook'
Properties:
Authentication: GITHUB_HMAC
AuthenticationConfiguration:
SecretToken: !Ref GitHubSecret
Filters:
- JsonPath: $.ref
MatchEquals: 'refs/heads/{Branch}'
TargetPipeline: !Ref cfSSMAutomationDev
TargetAction: SourceAction
Name: AppPipelineWebhook
TargetPipelineVersion: !GetAtt cfSSMAutomationDev.Version
RegisterWithThirdParty: true
So I am not sure what is wrong. My suspicion is that OAuth token requires more privilege. Does anyone have similar experience with this? Any suggestion is much appreciated
Even I was facing the same issue, by seeing codepipeline UI configuration's Repository I used
{
"Configuration": {
"Owner": "myUserName",
"Repo": "orgname/repository-name",
}
}
so cloudformation was checking for the repository myUserName/orgname/repository-name which wasn't exist.
It got solved after following the below solution:
{
"Configuration": {
"Owner": "orgname",
"Repo": "repository-name",
}
}
private repo -> ownerName: YourUserName
organisation repo -> ownerName: OrganisationName