This sample repo shows various capabilities of terraform to create dynamic infrastructure using lists, maps, loops and more applied to VMs, Networking and some other resources as well.
It creates:
- A new Resource Group.
- A Windows VM.
- A CentOs VM.
- An Ubuntu VM.
- A RedHat VM.
- A VNet with multiple subnets that could be defined in multiple ways (lists, maps, etc.).
- Security Groups.
- Storage Account.
This project has the following files which make them easy to reuse, add or remove.
├── LICENSE
├── README.md
├── WindowsVMVar.tf
├── centOSVM.tf
├── centOSVMvar.tf
├── cloud-init-jenkins.yaml
├── cloud-init.yaml
├── main.tf
├── mainVar.tf
├── networking.tf
├── networkingVar.tf
├── outputs.tf
├── redHatVM.tf
├── redHatVMVar.tf
├── security.tf
├── securityVar.tf
├── storageVar.tf
├── storage.tf
├── ubuntuVM.tf
├── ubuntuVMVar.tf
├── vmVar.tf
└── windowsVM.tf
It is assumed that you have azure CLI installed and configured. More information on this topic here. I recommend using a Service Principal with a certificate for authentication specially if you are using this as part of your Ci/CD pipeline.
- Terraform 0.12.7
- AzureRM provider 1.33.1
- Azure CLI 2.17.1
Linux uses key based authentication and it assumes you already have a key and you can configure the path using the sshKeyPath variable in vmVar.tf
. You can create one using this command:
ssh-keygen -t rsa -b 4096 -m PEM -C [email protected] -f ~/.ssh/vm_ssh
and set it using this approach:
export TF_VAR_sshKeyPath=`cat ~/.ssh/vm_ssh.pub`
Linux VMs also show integration with cloud init to customize the VM by installing or making some configurations at provisioning time. You can customize this behavior by modifying these files:
- cloud-init-jenkins.yaml
- cloud-init.yaml
Windows authentication uses user name and password. It is not recommended setting these values in terraform scripts. You can set them as Environment variables. More information about this approach can be found here.
These variables vmUserName and password that you should set up using this approach and they are also located in vmVar.tf
:
export TF_VAR_vmUserName={{VMUSER}}
export TF_VAR_password={{VMPASSWORD}}
Starting with terraform 0.14 you can also set all these credentials as sensitive. More information here.
Just run these commands to initialize terraform, get a plan and approve it to apply it.
terraform fmt
terraform init
terraform validate
terraform plan
terraform apply
I also recommend using a remote state instead of a local one. You can change this configuration in main.tf
You can create a free Terraform Cloud account here.
It will destroy everything that was created.
terraform destroy --force
Be aware that by running this script your account might get billed.
- Marcelo Zambrana