![Terraform-여러 배포에 동일한 tf 파일을 사용하시겠습니까?](https://rvso.com/image/717741/Terraform-%EC%97%AC%EB%9F%AC%20%EB%B0%B0%ED%8F%AC%EC%97%90%20%EB%8F%99%EC%9D%BC%ED%95%9C%20tf%20%ED%8C%8C%EC%9D%BC%EC%9D%84%20%EC%82%AC%EC%9A%A9%ED%95%98%EC%8B%9C%EA%B2%A0%EC%8A%B5%EB%8B%88%EA%B9%8C%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을 사용하여 로드할 수 있습니다.
단일 명령에서 여러 -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()