Terraform条件创建AWS IAM实例配置文件问题求助
解决Terraform实例配置文件复用问题
直接用Terraform的ignore_errors和条件资源创建逻辑实现需求,具体步骤如下:
- 读取已有实例配置文件(忽略不存在的情况)
给数据源添加ignore_errors = true,这样当实例配置文件不存在时,Terraform不会抛出错误,而是返回exists = false:
data "aws_iam_instance_profile" "existing_profile" { name = "ec2_instance_profile" ignore_errors = true }
- 条件创建新的实例配置文件
通过count参数控制资源是否创建:当已有配置文件存在时,count = 0(不创建新资源);不存在时count = 1(创建新资源):
resource "aws_iam_instance_profile" "new_profile" { count = data.aws_iam_instance_profile.existing_profile.exists ? 0 : 1 name = "ec2_instance_profile" role = data.aws_iam_role.role.name }
- 统一引用实例配置文件属性
用本地值封装逻辑,不管是已有还是新建的配置文件,都能正确获取arn和id:
locals { instance_profile_arn = data.aws_iam_instance_profile.existing_profile.exists ? data.aws_iam_instance_profile.existing_profile.arn : aws_iam_instance_profile.new_profile[0].arn instance_profile_id = data.aws_iam_instance_profile.existing_profile.exists ? data.aws_iam_instance_profile.existing_profile.id : aws_iam_instance_profile.new_profile[0].id }
后续需要使用实例配置文件的地方,直接引用local.instance_profile_arn或local.instance_profile_id即可,既避免重复创建报错,又保证了配置复用性。
内容的提问来源于stack exchange,提问作者Anirban Das
相关产品推荐
相关产品推荐

