func ReplaceResourceBlock()

in types/hcl.go [42:84]


func ReplaceResourceBlock(workingDirectory, targetAddress string, newBlocks []*hclwrite.Block) error {
	for _, file := range helper.ListHclFiles(workingDirectory) {
		// #nosec G304
		src, err := os.ReadFile(filepath.Join(workingDirectory, file.Name()))
		if err != nil {
			return err
		}
		f, diag := hclwrite.ParseConfig(src, file.Name(), hcl.InitialPos)
		if f == nil || diag != nil && diag.HasErrors() || f.Body() == nil {
			continue
		}
		blocks := f.Body().Blocks()
		f.Body().Clear()
		found := false
		for _, block := range blocks {
			if block != nil && block.Type() == "resource" {
				address := strings.Join(block.Labels(), ".")
				if targetAddress == address {
					f.Body().AppendUnstructuredTokens(CommentOutBlock(block))
					f.Body().AppendNewline()
					for _, newBlock := range newBlocks {
						if newBlock == nil {
							continue
						}
						f.Body().AppendBlock(newBlock)
						f.Body().AppendNewline()
					}
					found = true
					continue
				}
			}
			f.Body().AppendBlock(block)
			f.Body().AppendNewline()
		}
		if found {
			if err := os.WriteFile(filepath.Join(workingDirectory, file.Name()), hclwrite.Format(f.Bytes()), 0600); err != nil {
				log.Printf("[Error] saving configuration %s: %+v", file.Name(), err)
			}
			return nil
		}
	}
	return nil
}