New variable. generate value from config args. and render to source.
(ctx context.Context, client ctrlclient.Client, playbook kkcorev1.Playbook, st source.SourceType)
| 55 | |
| 56 | // New variable. generate value from config args. and render to source. |
| 57 | func New(ctx context.Context, client ctrlclient.Client, playbook kkcorev1.Playbook, st source.SourceType) (Variable, error) { |
| 58 | var err error |
| 59 | // new source |
| 60 | var s source.Source |
| 61 | |
| 62 | switch st { |
| 63 | case source.MemorySource: |
| 64 | s = source.NewMemorySource() |
| 65 | case source.FileSource: |
| 66 | path := filepath.Join(_const.GetWorkdirFromConfig(playbook.Spec.Config), _const.RuntimeDir, kkcorev1.SchemeGroupVersion.String(), _const.RuntimePlaybookDir, playbook.Namespace, playbook.Name, _const.RuntimePlaybookVariableDir) |
| 67 | s, err = source.NewFileSource(path) |
| 68 | if err != nil { |
| 69 | return nil, err |
| 70 | } |
| 71 | default: |
| 72 | return nil, errors.Errorf("unsupported source type: %v", st) |
| 73 | } |
| 74 | |
| 75 | // get inventory |
| 76 | var inventory = &kkcorev1.Inventory{} |
| 77 | if playbook.Spec.InventoryRef != nil { |
| 78 | if err := client.Get(ctx, types.NamespacedName{Namespace: playbook.Spec.InventoryRef.Namespace, Name: playbook.Spec.InventoryRef.Name}, inventory); err != nil { |
| 79 | return nil, errors.Wrapf(err, "failed to get inventory %q from playbook %q", playbook.Spec.InventoryRef, ctrlclient.ObjectKeyFromObject(&playbook)) |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | v := &variable{ |
| 84 | key: string(playbook.UID), |
| 85 | source: s, |
| 86 | value: &value{ |
| 87 | Config: playbook.Spec.Config, |
| 88 | Inventory: *inventory, |
| 89 | Hosts: make(map[string]host), |
| 90 | }, |
| 91 | } |
| 92 | |
| 93 | if gd, ok := ConvertGroup(*inventory)["all"]; ok { |
| 94 | for _, hostname := range gd { |
| 95 | v.value.Hosts[hostname] = host{ |
| 96 | RemoteVars: make(map[string]any), |
| 97 | RuntimeVars: make(map[string]any), |
| 98 | } |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | // read data from source |
| 103 | data, err := v.source.Read() |
| 104 | if err != nil { |
| 105 | return nil, errors.Wrapf(err, "failed to read data from source. playbook: %q", ctrlclient.ObjectKeyFromObject(&playbook)) |
| 106 | } |
| 107 | |
| 108 | for k, d := range data { |
| 109 | // set hosts |
| 110 | h := host{} |
| 111 | if val, ok := d["remote"]; ok { |
| 112 | remoteVars, ok := val.(map[string]any) |
| 113 | if !ok { |
| 114 | return nil, errors.New("type assertion failed. expected map[string]any for remote vars") |