|
| 1 | +/* |
| 2 | +Use this data source to query Organizations. |
| 3 | +
|
| 4 | +Example Usage |
| 5 | +
|
| 6 | +```hcl |
| 7 | +data "awx_organizations" "all_orgs" {} |
| 8 | +``` |
| 9 | +
|
| 10 | +*/ |
| 11 | +package awx |
| 12 | + |
| 13 | +import ( |
| 14 | + "context" |
| 15 | + "strconv" |
| 16 | + "time" |
| 17 | + |
| 18 | + awx "github.com/denouche/goawx/client" |
| 19 | + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" |
| 20 | + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" |
| 21 | +) |
| 22 | + |
| 23 | +func dataSourceOrganizations() *schema.Resource { |
| 24 | + return &schema.Resource{ |
| 25 | + ReadContext: dataSourceOrganizationsRead, |
| 26 | + Schema: map[string]*schema.Schema{ |
| 27 | + "organizations": { |
| 28 | + Type: schema.TypeList, |
| 29 | + Computed: true, |
| 30 | + Elem: &schema.Resource{ |
| 31 | + Schema: map[string]*schema.Schema{ |
| 32 | + "id": { |
| 33 | + Type: schema.TypeInt, |
| 34 | + Computed: true, |
| 35 | + }, |
| 36 | + "name": { |
| 37 | + Type: schema.TypeString, |
| 38 | + Computed: true, |
| 39 | + }, |
| 40 | + }, |
| 41 | + }, |
| 42 | + }, |
| 43 | + }, |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +func dataSourceOrganizationsRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { |
| 48 | + var diags diag.Diagnostics |
| 49 | + client := m.(*awx.AWX) |
| 50 | + |
| 51 | + parsedOrgs := make([]map[string]interface{}, 0) |
| 52 | + |
| 53 | + orgs, err := client.OrganizationsService.ListOrganizations(map[string]string{}) |
| 54 | + if err != nil { |
| 55 | + diags = append(diags, diag.Diagnostic{ |
| 56 | + Severity: diag.Error, |
| 57 | + Summary: "Unable to fetch organizations", |
| 58 | + Detail: "Unable to fetch organizations from AWX API", |
| 59 | + }) |
| 60 | + return diags |
| 61 | + } |
| 62 | + for _, c := range orgs { |
| 63 | + parsedOrgs = append(parsedOrgs, map[string]interface{}{ |
| 64 | + "id": c.ID, |
| 65 | + "name": c.Name, |
| 66 | + }) |
| 67 | + } |
| 68 | + |
| 69 | + err = d.Set("organizations", parsedOrgs) |
| 70 | + if err != nil { |
| 71 | + return diag.FromErr(err) |
| 72 | + } |
| 73 | + |
| 74 | + d.SetId(strconv.FormatInt(time.Now().Unix(), 10)) |
| 75 | + |
| 76 | + return diags |
| 77 | +} |
0 commit comments