module.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package ansible
  15. import (
  16. "bytes"
  17. )
  18. // Module represents name and args of ansible module to execute
  19. type Module struct {
  20. // Name is ansible module name
  21. Name string
  22. // Args is a list of module arguments in form of key=value
  23. Args []string
  24. }
  25. // Host represents an ansible host
  26. type Host struct {
  27. // Name denotes the host to operate on
  28. Name string
  29. // Vars is a map recording host vars
  30. Vars map[string]string
  31. }
  32. // GetVar returns variable value. Second return value will be false if the
  33. // variable does not exist
  34. func (h *Host) GetVar(k string) (v string, exist bool) {
  35. if len(h.Vars) == 0 {
  36. return
  37. }
  38. v, exist = h.Vars[k]
  39. return
  40. }
  41. // SetVar sets variable k to value v
  42. func (h *Host) SetVar(k, v string) {
  43. if h.Vars == nil {
  44. h.Vars = map[string]string{
  45. k: v,
  46. }
  47. return
  48. }
  49. h.Vars[k] = v
  50. }
  51. // Inventory contains a list of ansible hosts
  52. type Inventory struct {
  53. Hosts []Host
  54. }
  55. // IsEmpty returns true if the inventory is empty
  56. func (i *Inventory) IsEmpty() bool {
  57. return len(i.Hosts) == 0
  58. }
  59. // Data returns serialized form of the inventory as represented on disk
  60. func (i *Inventory) Data() []byte {
  61. b := &bytes.Buffer{}
  62. for _, h := range i.Hosts {
  63. b.WriteString(h.Name)
  64. for k, v := range h.Vars {
  65. b.WriteRune(' ')
  66. b.WriteString(k)
  67. b.WriteRune('=')
  68. b.WriteString(v)
  69. }
  70. b.WriteRune('\n')
  71. }
  72. return b.Bytes()
  73. }