amazon-ec2 - attaching different Security Groups to different EC2s
问题描述
Requirement:-
I have multiple group(say 2 groups) of EC2s where each group contain 6 EC2. and I have to attach different SG to each group.
Example:-
Group1 contains :- Head1, child :EC2-1, EC2-2....6 and need to attach SG1
Group2 contains :- Head2, child :EC2-3, EC2-4 ...6 and need to attach SG2
I don't want to write separate resource "aws_instance" Head-Module
resource "aws_security_group" "sg" {
count = var.ec2_instance_count
name = "${local.account}${count.index}"
vpc_id = local.vpc_id
}
resource "aws_instance" "ec2_instance" {
count = var.ec2_instance_count
security_groups = [element(aws_security_group.sg.*.id, count.index)]
}
Child-Module:
data "aws_security_groups" "data_security_group" {
filter {
name = "group-name"
values = ["${local.account}${count.index}"]
}
}
resource "aws_instance" "ec2_child" {
count = var.ec2_instance_count*var.numberofchild
security_groups = [element(aws_security_group.data_security_group.*.id, count.index)]
}
Error: Error launching source instance: InvalidGroup.NotFound: The security group 'terraform-2020082 4151444795600000001' does not exist in VPC 'vpc-ghhje85abcy' status code: 400, request id: 9260fd88-a03a-4c46-b67c-3287594cdab5
on main.tf line 68, in resource "aws_instance" "ec2_instance": 68: resource "aws_instance" "ec2_instance" {
Note: I am using data "aws_security_groups"
instead of data "aws_security_group"
. If I use the later one, I know I will be able to get only one SG in the data resource and it throws me an error :multiple Security Groups matched; from which I kind of moved ahead by using data "aws_security_groups"
and this error get vanished. but the latest error I m facing is: InvalidGroup.NotFound as mentioned above.
Update: I am able to use data resource and able to attach the different SG to different EC2. the only issue is random Sequencing. for all 6 EC2 of group 1 I want them to assign first SG and so on.
解决方案
不要使用数据,而是使用计数来创建您resource "aws_security_group"
的计数resource "aws_instance"
,就像您可以直接引用它们一样...
resource "aws_security_group" "sg" {
count = var.ec2_instance_count
name = "${local.account}${count.index}"
vpc_id = local.vpc_id
}
resource "aws_instance" "ec2_instance" {
count = var.ec2_instance_count
security_groups = [element(aws_security_group.sg.*.id, count.index)]
}
推荐阅读
- c - Apple Accelerate BNNS 卷积参数
- machine-learning - 将自定义元数据(边界框)嵌入 HLS 视频流
- python - ModuleNotFoundError - Airflow 找不到打包的模块
- vue-component - Vue 3:附加到子组件道具
- office365 - S3 公共 URL 无法通过开放式办公室或谷歌查看器在网站中查看
- scala - Scala Map 接受可变对象作为键时可以吗?
- ruby - Shopify 脚本 API - 检查变体值
- typescript - 为什么 undefined 可以分配给 void?
- android - 为什么要安装 gradle 依赖项?
- python - 卡在配置中的 mypy_path 没有被拾取