10 "github.com/hashicorp/terraform/config"
13 // ResourceAddress is a way of identifying an individual resource (or,
14 // eventually, a subset of resources) within the state. It is used for Targets.
15 type ResourceAddress struct {
16 // Addresses a resource falling somewhere in the module path
17 // When specified alone, addresses all resources within a module path
20 // Addresses a specific resource that occurs in a list
23 InstanceType InstanceType
27 Mode config.ResourceMode // significant only if InstanceTypeSet
30 // Copy returns a copy of this ResourceAddress
31 func (r *ResourceAddress) Copy() *ResourceAddress {
36 n := &ResourceAddress{
37 Path: make([]string, 0, len(r.Path)),
39 InstanceType: r.InstanceType,
44 for _, p := range r.Path {
45 n.Path = append(n.Path, p)
50 // String outputs the address that parses into this address.
51 func (r *ResourceAddress) String() string {
53 for _, p := range r.Path {
54 result = append(result, "module", p)
58 case config.ManagedResourceMode:
60 case config.DataResourceMode:
61 result = append(result, "data")
63 panic(fmt.Errorf("unsupported resource mode %s", r.Mode))
67 result = append(result, r.Type)
72 if r.InstanceTypeSet {
73 switch r.InstanceType {
84 name += fmt.Sprintf("[%d]", r.Index)
86 result = append(result, name)
89 return strings.Join(result, ".")
92 // stateId returns the ID that this resource should be entered with
93 // in the state. This is also used for diffs. In the future, we'd like to
94 // move away from this string field so I don't export this.
95 func (r *ResourceAddress) stateId() string {
96 result := fmt.Sprintf("%s.%s", r.Type, r.Name)
98 case config.ManagedResourceMode:
100 case config.DataResourceMode:
101 result = fmt.Sprintf("data.%s", result)
103 panic(fmt.Errorf("unknown resource mode: %s", r.Mode))
106 result += fmt.Sprintf(".%d", r.Index)
112 // parseResourceAddressConfig creates a resource address from a config.Resource
113 func parseResourceAddressConfig(r *config.Resource) (*ResourceAddress, error) {
114 return &ResourceAddress{
118 InstanceType: TypePrimary,
123 // parseResourceAddressInternal parses the somewhat bespoke resource
124 // identifier used in states and diffs, such as "instance.name.0".
125 func parseResourceAddressInternal(s string) (*ResourceAddress, error) {
126 // Split based on ".". Every resource address should have at least two
127 // elements (type and name).
128 parts := strings.Split(s, ".")
129 if len(parts) < 2 || len(parts) > 4 {
130 return nil, fmt.Errorf("Invalid internal resource address format: %s", s)
133 // Data resource if we have at least 3 parts and the first one is data
134 mode := config.ManagedResourceMode
135 if len(parts) > 2 && parts[0] == "data" {
136 mode = config.DataResourceMode
140 // If we're not a data resource and we have more than 3, then it is an error
141 if len(parts) > 3 && mode != config.DataResourceMode {
142 return nil, fmt.Errorf("Invalid internal resource address format: %s", s)
145 // Build the parts of the resource address that are guaranteed to exist
146 addr := &ResourceAddress{
150 InstanceType: TypePrimary,
154 // If we have more parts, then we have an index. Parse that.
156 idx, err := strconv.ParseInt(parts[2], 0, 0)
158 return nil, fmt.Errorf("Error parsing resource address %q: %s", s, err)
161 addr.Index = int(idx)
167 func ParseResourceAddress(s string) (*ResourceAddress, error) {
168 matches, err := tokenizeResourceAddress(s)
172 mode := config.ManagedResourceMode
173 if matches["data_prefix"] != "" {
174 mode = config.DataResourceMode
176 resourceIndex, err := ParseResourceIndex(matches["index"])
180 instanceType, err := ParseInstanceType(matches["instance_type"])
184 path := ParseResourcePath(matches["path"])
186 // not allowed to say "data." without a type following
187 if mode == config.DataResourceMode && matches["type"] == "" {
188 return nil, fmt.Errorf("must target specific data instance")
191 return &ResourceAddress{
193 Index: resourceIndex,
194 InstanceType: instanceType,
195 InstanceTypeSet: matches["instance_type"] != "",
196 Name: matches["name"],
197 Type: matches["type"],
202 func (addr *ResourceAddress) Equals(raw interface{}) bool {
203 other, ok := raw.(*ResourceAddress)
208 pathMatch := len(addr.Path) == 0 && len(other.Path) == 0 ||
209 reflect.DeepEqual(addr.Path, other.Path)
211 indexMatch := addr.Index == -1 ||
213 addr.Index == other.Index
215 nameMatch := addr.Name == "" ||
217 addr.Name == other.Name
219 typeMatch := addr.Type == "" ||
221 addr.Type == other.Type
223 // mode is significant only when type is set
224 modeMatch := addr.Type == "" ||
226 addr.Mode == other.Mode
230 addr.InstanceType == other.InstanceType &&
236 func ParseResourceIndex(s string) (int, error) {
240 return strconv.Atoi(s)
243 func ParseResourcePath(s string) []string {
247 parts := strings.Split(s, ".")
248 path := make([]string, 0, len(parts))
249 for _, s := range parts {
250 // Due to the limitations of the regexp match below, the path match has
251 // some noise in it we have to filter out :|
252 if s == "" || s == "module" {
255 path = append(path, s)
260 func ParseInstanceType(s string) (InstanceType, error) {
263 return TypePrimary, nil
265 return TypeDeposed, nil
267 return TypeTainted, nil
269 return TypeInvalid, fmt.Errorf("Unexpected value for InstanceType field: %q", s)
273 func tokenizeResourceAddress(s string) (map[string]string, error) {
274 // Example of portions of the regexp below using the
275 // string "aws_instance.web.tainted[1]"
276 re := regexp.MustCompile(`\A` +
277 // "module.foo.module.bar" (optional)
278 `(?P<path>(?:module\.[^.]+\.?)*)` +
279 // possibly "data.", if targeting is a data resource
280 `(?P<data_prefix>(?:data\.)?)` +
281 // "aws_instance.web" (optional when module path specified)
282 `(?:(?P<type>[^.]+)\.(?P<name>[^.[]+))?` +
283 // "tainted" (optional, omission implies: "primary")
284 `(?:\.(?P<instance_type>\w+))?` +
285 // "1" (optional, omission implies: "0")
286 `(?:\[(?P<index>\d+)\])?` +
289 groupNames := re.SubexpNames()
290 rawMatches := re.FindAllStringSubmatch(s, -1)
291 if len(rawMatches) != 1 {
292 return nil, fmt.Errorf("Problem parsing address: %q", s)
295 matches := make(map[string]string)
296 for i, m := range rawMatches[0] {
297 matches[groupNames[i]] = m