github.com/devseccon/trivy@v0.47.1-0.20231123133102-bd902a0bd996/pkg/fanal/artifact/vm/ami.go (about) 1 package vm 2 3 import ( 4 "context" 5 6 "github.com/aws/aws-sdk-go-v2/aws" 7 "github.com/aws/aws-sdk-go-v2/service/ec2" 8 "golang.org/x/xerrors" 9 10 "github.com/devseccon/trivy/pkg/cloud/aws/config" 11 "github.com/devseccon/trivy/pkg/fanal/types" 12 "github.com/devseccon/trivy/pkg/log" 13 ) 14 15 type AMI struct { 16 *EBS 17 18 imageID string 19 } 20 21 func newAMI(imageID string, storage Storage, region, endpoint string) (*AMI, error) { 22 // TODO: propagate context 23 ctx := context.TODO() 24 cfg, err := config.LoadDefaultAWSConfig(ctx, region, endpoint) 25 if err != nil { 26 return nil, err 27 } 28 client := ec2.NewFromConfig(cfg) 29 output, err := client.DescribeImages(ctx, &ec2.DescribeImagesInput{ 30 ImageIds: []string{imageID}, 31 }) 32 if err != nil { 33 return nil, xerrors.Errorf("ec2.DescribeImages: %w", err) 34 } else if len(output.Images) == 0 { 35 return nil, xerrors.Errorf("%s not found", imageID) 36 } 37 38 // Take the first snapshot 39 for _, mapping := range output.Images[0].BlockDeviceMappings { 40 snapshotID := aws.ToString(mapping.Ebs.SnapshotId) 41 if snapshotID == "" { 42 continue 43 } 44 log.Logger.Infof("Snapshot %s found", snapshotID) 45 ebs, err := newEBS(snapshotID, storage, region, endpoint) 46 if err != nil { 47 return nil, xerrors.Errorf("new EBS error: %w", err) 48 } 49 return &AMI{ 50 EBS: ebs, 51 imageID: imageID, 52 }, nil 53 } 54 55 return nil, xerrors.New("no snapshot found") 56 } 57 58 func (a *AMI) Inspect(ctx context.Context) (types.ArtifactReference, error) { 59 ref, err := a.EBS.Inspect(ctx) 60 if err != nil { 61 return types.ArtifactReference{}, err 62 } 63 ref.Name = a.imageID 64 return ref, nil 65 }