To run an Ansible playbook from GitHub Actions, the runner needs SSH access to your managed nodes. Here's a step-by-step guide:
1. Prepare SSH Keys
Generate a dedicated SSH key pair (if you haven't already):
bash Copy code
ssh-keygen -t ed25519 -f github-actions -N ""
Add the public key (github-actions.pub) to ~/.ssh/authorized_keys on all managed nodes.
Securely store the private key (github-actions) as a GitHub repository secret named SSH_PRIVATE_KEY.
2. Configure Ansible Inventory
Create an inventory file (e.g., inventory.ini) in your repo:
ini Copy code
[webservers]
node1 ansible_host=192.168.1.10
node2 ansible_host=192.168.1.11
[all:vars]
ansible_user=ubuntu # SSH user for all nodes
3. GitHub Actions Workflow
Create .github/workflows/ansible.yml:
yaml Copy code
name: Run Ansible Playbook
on: [push] # Trigger on push events
jobs:
ansible:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Install Ansible
run: sudo apt update && sudo apt install -y ansible
- name: Set up SSH
run: |
mkdir -p ~/.ssh
chmod 700 ~/.ssh
echo "${{ secrets.SSH_PRIVATE_KEY }}" > ~/.ssh/id_ed25519
chmod 600 ~/.ssh/id_ed25519
# Trust hosts (disable strict host key checking)
echo -e "Host *\n StrictHostKeyChecking no\n" > ~/.ssh/config
- name: Run playbook
run: ansible-playbook -i inventory.ini site.yml
4. Security Considerations
Host Key Verification (Critical!):
Recommended: Pre-populate known hosts:
bash Copy code
ssh-keyscan your_host_ip >> ~/.ssh/known_hosts
Store the output as a secret SSH_KNOWN_HOSTS and add this step:
yaml Copy code
- name: Add hosts to known_hosts
run: echo "${{ secrets.SSH_KNOWN_HOSTS }}" >> ~/.ssh/known_hosts
Avoid disabling verification unless for testing (security risk).
Secrets Management:
Use GitHub Actions secrets for sensitive data (passwords, API keys).
For Ansible Vault, store the password in a secret and decrypt during the job:
yaml Copy code
- name: Decrypt secrets
run: |
echo "${{ secrets.VAULT_PASSWORD }}" > .vault-pass
ansible-vault decrypt secrets.yml --vault-password-file .vault-pass
5. Troubleshooting Tips
Permission Issues: Ensure the SSH user on managed nodes has sudo access (if needed).
Python Dependency: Managed nodes need Python (Ansible’s only requirement). Add this task if unsure:
yaml Copy code
- name: Install Python
become: yes
raw: apt-get install -y python3
Debugging: Use the -vvv flag in ansible-playbook for verbose output.
Key Files in Your Repo
code Copy code
.
├── .github/
│ └── workflows/
│ └── ansible.yml # GitHub Actions workflow
├── inventory.ini # Ansible inventory
├── site.yml # Main playbook
└── ... # Other playbook files
Final Notes
Test Locally: Ensure your playbook works locally before running in CI.
Minimize Key Exposure: Use a dedicated SSH key with restricted access.
Audit Logs: Regularly check GitHub Actions logs for security.
This setup provides a secure, automated way to deploy changes using Ansible via GitHub Actions.