Cette page a été traduite par l'API Cloud Translation.
Switch to English

Exemples de connecteurs

Cette page fournit des exemples de workflows illustrant l'utilisation de connecteurs dans un workflow pour accéder aux ressources d'autres produits Google Cloud.

Authentification

Lorsque vous utilisez un connecteur pour accéder à des ressources dans un autre produit Google Cloud, votre workflow doit être associé à un compte de service doté de droits suffisants pour accéder à ces ressources. Pour en savoir plus sur l'attribution de rôles aux comptes de service, consultez la page Accorder, modifier et révoquer les accès à des ressources. Pour savoir comment modifier le compte de service associé à un workflow, consultez la page Mettre à jour un workflow. Pour plus d'informations sur l'authentification, consultez la section Effectuer des requêtes authentifiées à partir d'un workflow.

Chaque exemple de cette page fournit des indications sur un rôle approprié qui accorde suffisamment de privilèges pour effectuer les tâches exécutées par cet exemple.

Utiliser ces exemples

Pour utiliser ces exemples, remplacez les valeurs des variables de l'étape initVariables par vos propres valeurs si nécessaire. ${sys.get_env("GOOGLE_CLOUD_PROJECT_ID")} extrait l'ID de votre projet Google Cloud et n'a pas besoin d'être remplacé.

Exemples Compute Engine

Les exemples suivants illustrent l'utilisation d'un workflow pour se connecter à une instance Compute Engine.

Le compte de service associé au workflow doit disposer du rôle IAM d'administrateur d'instances Compute (v1).

Arrêter une instance

YAML

- initVariables:
    assign:
      - project: ${sys.get_env("GOOGLE_CLOUD_PROJECT_ID")}
      - instance: "myinstance1"
      - zone: "us-central1-a"
- stopVM:
    try:
      call: googleapis.compute.v1.instances.stop
      args:
        project: ${project}
        instance: ${instance}
        zone: ${zone}
      result: stopVMResult
    except:
      as: e
      steps:
        - handleComputeEngineError:
            switch:
              - condition: ${e.code == 404}
                raise: "Compute Engine instance not found"
              - condition: ${e.code == 403}
                raise: "Error authenticating to Compute Engine"
        - unhandledException:
            raise: ${e}
- last:
    return: ${stopVMResult}

JSON

[
  {
    "initVariables": {
      "assign": [
        {
          "project": "${sys.get_env(\"GOOGLE_CLOUD_PROJECT_ID\")}"
        },
        {
          "instance": "myinstance1"
        },
        {
          "zone": "us-central1-a"
        }
      ]
    }
  },
  {
    "stopVM": {
      "try": {
        "call": "googleapis.compute.v1.instances.stop",
        "args": {
          "project": "${project}",
          "instance": "${instance}",
          "zone": "${zone}"
        },
        "result": "stopVMResult"
      },
      "except": {
        "as": "e",
        "steps": [
          {
            "handleComputeEngineError": {
              "switch": [
                {
                  "condition": "${e.code == 404}",
                  "raise": "Compute Engine instance not found"
                },
                {
                  "condition": "${e.code == 403}",
                  "raise": "Error authenticating to Compute Engine"
                }
              ]
            }
          },
          {
            "unhandledException": {
              "raise": "${e}"
            }
          }
        ]
      }
    }
  },
  {
    "last": {
      "return": "${stopVMResult}"
    }
  }
]

Démarrer une instance

YAML

- initVariables:
    assign:
      - project: ${sys.get_env("GOOGLE_CLOUD_PROJECT_ID")}
      - instance: "myinstance1"
      - zone: "us-central1-a"
- startVM:
    try:
      call: googleapis.compute.v1.instances.start
      args:
        project: ${project}
        instance: ${instance}
        zone: ${zone}
      result: startVMResult
    except:
      as: e
      steps:
        - handleComputeEngineError:
            switch:
              - condition: ${e.code == 404}
                raise: "Compute Engine instance not found"
              - condition: ${e.code == 403}
                raise: "Error authenticating to Compute Engine"
        - unhandledException:
            raise: ${e}
- last:
    return: ${startVMResult}

JSON

[
  {
    "initVariables": {
      "assign": [
        {
          "project": "${sys.get_env(\"GOOGLE_CLOUD_PROJECT_ID\")}"
        },
        {
          "instance": "myinstance1"
        },
        {
          "zone": "us-central1-a"
        }
      ]
    }
  },
  {
    "startVM": {
      "try": {
        "call": "googleapis.compute.v1.instances.start",
        "args": {
          "project": "${project}",
          "instance": "${instance}",
          "zone": "${zone}"
        },
        "result": "startVMResult"
      },
      "except": {
        "as": "e",
        "steps": [
          {
            "handleComputeEngineError": {
              "switch": [
                {
                  "condition": "${e.code == 404}",
                  "raise": "Compute Engine instance not found"
                },
                {
                  "condition": "${e.code == 403}",
                  "raise": "Error authenticating to Compute Engine"
                }
              ]
            }
          },
          {
            "unhandledException": {
              "raise": "${e}"
            }
          }
        ]
      }
    }
  },
  {
    "last": {
      "return": "${startVMResult}"
    }
  }
]

Exemple Pub/Sub

L'exemple suivant illustre l'utilisation d'un workflow pour publier un message dans un sujet avec Pub/Sub.

Le compte de service associé au workflow doit disposer du rôle IAM d'éditeur Pub/Sub.

YAML

- initVariables:
    assign:
      - project: ${sys.get_env("GOOGLE_CLOUD_PROJECT_ID")}
      - topic: "mytopic1"
      - message: "Hello world!"
- publish:
    try:
      call: googleapis.pubsub.v1.projects.topics.publish
      args:
        topic: ${"projects/" + project + "/topics/" + topic}
        body:
          messages:
            - data: ${base64.encode(text.encode(message))}
      result: publishResult
    except:
      as: e
      steps:
        - handlePubSubError:
            switch:
              - condition: ${e.code == 404}
                raise: "PubSub Topic not found"
              - condition: ${e.code == 403}
                raise: "Error authenticating to PubSub"
        - unhandledException:
            raise: ${e}
- last:
    return: ${publishResult}

JSON

[
  {
    "initVariables": {
      "assign": [
        {
          "project": "${sys.get_env(\"GOOGLE_CLOUD_PROJECT_ID\")}"
        },
        {
          "topic": "mytopic1"
        },
        {
          "message": "Hello world!"
        }
      ]
    }
  },
  {
    "publish": {
      "try": {
        "call": "googleapis.pubsub.v1.projects.topics.publish",
        "args": {
          "topic": "${\"projects/\" + project + \"/topics/\" + topic}",
          "body": {
            "messages": [
              {
                "data": "${base64.encode(text.encode(message))}"
              }
            ]
          }
        },
        "result": "publishResult"
      },
      "except": {
        "as": "e",
        "steps": [
          {
            "handlePubSubError": {
              "switch": [
                {
                  "condition": "${e.code == 404}",
                  "raise": "PubSub Topic not found"
                },
                {
                  "condition": "${e.code == 403}",
                  "raise": "Error authenticating to PubSub"
                }
              ]
            }
          },
          {
            "unhandledException": {
              "raise": "${e}"
            }
          }
        ]
      }
    }
  },
  {
    "last": {
      "return": "${publishResult}"
    }
  }
]

Exemple de Secret Manager

L'exemple suivant illustre l'utilisation d'un workflow pour accéder à un secret dans Secret Manager.

Le compte de service associé au workflow doit disposer du rôle d'accesseur de secrets du gestionnaire de secrets.

YAML

- initVariables:
    assign:
      - project: ${sys.get_env("GOOGLE_CLOUD_PROJECT_NUMBER")}
      - secret: "mysecret"
      - version: 1
- getSecret:
    try:
      call: googleapis.secretmanager.v1.projects.secrets.versions.access
      args:
        name: ${"projects/" + project + "/secrets/" + secret + "/versions/" + string(version)}
      result: secretResult
    except:
      as: e
      steps:
        - handleSecretManagerError:
            switch:
              - condition: ${e.code == 404}
                raise: "Secret not found"
              - condition: ${e.code == 403}
                raise: "Error authenticating to Secret Manager"
        - unhandledException:
            raise: ${e}
- storeSecret:
    assign:
      - secretValue: ${text.decode(base64.decode(secretResult.payload.data))}

JSON

[
  {
    "initVariables": {
      "assign": [
        {
          "project": "${sys.get_env(\"GOOGLE_CLOUD_PROJECT_NUMBER\")}"
        },
        {
          "secret": "mysecret"
        },
        {
          "version": 1
        }
      ]
    }
  },
  {
    "getSecret": {
      "try": {
        "call": "googleapis.secretmanager.v1.projects.secrets.versions.access",
        "args": {
          "name": "${\"projects/\" + project + \"/secrets/\" + secret + \"/versions/\" + string(version)}"
        },
        "result": "secretResult"
      },
      "except": {
        "as": "e",
        "steps": [
          {
            "handleSecretManagerError": {
              "switch": [
                {
                  "condition": "${e.code == 404}",
                  "raise": "Secret not found"
                },
                {
                  "condition": "${e.code == 403}",
                  "raise": "Error authenticating to Secret Manager"
                }
              ]
            }
          },
          {
            "unhandledException": {
              "raise": "${e}"
            }
          }
        ]
      }
    }
  },
  {
    "storeSecret": {
      "assign": [
        {
          "secretValue": "${text.decode(base64.decode(secretResult.payload.data))}"
        }
      ]
    }
  }
]

Exemples Firestore

Les exemples suivants illustrent l'utilisation d'un workflow pour se connecter à une instance Firestore.

Le compte de service associé au workflow doit se voir attribuer le rôle d'utilisateur Cloud Datastore.

Lire un document à partir de Firestore

YAML

- initVariables:
    assign:
      - project: ${sys.get_env("GOOGLE_CLOUD_PROJECT_ID")}
      - collection: "peopleDatabase"
      - document: "smith.j"
- readFromFirestore:
    try:
      call: googleapis.firestore.v1.projects.databases.documents.get
      args:
        name: ${"projects/"+project+"/databases/(default)/documents/"+collection+"/"+document}
      result: readResult
    except:
      as: e
      steps:
        - handleFirestoreReadError:
            switch:
              - condition: ${e.code == 404}
                raise: "Firestore database or document not found"
              - condition: ${e.code == 403}
                raise: "Error authenticating to Firestore"
        - unhandledException:
            raise: ${e}
- last:
    return: ${readResult.fields}

JSON

[
  {
    "initVariables": {
      "assign": [
        {
          "project": "${sys.get_env(\"GOOGLE_CLOUD_PROJECT_ID\")}"
        },
        {
          "collection": "peopleDatabase"
        },
        {
          "document": "smith.j"
        }
      ]
    }
  },
  {
    "readFromFirestore": {
      "try": {
        "call": "googleapis.firestore.v1.projects.databases.documents.get",
        "args": {
          "name": "${\"projects/\"+project+\"/databases/(default)/documents/\"+collection+\"/\"+document}"
        },
        "result": "readResult"
      },
      "except": {
        "as": "e",
        "steps": [
          {
            "handleFirestoreReadError": {
              "switch": [
                {
                  "condition": "${e.code == 404}",
                  "raise": "Firestore database or document not found"
                },
                {
                  "condition": "${e.code == 403}",
                  "raise": "Error authenticating to Firestore"
                }
              ]
            }
          },
          {
            "unhandledException": {
              "raise": "${e}"
            }
          }
        ]
      }
    }
  },
  {
    "last": {
      "return": "${readResult.fields}"
    }
  }
]

Créer ou mettre à jour un document dans Firestore

YAML

- initVariables:
    assign:
      - project: ${sys.get_env("GOOGLE_CLOUD_PROJECT_ID")}
      - collection: "peopleDatabase"
      - document: "smith.j"
      - valuesToWrite:
          FirstName:
            stringValue: "John"
          LastName:
            stringValue: "Smith"
          Age:
            integerValue: 32
- writeToFirestore:
    try:
      call: googleapis.firestore.v1.projects.databases.documents.patch
      args:
        name: ${"projects/"+project+"/databases/(default)/documents/"+collection+"/"+document}
        body:
          fields: ${valuesToWrite}
      result: writeResult
    except:
      as: e
      steps:
        - handleFirestoreWriteError:
            switch:
              - condition: ${e.code == 404}
                raise: "Firestore database or document not found"
              - condition: ${e.code == 403}
                raise: "Error authenticating to Firestore"
        - unhandledException:
            raise: ${e}
- last:
    return: ${writeResult.name}

JSON

[
  {
    "initVariables": {
      "assign": [
        {
          "project": "${sys.get_env(\"GOOGLE_CLOUD_PROJECT_ID\")}"
        },
        {
          "collection": "peopleDatabase"
        },
        {
          "document": "smith.j"
        },
        {
          "valuesToWrite": {
            "FirstName": {
              "stringValue": "John"
            },
            "LastName": {
              "stringValue": "Smith"
            },
            "Age": {
              "integerValue": 32
            }
          }
        }
      ]
    }
  },
  {
    "writeToFirestore": {
      "try": {
        "call": "googleapis.firestore.v1.projects.databases.documents.patch",
        "args": {
          "name": "${\"projects/\"+project+\"/databases/(default)/documents/\"+collection+\"/\"+document}",
          "body": {
            "fields": "${valuesToWrite}"
          }
        },
        "result": "writeResult"
      },
      "except": {
        "as": "e",
        "steps": [
          {
            "handleFirestoreWriteError": {
              "switch": [
                {
                  "condition": "${e.code == 404}",
                  "raise": "Firestore database or document not found"
                },
                {
                  "condition": "${e.code == 403}",
                  "raise": "Error authenticating to Firestore"
                }
              ]
            }
          },
          {
            "unhandledException": {
              "raise": "${e}"
            }
          }
        ]
      }
    }
  },
  {
    "last": {
      "return": "${writeResult.name}"
    }
  }
]

Exemple de tâches

L'exemple suivant montre comment utiliser un workflow pour créer des tâches dans Tasks.

Le compte de service associé au workflow doit disposer du rôle Cloud Tasks Tasks.

YAML

- initVariables:
    assign:
      - project: ${sys.get_env("GOOGLE_CLOUD_PROJECT_ID")}
      - location: ${sys.get_env("GOOGLE_CLOUD_LOCATION")}
      - queue: "testqueue"
      - taskURL: "https://somewhere.com/apiendpoint"
      - method: "POST"
      - body: "Hello world!"
- startTask:
    try:
      call: googleapis.cloudtasks.v2.projects.locations.queues.tasks.create
      args:
        parent: ${"projects/" + project + "/locations/" + location + "/queues/" + queue}
        body:
          task:
            httpRequest:
              body: ${base64.encode(text.encode(body))}
              httpMethod: ${method}
              url: ${taskURL}
            scheduleTime:
              seconds: int(sys.now() + 60*60*24)
      result: taskResult
    except:
      as: e
      steps:
        - handleTasksError:
            switch:
              - condition: ${e.code == 404}
                raise: "Tasks queue not found"
              - condition: ${e.code == 403}
                raise: "Error authenticating to Cloud Tasks"
        - unhandledException:
            raise: ${e}

- last:
    return: ${taskResult.body}

JSON

[
  {
    "initVariables": {
      "assign": [
        {
          "project": "${sys.get_env(\"GOOGLE_CLOUD_PROJECT_ID\")}"
        },
        {
          "location": "${sys.get_env(\"GOOGLE_CLOUD_LOCATION\")}"
        },
        {
          "queue": "testqueue"
        },
        {
          "taskURL": "https://somewhere.com/apiendpoint"
        },
        {
          "method": "POST"
        },
        {
          "body": "Hello world!"
        }
      ]
    }
  },
  {
    "startTask": {
      "try": {
        "call": "googleapis.cloudtasks.v2.projects.locations.queues.tasks.create",
        "args": {
          "parent": "${\"projects/\" + project + \"/locations/\" + location + \"/queues/\" + queue}",
          "body": {
            "task": {
              "httpRequest": {
                "body": "${base64.encode(text.encode(body))}",
                "httpMethod": "${method}",
                "url": "${taskURL}"
              },
              "scheduleTime": {
                "seconds": "int(sys.now() + 60*60*24)"
              }
            }
          }
        },
        "result": "taskResult"
      },
      "except": {
        "as": "e",
        "steps": [
          {
            "handleTasksError": {
              "switch": [
                {
                  "condition": "${e.code == 404}",
                  "raise": "Tasks queue not found"
                },
                {
                  "condition": "${e.code == 403}",
                  "raise": "Error authenticating to Cloud Tasks"
                }
              ]
            }
          },
          {
            "unhandledException": {
              "raise": "${e}"
            }
          }
        ]
      }
    }
  },
  {
    "last": {
      "return": "${taskResult.body}"
    }
  }
]