Created
January 18, 2024 09:56
-
-
Save Bogyie/b10605d8196b899770c3672898538be7 to your computer and use it in GitHub Desktop.
terraform import
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from dataclasses import dataclass | |
from typing import List | |
import yaml | |
import os | |
IMPORT_TEMP_FILE="__import_temp.tf" | |
IMPORT_CONFIG_FILE="import_config.yaml" | |
@dataclass | |
class Resource: | |
name: str | |
_id: str | |
def code(self, _type: str): | |
return "\n".join(("import {", f"to={_type}.{self.name}", f"id={self._id}", "}")) | |
@dataclass | |
class Import: | |
_type: str | |
resources: List[Resource] | |
def code(self): | |
return "\n".join([r.code(self._type) for r in self.resources]) | |
def generate_code(filename: str): | |
os.system(f"terraform plan -generate-config-out=__{filename}.tf") | |
def generate_file_by_resource_name(imports: List[Import]): | |
for i in imports: | |
for r in i.resources: | |
with open(IMPORT_TEMP_FILE, mode="w") as f: | |
f.write(r.code()) | |
generate_code(r.name) | |
def generate_file_by_resource_type(imports: List[Import]): | |
for i in imports: | |
with open(IMPORT_TEMP_FILE, mode="w") as f: | |
f.write(i.code()) | |
generate_code(i._type) | |
def generate_file_one(imports: List[Import]): | |
with open(IMPORT_TEMP_FILE, mode="w") as f: | |
f.write("\n".join([i.code() for i in imports])) | |
generate_code("__generated.tf") | |
def main(): | |
""" | |
- type: foo | |
resources: | |
- name: bar | |
id: baz | |
""" | |
with open(IMPORT_CONFIG_FILE, mode="r") as f: | |
import_config_plain = yaml.load(f.read(), Loader=yaml.FullLoader) | |
import_config = [ | |
Import(i["type"], [ | |
Resource(r["name"], r["id"]) for r in i["resources"] | |
]) for i in import_config_plain | |
] | |
import_func = [ | |
generate_file_by_resource_name, | |
generate_file_by_resource_type, | |
generate_file_one, | |
][0] | |
import_func(import_config) | |
if __name__ == "__main__": | |
main() | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- type: foo1 | |
resources: | |
- name: bar1 | |
id: baz1 | |
- name: bar2 | |
id: baz2 | |
- type: foo2 | |
resources: | |
- name: bar1 | |
id: baz1 | |
- name: bar2 | |
id: baz2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
👍