Skip to content

Commit 7b6565d

Browse files
authored
Merge pull request #11 from openfresh/feature/ec2_tag
add command own EC2 Name Tag
2 parents 2287c30 + e57ece9 commit 7b6565d

File tree

4 files changed

+74
-24
lines changed

4 files changed

+74
-24
lines changed

cmd/ec2/describe_tag.go

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package ec2
2+
3+
import (
4+
"fmt"
5+
6+
"github.com/aws/aws-sdk-go/aws"
7+
"github.com/aws/aws-sdk-go/service/ec2"
8+
"github.com/spf13/cobra"
9+
)
10+
11+
var (
12+
describeNameTagCmd = &cobra.Command{
13+
Use: "describe-name-tag",
14+
Short: "get EC2 tag value",
15+
RunE: func(cmd *cobra.Command, args []string) error {
16+
17+
params := &ec2.DescribeInstancesInput{
18+
InstanceIds: aws.StringSlice([]string{instanceID}),
19+
}
20+
21+
res, err := client.DescribeInstances(params)
22+
if err != nil {
23+
return err
24+
}
25+
26+
if len(res.Reservations) == 0 {
27+
return fmt.Errorf("describe-instances %s is failed.", instanceID)
28+
}
29+
30+
for _, i := range res.Reservations[0].Instances {
31+
var nameTag string
32+
for _, t := range i.Tags {
33+
if *t.Key == "Name" {
34+
nameTag = *t.Value
35+
break
36+
}
37+
}
38+
fmt.Println(nameTag)
39+
}
40+
41+
return nil
42+
},
43+
}
44+
)

cmd/ec2/init.go

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package ec2
2+
3+
import (
4+
"github.com/aws/aws-sdk-go/service/ec2"
5+
"github.com/openfresh/lightaws/remote"
6+
"github.com/spf13/cobra"
7+
)
8+
9+
var (
10+
EC2Cmd = &cobra.Command{
11+
Use: "ec2",
12+
Long: `EC2`,
13+
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
14+
client = ec2.New(remote.NewAWSSession(region))
15+
return nil
16+
},
17+
}
18+
client *ec2.EC2
19+
instanceID string
20+
region string
21+
tagName string
22+
)
23+
24+
func init() {
25+
EC2Cmd.AddCommand(describeNameTagCmd)
26+
EC2Cmd.PersistentFlags().StringVarP(&instanceID, "instance-id", "i", "", "")
27+
EC2Cmd.PersistentFlags().StringVarP(&region, "region", "r", "", "")
28+
}

cmd/metadata/describe_tag.go

Lines changed: 0 additions & 24 deletions
This file was deleted.

cmd/root.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import (
1818
"fmt"
1919
"os"
2020

21+
"github.com/openfresh/lightaws/cmd/ec2"
2122
"github.com/openfresh/lightaws/cmd/ecr"
2223
"github.com/openfresh/lightaws/cmd/metadata"
2324
"github.com/spf13/cobra"
@@ -53,6 +54,7 @@ func init() {
5354

5455
RootCmd.AddCommand(
5556
metadata.MetadataCmd,
57+
ec2.EC2Cmd,
5658
ecr.EcrCmd,
5759
)
5860
}

0 commit comments

Comments
 (0)