Calculate aws_volume_attachment ID using python

Viewed 129

I'm updating a Terraform state file using python(boto3) so it can reflect existing resources in AWS, and I came across the resource aws_volume_attachment which only exist in Terraform, the ID is calculated using the hash of the following attributes: instance ID, volume ID and the device name. https://github.com/hashicorp/terraform/blob/73dbded87ea739a2fbcfd83150ac09633df659c0/builtin/providers/aws/resource_aws_volume_attachment.go#L244-L251

I tried executing the following so I can have the same ID as in the state file which in my case should be vai-437263023 but I'm getting vai-3795101912 instead.

package main

import (
    "bytes"
    "fmt"
    "hash/crc32"
)

func String(s string) int {
    v := int(crc32.ChecksumIEEE([]byte(s)))
    if v >= 0 {
        return v
    }
    if -v >= 0 {
        return -v
    }

    return 0
}

func main() {
    // Expected: vai-437263023
   //  Received: vai-3795101912
   var buf bytes.Buffer
    buf.WriteString(fmt.Sprintf("%s-", "/dev/sdb"))
    buf.WriteString(fmt.Sprintf("%s-", "i-06754cada7514bb34"))
    buf.WriteString(fmt.Sprintf("%s-", "vol-028e997ae79e3a8ff"))

    fmt.Printf("vai-%d", String(buf.String()))
}

How can I get the same ID as in the state file? and how can I calculate the same ID but using python instead of GO?

1 Answers

I've checked a few provider versions and Terraform versions, and your code works well each time!

Python3:

>>> import binascii
>>> binascii.crc32(bytes('{}-{}-{}-'.format('/dev/sdb','i-06754cada7514bb34','vol-028e997ae79e3a8ff'), 'utf-8'))

3795101912

Also about that negative number check. It's func ChecksumIEEE(data []byte) uint32 so it can only be a negative int on a 32-bit platform. Still, such platform would calculate your hash as 499865384, so it's not that corner case.

Related