![Terraform - 複数のデプロイメントに同じ tf ファイルを使用しますか?](https://rvso.com/image/717741/Terraform%20-%20%E8%A4%87%E6%95%B0%E3%81%AE%E3%83%87%E3%83%97%E3%83%AD%E3%82%A4%E3%83%A1%E3%83%B3%E3%83%88%E3%81%AB%E5%90%8C%E3%81%98%20tf%20%E3%83%95%E3%82%A1%E3%82%A4%E3%83%AB%E3%82%92%E4%BD%BF%E7%94%A8%E3%81%97%E3%81%BE%E3%81%99%E3%81%8B%3F.png)
resource "aws_instance" "win-example" {
ami = "${lookup(var.WIN_AMIS, var.AWS_REGION)}"
instance_type = "t2.medium"
count="${var.count}"
vpc_security_group_ids = ["${var.security_group_id}"]
key_name = "${aws_key_pair.mykey.key_name}"
user_data = <<EOF
<powershell>
net user ${var.username} '${var.password}' /add /y
net localgroup administrators ${var.username} /add
winrm quickconfig -q
winrm set winrm/config/winrs '@{MaxMemoryPerShellMB="300"}'
winrm set winrm/config '@{MaxTimeoutms="1800000"}'
winrm set winrm/config/service '@{AllowUnencrypted="true"}'
winrm set winrm/config/service/auth '@{Basic="true"}'
netsh advfirewall firewall add rule name="WinRM 5985" protocol=TCP dir=in localport=5985 action=allow
netsh advfirewall firewall add rule name="WinRM 5986" protocol=TCP dir=in localport=5986 action=allow
net stop winrm
sc.exe config winrm start=auto
net start winrm
</powershell>
EOF
provisioner "file" {
source = "test.txt"
destination = "C:/test.txt"
}
connection {
type = "winrm"
timeout = "10m"
user = "${var.username}"
password = "${var.password}"
}
tags {
Name="${format("${var.username}-%01d",count.index+1)}"
}
}
上記のコードを複数回実行し、var.username に別の値を指定するとインスタンスが再作成されますが、同じ tf ファイルを複数回使用して、異なるユーザー名で新しいマシンを作成することは可能ですか?
答え1
それに対応する異なるユーザー名とパスワードの配列を使用します。
ただし、secrets.tfvarsをscmに入れないでください。
ユーザー名とパスワードをバージョン管理に保存することはお勧めしませんが、ローカルの秘密変数ファイルを作成し、-var-file を使用してそれを読み込むことができます。
1 つのコマンドで複数の -var-file 引数を使用できます。一部はバージョン管理にチェックインし、その他はチェックインしません。例:
$ terraform apply \ -var-file="secret.tfvars" \
secrets.tfvars 内
instance_count = 3
usernames = ["jeff","jason","jake"]
passwords = ["jeff_password","jason_password","jake_password"]
次にリソースで
resource "aws_instance" "win-example" {
ami = "${lookup(var.WIN_AMIS, var.AWS_REGION)}"
instance_type = "t2.medium"
count="${var.count}"
vpc_security_group_ids = ["${var.security_group_id}"]
key_name = "${aws_key_pair.mykey.key_name}"
user_data = <<EOF
<powershell>
net user ${var.usernames[count.index]} '${var.passwords[count.index]}' /add /y
net localgroup administrators ${var.usernames[count.index]} /add
winrm quickconfig -q
winrm set winrm/config/winrs '@{MaxMemoryPerShellMB="300"}'
winrm set winrm/config '@{MaxTimeoutms="1800000"}'
winrm set winrm/config/service '@{AllowUnencrypted="true"}'
winrm set winrm/config/service/auth '@{Basic="true"}'
netsh advfirewall firewall add rule name="WinRM 5985" protocol=TCP dir=in localport=5985 action=allow
netsh advfirewall firewall add rule name="WinRM 5986" protocol=TCP dir=in localport=5986 action=allow
net stop winrm
sc.exe config winrm start=auto
net start winrm
</powershell>
EOF
provisioner "file" {
source = "test.txt"
destination = "C:/test.txt"
}
connection {
type = "winrm"
timeout = "10m"
user = "${var.usernames[count.index]}"
password = "${var.passwords[count.index]}"
}
tags {
Name="${format("${var.username}-%01d",count.index+1)}"
}
}
答え2
各ユーザーのサブフォルダー (./terraform/user1、./terraform/user2....) を作成し、すべての tf ファイルをこれらのフォルダーにコピーし、すべてのユーザーに新しいセキュリティ グループを作成する必要があり、そのマシンのみが再作成を停止し、すべてのユーザーに対して、以前のマシンを破棄せずに新しいマシンが作成されました。
#!/bin/python
import json
import os.path
import shutil
from os import mkdir
from pprint import pprint
from python_terraform import *
json_data=open('./my.json')
data = json.load(json_data)
json_data.close()
def myfunc():
tf = Terraform(working_dir=final_path, variables={'count':count,'INSTANCE_USERNAME':user})
tf.plan(no_color=IsFlagged, refresh=True, capture_output=False)
approve = {"auto-approve": True}
print(tf.init(reconfigure=True))
print(tf.plan())
print(tf.apply(**approve))
return
for i in range (0, len (data['customers'])):
#print data['customers'][i]['email']
k=data['customers'][i]['email']
#print(k.split('@')[0])
user=k.split('@')[0]
#print(user)
count=data['customers'][i]['instances']
#print(count)
#enter = int(input('Enter number of instances: '))
start_path="/home/ja/terraform-course/demo-2b/"
final_path=os.path.join(start_path,user)
if not os.path.exists(final_path):
os.makedirs(final_path)
shutil.copy2('./vars.tf', final_path)
shutil.copy2('./sg.tf', final_path)
shutil.copy2('./windows.tf', final_path)
shutil.copy2('./provider.tf', final_path)
shutil.copy2('./test.txt', final_path)
final=os.path.join(final_path,'sg.tf')
final1=os.path.join(final_path,'windows.tf')
with open(final, 'r') as file :
filedata = file.read()
filedata = filedata.replace('allow-all', user)
with open(final, 'w') as file:
file.write(filedata)
with open(final1, 'r') as file :
filedata = file.read()
filedata = filedata.replace('allow-all', user)
with open(final1, 'w') as file:
file.write(filedata)
myfunc()