DEV Community

Kevin Mack
Kevin Mack

Posted on • Originally published at welldocumentednerd.com on

Creating Terraform Scripts from existing resources in Azure Government

Lately I’ve been doing a lot of work with TerraForm lately, and one of the questions I’ve gotten a lot is the ability to create terraform scripts based on existing resources.

So the use case is the following: You are working on projects, or part of an organization that has a lot of resources in Azure, and you want to start using terraform for a variety of reasons:

  • Being able to iterating in your infrastructure
  • Consistency of environment management
  • Code History of changes

The good new is there is a tool for that. The tool can be found here on github along with a list of pre-requisites. I’ve used this tool in Azure Commercial and have been really happy with the results. I wanted to use this with Azure Commercial.

NOTE => The Pre-reqs are listed on the az2tf tool, but one they didn’t list I needed to install was jq, using “apt-get install jq”.

Next we need to configure our environment for running terraform. For me, I ran this using the environment I had configured for Terraform. In the Git repo, there is a PC Setup document that walks you through how to configure your environment with VS code and Terraform. I then was able to clone the git repo, and execute the az2tf tool using a Ubuntu subsystem on my Windows 10 machine.

Now, the tool, az2f, was built to work with azure commercial, and there is one change that has to be made for it to leverage azure government

Once you have the environment created, and the pre-requisites are all present, you can open a “Terminal” window in vscode, and connect to Azure Government.

In the ./scripts/resources.sh and ./scripts/resources2.sh files, you will find the following on line 9:

ris=printf “curl -s -X GET -H \”Authorization: Bearer %s\” -H \”Content-Type: application/json\” [https://management.azure.com/subscriptions/%s/resources?api-version=2017-05-10](https://management.azure.com/subscriptions/%25s/resources?api-version=2017-05-10)” $bt $sub

Please change this line to the following:

ris=printf “curl -s -X GET -H \”Authorization: Bearer %s\” -H \”Content-Type: application/json\” [https://management.usgovcloudapi.net/subscriptions/%s/resources?api-version=2017-05-10](https://management.usgovcloudapi.net/subscriptions/%25s/resources?api-version=2017-05-10)” $bt $sub

You can then run the “az2tf” tool by running the following command in the terminal:

./az2tf.sh -s {Subscription ID} -g {Resource Group Name}

This will generate the script, and you will see a new folder created in the structure marked “tf.{Subscription ID}” and inside of it will be all configuration steps to setup the environment.

Top comments (0)