Search code examples
yamlgithub-actions

Triggering yaml file when a certain label is applied to the pull request


I am working on a project where I need to create a tweet from an account whenever a certain issue or pull request has a label issue/tweet

I am able to make tweet when label is applied to issue but unable to do so when the same lable is applied to a pr

the .yml file I am working on

name: Send a Tweet

on:
  issues:
    -label: issue/tweet
  pull_request:
    types: [labeled]

jobs:
  tweet:
    if: ${{github.event.label.name == 'issue/tweet'}}
    runs-on: ubuntu-latest
    steps:
      - uses: ethomson/send-tweet-action@v1
        with:
          status: ${{github.event.issue.html_url}} "#opensource"
          consumer-key: ${{ secrets.TWITTER_CONSUMER_API_KEY }}
          consumer-secret: ${{ secrets.TWITTER_CONSUMER_API_SECRET }}
          access-token: ${{ secrets.TWITTER_ACCESS_TOKEN }}
          access-token-secret: ${{ secrets.TWITTER_ACCESS_TOKEN_SECRET }}

expected to make a tweet when pr is labeled with `issue/tweet'


Solution

  • Let's dissect the important parts...

    Workflow sections

    on events

    You want issues and pull_request to trigger the workflow and I think both of them should have their types set to labeled.

    if job condition

    The condition needs to be applied to the correct object within github.event. For each of these events, the content is different. It's defined in Webhook events and payloads.

    Both issue and pull_request should have github.event.label so I'm not sure why it wouldn't work. It might be a good idea to dump the entire context at the beginning of your job in order to debug it.

    However, both events also have github.event.TYPE.labels, an array of label objects. Therefore, it might be a better option to use that and apply contains expression on it:

    contains(github.event.TYPE.labels.*.name, 'issue/tweet')
    

    Result

    name: Send a Tweet
    
    on:
      issues:
        types: [labeled]
      pull_request:
        types: [labeled]
    
    jobs:
      tweet:
        if: >-
          (
            contains(github.event.pull_request.labels.*.name, 'issue/tweet') ||
            contains(github.event.issue.labels.*.name, 'issue/tweet')
          )
        runs-on: ubuntu-latest
        steps:
          - uses: crazy-max/ghaction-dump-context@v1
          - uses: ethomson/send-tweet-action@v1
            with:
              status: ${{github.event.issue.html_url}} "#opensource"
              consumer-key: ${{ secrets.TWITTER_CONSUMER_API_KEY }}
              consumer-secret: ${{ secrets.TWITTER_CONSUMER_API_SECRET }}
              access-token: ${{ secrets.TWITTER_ACCESS_TOKEN }}
              access-token-secret: ${{ secrets.TWITTER_ACCESS_TOKEN_SECRET }}