MCPcopy Create free account
hub / github.com/beelit94/python-terraform / generate_cmd_string

Method generate_cmd_string

python_terraform/terraform.py:214–284  ·  view source on GitHub ↗

For any generate_cmd_string doesn't written as public method of Terraform examples: 1. call import command, ref to https://www.terraform.io/docs/commands/import.html --> generate_cmd_string call: terraform import -input=true aws_instance.foo i-abcd123

(self, cmd: str, *args, **kwargs)

Source from the content-addressed store, hash-verified

212 return self.cmd("init", *args, **options)
213
214 def generate_cmd_string(self, cmd: str, *args, **kwargs) -> List[str]:
215 """For any generate_cmd_string doesn't written as public method of Terraform
216
217 examples:
218 1. call import command,
219 ref to https://www.terraform.io/docs/commands/import.html
220 --> generate_cmd_string call:
221 terraform import -input=true aws_instance.foo i-abcd1234
222 --> python call:
223 tf.generate_cmd_string('import', 'aws_instance.foo', 'i-abcd1234', input=True)
224
225 2. call apply command,
226 --> generate_cmd_string call:
227 terraform apply -var='a=b' -var='c=d' -no-color the_folder
228 --> python call:
229 tf.generate_cmd_string('apply', the_folder, no_color=IsFlagged, var={'a':'b', 'c':'d'})
230
231 :param cmd: command and sub-command of terraform, seperated with space
232 refer to https://www.terraform.io/docs/commands/index.html
233 :param args: arguments of a command
234 :param kwargs: same as kwags in method 'cmd'
235 :return: string of valid terraform command
236 """
237 cmds = cmd.split()
238 cmds = [self.terraform_bin_path] + cmds
239 if cmd in COMMAND_WITH_SUBCOMMANDS:
240 args = list(args)
241 subcommand = args.pop(0)
242 cmds.append(subcommand)
243
244 for option, value in kwargs.items():
245 if "_" in option:
246 option = option.replace("_", "-")
247
248 if isinstance(value, list):
249 for sub_v in value:
250 cmds += [f"-{option}={sub_v}"]
251 continue
252
253 if isinstance(value, dict):
254 if "backend-config" in option:
255 for bk, bv in value.items():
256 cmds += [f"-backend-config={bk}={bv}"]
257 continue
258
259 # since map type sent in string won't work, create temp var file for
260 # variables, and clean it up later
261 elif option == "var":
262 # We do not create empty var-files if there is no var passed.
263 # An empty var-file would result in an error: An argument or block definition is required here
264 if value:
265 filename = self.temp_var_files.create(value)
266 cmds += [f"-var-file={filename}"]
267
268 continue
269
270 # simple flag,
271 if value is IsFlagged:

Callers 2

cmdMethod · 0.95
test_terraform.pyFile · 0.80

Calls 1

createMethod · 0.80

Tested by

no test coverage detected