Use github actions to add deploy key to repo? - github-actions

I'm trying to find out if it's possible to add a deploy key with GitHub actions. I have already generates key with ssh-keygen and tried to add it manually which works. But I would like to add my generated key with GitHub actions as well.
In other words I want to do this "GitHub -> repo -> settings -> deploy keys -> add deploy key (the generated key during workflow)" but I want to do it with GitHub actions if it's possible.
This is the workflow that i have created so far:
on:
# Triggers the workflow on push or pull request events but only for the master branch
push:
branches: [ main ]
# Allows you to run this workflow manually from the Actions tab
workflow_dispatch:
# A workflow run is made up of one or more jobs that can run sequentially or in parallel
jobs:
# This workflow contains a single job called "build"
build:
# The type of runner that the job will run on
runs-on: ubuntu-latest
if: github.event.repository.name != 'testar-deploy-key'
# Steps represent a sequence of tasks that will be executed as part of the job
steps:
# Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
- uses: actions/checkout#v2
- name: Create deploy key
run: |
# Deploy key
ssh-keygen -m PEM -t rsa -b 4096 -C "mail#mail.com" -o -f id_rsa
#Here i want in someway to add my generated key to the current github repository.
git config --local user.email "action#github.com"
git config --local user.name "GitHub Action"
git add .
git commit -m "Generate SSH"
# Push changes
- name: Push changes
uses: ad-m/github-push-action#master
with:
branch: main
github_token: ${{ secrets.GITHUB_TOKEN }}

Related

Github dispatches workflow Invalid request

I'm trying to trigger a workflow event in Github.
for some reason, I'm able to GET information about my organization repository workflow but can not use '/dispatches'
Work is based on: https://docs.github.com/en/rest/actions/workflows#create-a-workflow-dispatch-event
Here is the curl code:
curl -X POST \
-H "Accept:application/vnd.github.v3+json" \
-H 'Authorization:token ${{ github.token }}' \
'https://api.github.com/repos/[owner/org]/[repo]/actions/workflows/9999999/dispatches' \
-d '{"event_type":"semantic-release"}'
Getting error:
422 Unprocessable Entity
"message": "Invalid request.\n\nFor 'links/0/schema', nil is not an object.",
"documentation_url": "https://docs.github.com/rest/reference/repos#create-a-repository-dispatch-event"
Am I missing some basic information for this to work and trigger an event?
Instead of trying to call the GitHub API directly, try and use the GitHub CLI gh (that you can install first to test locally).
You can also use GitHub CLI in workflows.
GitHub CLI is preinstalled on all GitHub-hosted runners.
For each step that uses GitHub CLI, you must set an environment variable called GITHUB_TOKEN to a token with the required scopes
It has a gh workflow run, which does create a workflow_dispatch event for a given workflow.
Authenticates first (gh auth login, if you are doing a local test):
# authenticate against github.com by reading the token from a file
$ gh auth login --with-token < mytoken.txt
Examples:
# Run the workflow file 'triage.yml' at the remote's default branch
$ gh workflow run triage.yml
# Run the workflow file 'triage.yml' at a specified ref
$ gh workflow run triage.yml --ref my-branch
# Run the workflow file 'triage.yml' with command line inputs
$ gh workflow run triage.yml -f name=scully -f greeting=hello
# Run the workflow file 'triage.yml' with JSON via standard input
$ echo '{"name":"scully", "greeting":"hello"}' | gh workflow run triage.yml --json
In your case (GitHub Action):
jobs:
push:
runs-on: ubuntu-latest
steps:
- run: gh workflow run triage.yml
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
As explained by hanayama in the comments:
Found out the secrets. GITHUB_TOKEN doesn't work, even with permissions edited for the entire workflow.
Using a personal access token worked.

Automate doc build on Github pages when new version is released

On a github repository my_repo, I could correctly set up github actions to trigger build, tests and documentation:
name: CMake
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
env:
# Customize the CMake build type here (Release, Debug, RelWithDebInfo, etc.)
BUILD_TYPE: Release
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout#v2
- name: Install dependencies
run: sudo apt-get install -y --no-install-recommends libboost-all-dev libgdal-dev doxygen graphviz
- name: Configure CMake
run: cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}}
- name: Build
run: cmake --build ${{github.workspace}}/build --config ${{env.BUILD_TYPE}}
- name: Test
working-directory: ${{github.workspace}}/build
run: ctest -C ${{env.BUILD_TYPE}}
- name: Docs
working-directory: ${{github.workspace}}/build
run: make doc
I also implemented Release Drafter to automate the process of bumping versions:
name: Release Drafter
on:
push:
branches:
- master
pull_request:
types: [opened, reopened, synchronize]
jobs:
update_release_draft:
runs-on: ubuntu-latest
steps:
- uses: release-drafter/release-drafter#v5
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
Now, I would like to automate the following:
a major version is released in the repo my_repo
this triggers an event in my Github Pages repo
the documentation is built in my Github Pages repo in the folder softs/my_repo/docs
the website is published (that is equivalent to commiting the changes and pushing the master branch)
I don't exactly know how to implement that. Should I write a github workflow in my Github pages to "listen" what is happening in the my_repo project? Also, I can I forward the version from the my_repo to Doxygen?
I ended up being able to reach my goals. I will post this sample code in case it could benefit the next beginner with Github Action to automate the documentation building:
name: CMake
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
env:
# Customize the CMake build type here (Release, Debug, RelWithDebInfo, etc.)
BUILD_TYPE: Release
jobs:
build:
# The CMake configure and build commands are platform agnostic and should work equally well on Windows or Mac.
# You can convert this to a matrix build if you need cross-platform coverage.
# See: https://docs.github.com/en/free-pro-team#latest/actions/learn-github-actions/managing-complex-workflows#using-a-build-matrix
runs-on: ubuntu-latest
steps:
- uses: actions/checkout#v2
with:
# we want to find git tags to pass version to doxygen
fetch-depth: 0
- name: Install quetzal and Doxygen dependencies
run: sudo apt-get install -y --no-install-recommends libboost-all-dev libgdal-dev doxygen graphviz
- name: Configure CMake
# Configure CMake in a 'build' subdirectory. `CMAKE_BUILD_TYPE` is only required if you are using a single-configuration generator such as make.
# See https://cmake.org/cmake/help/latest/variable/CMAKE_BUILD_TYPE.html?highlight=cmake_build_type
run: cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}}
- name: Build
# Build your program with the given configuration
run: cmake --build ${{github.workspace}}/build --config ${{env.BUILD_TYPE}}
- name: Test
working-directory: ${{github.workspace}}/build
# Execute tests defined by the CMake configuration.
# See https://cmake.org/cmake/help/latest/manual/ctest.1.html for more detail
run: ctest -C ${{env.BUILD_TYPE}}
- name: Generate documentation
working-directory: ${{github.workspace}}/build
# this is defined in the repo docs/CMakeLists.txt file
run: make docs
- name: Moving Files
run: |
mv ${{github.workspace}}/build/docs/html ./docs/api
# Deploy to GitHub Pages
- name: Deploy
uses: peaceiris/actions-gh-pages#v3
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: ./
In the project/docs/CMakeLists.txt:
# look for Doxygen package
# Require dot, treat the other components as optional
find_package(Doxygen
REQUIRED dot
OPTIONAL_COMPONENTS mscgen dia)
if(DOXYGEN_FOUND)
# exclude sqlite code
set(DOXYGEN_EXCLUDE_PATTERNS
*/sqlite3/*
)
# doxygen settings can be set here, prefixed with "DOXYGEN_"
set(DOXYGEN_PROJECT_NAME "my-project")
set(DOXYGEN_INPUT "mainpage.md")
set(DOXYGEN_USE_MDFILE_AS_MAINPAGE "mainpage.md")
set(DOXYGEN_EXCLUDE_PATTERNS "README.md")
set(DOXYGEN_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/docs")
# this target will only be built if specifically asked to.
# run "make docs" to create the doxygen documentation
doxygen_add_docs(
docs
${PROJECT_SOURCE_DIR}
COMMENT "Generate API-documents for NoteSearch."
)
endif(DOXYGEN_FOUND)
To automatically retrieve the version number and pass it to Doxygen (as well as to the C++ code), I could adapt the solution given by Brian Milco here: https://ipenguin.ws/2012/11/cmake-automatically-use-git-tags-as.html .
They posted the solution in 2012, so there may be easier ways to do the same thing in 2022. But, as far as I am concerned, it works for me!
In the root CMakeLists.txt:
cmake_minimum_required(VERSION 3.5 FATAL_ERROR)
#
# VERSIONING
#
# Appends the cmake/modules path to MAKE_MODULE_PATH variable.
set(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules ${CMAKE_MODULE_PATH})
include(GetGitRevisionDescription)
git_describe(VERSION --tags --dirty=-d)
#parse the version information into pieces.
string(REGEX REPLACE "^v([0-9]+)\\..*" "\\1" VERSION_MAJOR "${VERSION}")
string(REGEX REPLACE "^v[0-9]+\\.([0-9]+).*" "\\1" VERSION_MINOR "${VERSION}")
string(REGEX REPLACE "^v[0-9]+\\.[0-9]+\\.([0-9]+).*" "\\1" VERSION_PATCH "${VERSION}")
string(REGEX REPLACE "^v[0-9]+\\.[0-9]+\\.[0-9]+(.*)" "\\1" VERSION_SHA1 "${VERSION}")
set(VERSION_SHORT "${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}")
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules/version.cpp.in
${CMAKE_CURRENT_BINARY_DIR}/version.cpp)
set(version_file "${CMAKE_CURRENT_BINARY_DIR}/version.cpp")
#Add the version_file to the executables being built or it won't compile.
#add_executable(${PROJECT_NAME} ${source_files} ${ui_files} ${version_file})
#
# PROJECT DESCRIPTION
#
project(
"project_name"
LANGUAGES CXX
VERSION ${VERSION_SHORT}
This sets the CMake project version to the automatically retrieved git version tag, and it is passed to the Doxygen module by a default on set(DOXYGEN_PROJECT_NUMBER $(PROJECT_VERSION).
A complete working solution can be find on my project at https://github.com/Becheler/quetzal-CoalTL/commit/2ef5851cc6a34391d7a9ea64fb7c7122feb23b0a

Using deployer with github actions to deploy private repository

I'm trying to deploy a PHP Project using github action
The connection on the target server works but I'm stuck at the part when deployer tries to clone the repository.
I'm storing a private ssh key in the github secret in order to access the server and I try to use the same ssh key to access the github repository (the key is added in the deploy key of the repository).
Here the command that fails :
cd {releasePath} && (/usr/bin/git clone -b "develop" --recursive git#github.com:arnaudschaeffer/myprivaterepo.git {releasePath} /releases/3 2>&1)
Command failed with exit code 1: bin/dep deploy staging -vvv
Deployer works from my local environment. I can make it work with both my personnal SSH Keys and the one I've had in a secret in order to connect to the target server.
Here's my github yml file :
# This is a basic workflow to help you get started with Actions
name: Deploy develop
# Controls when the action will run.
on:
# Triggers the workflow on push or pull request events but only for the main branch
push:
branches: [ develop ]
# Allows you to run this workflow manually from the Actions tab
workflow_dispatch:
# A workflow run is made up of one or more jobs that can run sequentially or in parallel
jobs:
deploy:
name: Deploy to develop
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout#v2
with:
ref: 'develop'
ssh-key: ${{ secrets.SSH_PRIVATE_KEY }}
persist-credentials: true
- name: Setup PHP
uses: shivammathur/setup-php#v2
with:
php-version: 7.4
- name: Configure SSH
env:
SSH_PRIVATE_KEY: ${{ secrets.SSH_PRIVATE_KEY }}
SSH_HOST: ${{ secrets.SSH_HOST }}
SSH_USER: ${{ secrets.SSH_USER }}
SSH_PORT: ${{ secrets.SSH_PORT }}
run: |
mkdir -p ~/.ssh/
echo "$SSH_PRIVATE_KEY" > ~/.ssh/staging.key
chmod 600 ~/.ssh/staging.key
cat >>~/.ssh/config <<END
Host github
Hostname github.com
IdentityFile ~/.ssh/staging.key
IdentitiesOnly yes
Host host_name
HostName $SSH_HOST
User $SSH_USER
Port $SSH_PORT
IdentityFile ~/.ssh/staging.key
StrictHostKeyChecking no
END
- name: Set Up Deployer
run: |
curl -LO https://deployer.org/deployer.phar && mkdir bin && mv deployer.phar bin/dep && sudo chmod +x bin/dep
# Add deploy key in GitHub account
- name: Deploy
uses: deployphp/action#master
with:
private-key: ${{ secrets.SSH_PRIVATE_KEY }}
#Both target server and github known hosts
known-hosts: ${{ secrets.KNOWN_HOSTS }}
dep: deploy staging -vvv
Is there some extra step to clone the repository in deployer ?
Thank in advance !

GitHub action to run command and add commit if I type comment

My objective is to get to the point where I can type /run-black as a comment on a pull request in GitHub, and then GitHubActions will run black . on the pull request's branch and add a commit.
The use case is that sometimes casual contributors make a small pull request to my library (e.g. fixing a typo), and I'd like to be able to just write a comment like /run-black to have the black formatter run on their files before I merge.
Use the action Slash Command Dispatch. Add a repo scoped PAT with the name PAT to your secrets and create two workflows with the following definitions.
name: Slash Command Dispatch
on:
issue_comment:
types: [created]
jobs:
slashCommandDispatch:
runs-on: ubuntu-latest
steps:
- name: Slash Command Dispatch
uses: peter-evans/slash-command-dispatch#v2
with:
token: ${{ secrets.PAT }}
issue-type: pull-request
commands: |
run-black
on:
repository_dispatch:
types: [run-black-command]
jobs:
runBlack:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout#v2
with:
repository: ${{github.event.client_payload.pull_request.head.repo.full_name}}
ref: ${{github.event.client_payload.pull_request.head.ref}}
token: ${{ secrets.PAT }}
- name: Slash Command Dispatch
run: black .
- run: |
git config --local user.email "41898282+github-actions[bot]#users.noreply.github.com"
git config --local user.name "github-actions[bot]"
git commit -m "Run black" -a
git push

Tagging, and building and uploading a python library

I have a github action that runs when a branch is merged into master. It should tag the repo with a version number that it obtains from setup.py, and then push the tag. It should then build the package and upload it to a package repository.
Progress so far: Building and uploading works, tagging does not
name: Deploy Library
on [push]
jobs:
build:
runs-on: ubuntu latest
steps:
- uses: actions/checkout#master
- name: Set up Python env
uses: actions/setup-python#v1
with:
python-version: '3.6'
- name: Install Deps
run: |
python -m pip install --upgrade pip
pip install wheel
pip install twine
- name: Build
run: |
python setup.py build bdist_wheel
- name: Tag
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
VERSION=*sed magic on setup.py*
git tag v$VERSION
git push origin v$VERSION
Everything works except for the git push at the end. The logs complain about the need for a username and password (I only have the GITHUB_TOKEN), and anyway, actions/checkout didn't complain...
I've checked the github actions page, and I can't find one relating to tagging.
The actions/checkout#v1 action leaves the git repository in a detached HEAD state. So in order to push back to the repository there are a few steps required.
Set git config for the user you want to be the commit author:
git config --global user.name 'My User'
git config --global user.email 'myuser#example.com'
Set the remote:
git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}#github.com/username/repository
You may also need to checkout. You can extract the branch name from the GITHUB_REF:
git checkout "${GITHUB_REF:11}"
Related questions and answers:
Push to origin from GitHub action
Unable to commit and push back changes made by github action (invalid user)