Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

curl 이용하여 Terraform Cloud 의 특정 workspace에서 variables 을 json 으로 가져와서 python에서 변수를 뽑아보았다.

https://www.terraform.io/docs/cloud/api/variables.html

Terraform Cloud 의 변수 가져와 json 파일 만들기

Code Block
TOKEN="xxxxxxxxxxxxxxxx"
curl \
  --header "Authorization: Bearer $TOKEN" \
  --header "Content-Type: application/vnd.api+json" \
"https://app.terraform.io/api/v2/workspaces/ws-xxxxxx/vars" > example-prd

json 파일에서 terraform.tfvar 형태로 변수 파일 만들기

Code Block
#!/usr/bin/env python3

import json
import sys

'''
TOKEN="xxxxxxxxxxxxxxxx"
curl \
  --header "Authorization: Bearer $TOKEN" \
  --header "Content-Type: application/vnd.api+json" \
"https://app.terraform.io/api/v2/workspaces/ws-xxxxxx/vars" > example-prd
'''

tc_json_file = "example-prd"
 
# cat scnt-prd | jq .data > scnt.json
with open(tc_json_file) as f:
  json_data = json.load(f)

json_data_lists=json_data["data"]

for json_data_lis in json_data_lists:
    dict_json_attributes=json_data_lis['attributes']
    #print(dict_json_attributes)
    key = dict_json_attributes['key']
    if key == "TF_VAR_github_token" or key == "AWS_ACCESS_KEY_ID" or key == "AWS_SECRET_ACCESS_KEY" :
        prefix = "#"
    else:
        prefix = ""
    #value = dict_json_attributes['value']
    if dict_json_attributes['value']:
        value = dict_json_attributes['value']
    else:
        value = 'none'
    print(prefix + key + " = " + "\"" + value  + "\"")

...

Code Block
./tfh pullvars  -token xxxxxxxxxxxxxxxxxxxxxx -org xxxxxxxxxxxx -name xxxxxxxxxxxx
| grep ^[a-zA-Z] | sort > var.txt

$ cat var.txt 
a_domain = "aaa"
b_domain = "bbb"