Install Git and Create Your First Repository: Commits, Branches and Remotes
Why Git #
Git keeps the history of your files. For infrastructure as code this means every change to Terraform or Ansible is reviewed, versioned and reversible, and a pipeline such as GitHub Actions can run on every push.
Install and configure #
sudo apt update && sudo apt install -y git # macOS: brew install git
git --version
git config --global user.name "Your Name"
git config --global user.email "you@example.com"
git config --global init.defaultBranch main
git config --global pull.rebase true
First repository #
mkdir infra && cd infra
git init
echo "# infra" > README.md
git status
git add README.md
git commit -m "Add README"
git log --oneline
A commit is a snapshot of the files you added with git add (the staging area). Write messages that say what changed and why.
.gitignore: what must never be committed #
.terraform/
*.tfstate
*.tfstate.backup
*.tfvars
.env
*.pemState files and credentials contain secrets. If one is committed, deleting it later does not remove it from the history: rotate the secret. See Terraform secrets management.
Branches #
git switch -c add-vpc # create and move to a branch
# edit files...
git add -A && git commit -m "Add VPC module"
git switch main
git merge add-vpc # or open a pull request instead
git branch -d add-vpc
The usual flow is a short branch per change, a pull request for review and a merge into main.
Connect to GitHub with SSH #
ssh-keygen -t ed25519 -C "you@example.com"
cat ~/.ssh/id_ed25519.pub # paste it in GitHub > Settings > SSH keys
ssh -T git@github.com
git remote add origin git@github.com:your-user/infra.git
git push -u origin main
This uses public key authentication. Keys can also sign commits; see GnuPG.
Everyday commands #
git pull # update
git diff # unstaged changes; --staged for staged ones
git restore file.tf # discard changes in a file
git commit --amend # fix the last commit (not after pushing)
git stash / git stash pop # park changes
git log --graph --oneline --all
git revert <commit> # undo a pushed commit with a new commit
Next steps #
Use Git as the source of truth for a cluster with Argo CD, or run Terraform from a pipeline with GitHub Actions and AWS OIDC.