Dockerizing Azure CLI
Dockerizing Azure CLI is useful when you want to run Azure CLI commands in a containerized environment. I'll share what I lerned step by step in this post.
Why Dockerize Azure CLI?
Azure CLI relies on specific versions of Python and other dependencies, which can conflict with your local environment. Running Azure CLI commands in a Docker container is a great way to avoid dependency issues while keeping your system clean.
Use Case
When multiple team members are working with Terraform to manage Azure resources, they may encounter issues if each stores their tfstate files locally. In this use case, we store tfstate files in an Azure Storage Container.
To allow Terraform to access the Azure Storage Container, it needs the ARM ACCESS KEY. We are storing the ARM ACCESS KEY in Azure Key Vault. We need Azure CLI to retrieve the ARM ACCESS KEY from Azure Key Vault.
The challenge is: How do we fetch the ARM ACCESS KEY inside a Docker container and make it accessible to the host machine?
Prerequisites
- Docker
- Terraform
- An Azure Storage Container for storing the tfstate file
- An Azure Key Vault for storing the ARM ACCESS KEY
Step-by-Step Guide
Step 1: Create a shell script for Azure CLI commands
This script retrieves the Azure Storage Container ARM ACCESS KEY from Azure Key Vault and stores it in a temporary file. Since environment variables inside containers are not accessible from the host, we’ll write the key to a file.
Create a script named tfgetarmhey.sh
with the following content:
Step 2: Create a Dockerfile
I find long commands hard to read and maintain. I prefer to create a Dockerfile to build the image. Here's how to create one:
Step 3: Build the Docker image
Run the following command to build the Docker image:
Step 4: Run bash in the Docker container
- Run the following commands to run the Docker container in interactive mode:
Step 5: Run the shell script in the Docker container:
- Inside the docker container, execute the script:
- Authenticate using your Browser with the provided code and then use your credentials. Press Enter to continue until the shell is available.
- Once complete, type
exit
to leave the Docker container.
Step 6: Set the Environment Variable on the Host Machine
To use the ARM ACCESS KEY in Terraform on the host machine:
- Extract the ARM ACCESS KEY from the Docker container:
- Clean up the Docker container:
- Initialize Terraform with the ARM ACCESS KEY to set up the backend:
Conclusion
By Dockerizing Azure CLI, you can securely manage Azure resources without polluting your local environment. This setup is particularly useful in collaborative scenarios where environment consistency is critical. Let me know in the comments if you encounter any issues or have suggestions to improve this workflow!