Question

How can I pass secrets in GitHub Actions to an Ansible playbook?

Answer and Explanation

To securely pass secrets from GitHub Actions to an Ansible playbook, you can leverage GitHub's secrets management feature and Ansible's ability to receive variables. Here's a comprehensive approach:

1. Store Secrets in GitHub:

- Navigate to your GitHub repository's "Settings" tab.

- Click on "Secrets" -> "Actions".

- Add your secrets as environment variables. For instance, create a secret named SSH_PRIVATE_KEY, API_TOKEN, or DB_PASSWORD.

2. Define the GitHub Actions Workflow:

- Create a .github/workflows/your-workflow.yml file in your repository.

- Define a job that runs your Ansible playbook. In this job, access the secrets using the secrets context.

3. Pass Secrets as Environment Variables:

- Use the env section in your workflow to define environment variables using the GitHub secrets.

- The syntax is ${{ secrets.YOUR_SECRET_NAME }}.

4. Example GitHub Actions Workflow YAML File:

yaml name: Deploy with Ansible
on:
  push:
    branches: [ main ]
jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v3
      - name: Set up Python
        uses: actions/setup-python@v4
        with:
          python-version: '3.x'
      - name: Install Ansible
        run: pip install ansible
      - name: Run Ansible Playbook
        env:
          SSH_PRIVATE_KEY: ${{ secrets.SSH_PRIVATE_KEY }}
          API_TOKEN: ${{ secrets.API_TOKEN }}
        run: ansible-playbook -i inventory.ini deploy.yml --extra-vars "api_token=$API_TOKEN"

5. Access Secrets in Ansible Playbook:

- Access the environment variables within your Ansible playbook using the lookup plugin with the env option.

- Alternatively, pass the environment variables as extra variables (as demonstrated above) and reference them directly.

6. Example Ansible Playbook:

yaml - hosts: all
  tasks:
    - name: Print API Token
      debug:
        msg: "API Token is: {{ api_token }}"
    - name: Use SSH Private Key (Example)
      command: echo "Using SSH Key"       environment:
        SSH_PRIVATE_KEY: "{{ lookup('env', 'SSH_PRIVATE_KEY') }}"

7. Using --extra-vars:

- In the GitHub Actions workflow, you are passing secrets as extra variables: --extra-vars "api_token=$API_TOKEN". Now, in your Ansible playbook, you can directly use {{ api_token }}.

8. Important Security Considerations:

- Never commit secrets directly to your repository.

- Avoid printing or logging secrets unnecessarily.

- Use vault for more complex secret management within Ansible itself.

By following these steps, you can securely pass secrets from GitHub Actions to your Ansible playbook, ensuring that sensitive information is protected and properly managed during your CI/CD processes. Remember to adjust variable names and commands to fit your specific use case and always prioritize security best practices.

More questions