Complete Source file here :https://gitlab.com/imkiran13/terraform-modules-cicd.git
GitLab CI Configuration
Access CI/CD Settings:
- Navigate to your project, then go to
Settings
>CI/CD
.
- Navigate to your project, then go to
Upload Secure Files:
Under the "Secure Files" section, upload your PEM file.
Add CI/CD Variables:
Scroll to "Variables" and click "Add."
Add the following masked variables:
AWS_ACCESS_KEY_ID
AWS_SECRET_ACCESS_KEY
Set Up a New GitLab Runner:
Navigate to
Runners
and select "New project runner."Choose "Linux" and set the following:
Tags:
Terraform,AWS
Description: A brief description of your runner.
Timeout: 600 seconds.
Click "Create Runner
.
Using tfenv
To manage different Terraform versions easily, we will use tfenv
. Follow these steps:
Install tfenv:
Follow the instructions available on the tfenv GitHub page.
Manual
- Check out tfenv into any path (here is
${HOME}/.tfenv
)
- Check out tfenv into any path (here is
git clone --depth=1 https://github.com/tfutils/tfenv.git ~/.tfenv
- Add
~/.tfenv/bin
to your$PATH
any way you like
bash:
echo 'export PATH="$HOME/.tfenv/bin:$PATH"' >> ~/.bash_profile
3.On Ubuntu/Debian touching /usr/local/bin
might require sudo access, but you can create ${HOME}/bin
or ${HOME}/.local/bin
and on next login it will get added to the session $PATH
or by running . ${HOME}/.profile
it will get added to the current shell session's $PATH
.
mkdir -p ~/.local/bin/
. ~/.profile
ln -s ~/.tfenv/bin/* ~/.local/bin
which tfenv
Install the Required Terraform Version:
sudo apt install unzip tfenv list-remote # Lists all available versions tfenv install 1.5.5 # Installs the specified version
Installing GitLab Runner
Install GitLab Runner:
Open your console and follow the installation commands provided on the GitLab Runner page
.
Register the Runner:
Enter the token and name for the runner, choose "shell" as the executor
.
Modify Your Code and Push:
- Make minor changes to your code and push it. This should trigger the CI/CD pipeline.
Run Commands as gitlab-runner:
cat /etc/passwd sudo rm -r /home/gitlab-runner/.bash_logout su - gitlab-runner # Switch to gitlab-runner user
Deploying an Ubuntu Server
Log into the server and deploy the necessary infrastructure using your Terraform scripts.
Cleaning Up
To destroy the infrastructure, run:
terraform destroy -auto-approve
You can use Checkov, a free tool, to scan your Terraform code for security issues:
apt install -y python3-pip
Troubleshooting
If you encounter errors:
Check the GitLab CI/CD pipeline logs for error messages.
Google any error codes for potential solutions.
Conclusion
This setup provides a streamlined approach to managing infrastructure with Terraform in a GitLab CI/CD environment. Feel free to customize the configurations as needed to fit your specific requirements.
For further assistance, refer to the official Terraform documentation or GitLab CI/CD documentation.