Search code examples
bashgithubgithub-actions

Git actions branch


So I have two secrets: DEV_SERVER_IP and MASTER_SERVER_IP. in main.yml I need something like this

 run: echo "::set-env name=BRANCH_NAME::$(echo ${GITHUB_REF#refs/heads/} | sed 's/\//_/g')"   

     run: ssh-keyscan -H ${{ secrets.BRANCH_NAME_SERVER_IP }} >> ~/.ssh/known_hosts

but am getting error

  env:
    BRANCH_NAME: dev
Error: Input required and not supplied: key

I need here something like this ssh-keyscan -H ${{ secrets.${BRANCH_NAME}_SERVER_IP }}

how can I fix this?


Solution

  • You're trying to use shell style logic inside a Github context expansion (${{ ... }}) which won't work. Just move all your logic into your shell script instead:

    name: Example
    
    on:
      push:
    
    jobs:
      example:
        runs-on: ubuntu-latest
        steps:
          - name: get target ip
            env:
              DEV_SERVER_IP: ${{ secrets.DEV_SERVER_IP }}
              MAIN_SERVER_IP: ${{ secrets.MAIN_SERVER_IP }}
            run: |
              branch_name=$(sed 's|/|_|g' <<< ${GITHUB_REF#refs/heads/})
              target="${branch_name^^}_SERVER_IP"
              mkdir -p ~/.ssh
              ssh-keyscan -H ${!target} >> ~/.ssh/known_hosts
              cat ~/.ssh/known_hosts
    

    In the above workflow, the expression ${branch_name^^} is a bash expression that returns the value of $branch_name in uppercase, and ${!target} is a bash expression that returns the value of the variable who name is stored in $target.

    Note that I'm not using your "set the BRANCH_NAME environment variable" task because the ::set-env command is disabled by default for security reasons.