Skip to content

Commit 7d5a759

Browse files
Support using IMDSv2 to get availability zone (#253)
1 parent 4b79a02 commit 7d5a759

File tree

1 file changed

+21
-1
lines changed

1 file changed

+21
-1
lines changed

mage/deploy.go

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1538,6 +1538,26 @@ func (d Deploy) orch(targetEnv string) error {
15381538
return err
15391539
}
15401540

1541+
// getAWSAvailabilityZone retrieves the AWS availability zone using IMDSv2 with fallback to IMDSv1
1542+
func getAWSAvailabilityZone() (string, error) {
1543+
// Try IMDSv2 first - requires getting a token
1544+
tokenCmd := "curl -s -X PUT \"http://169.254.169.254/latest/api/token\" -H \"X-aws-ec2-metadata-token-ttl-seconds: 60\""
1545+
token, err := script.Exec(tokenCmd).String()
1546+
1547+
if err == nil && token != "" {
1548+
// Use the token to get the AZ with IMDSv2
1549+
azCmd := fmt.Sprintf("curl -s -H \"X-aws-ec2-metadata-token: %s\" http://169.254.169.254/latest/meta-data/placement/availability-zone", strings.TrimSpace(token))
1550+
az, err := script.Exec(azCmd).String()
1551+
if err == nil && az != "" {
1552+
return strings.TrimSpace(az), nil
1553+
}
1554+
}
1555+
1556+
// Fall back to IMDSv1 if IMDSv2 fails
1557+
az, err := script.Exec("curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone").String()
1558+
return strings.TrimSpace(az), err
1559+
}
1560+
15411561
func (d Deploy) orchLocal(targetEnv string) error {
15421562
targetConfig := getTargetConfig(targetEnv)
15431563

@@ -1578,7 +1598,7 @@ func (d Deploy) orchLocal(targetEnv string) error {
15781598
cmd = cmd + " " + fmt.Sprintf("--set-string argo.aws.account=%s", strings.Trim(awsAccountID, "\n"))
15791599

15801600
// Get AWS region of this VM
1581-
az, err := script.Exec("curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone").String()
1601+
az, err := getAWSAvailabilityZone()
15821602
if err != nil || az == "" {
15831603
return fmt.Errorf("error retrieving the AWS AZ: %w", err)
15841604
}

0 commit comments

Comments
 (0)