1. Packages
  2. Google Cloud (GCP) Classic
  3. API Docs
  4. kms
  5. getKMSSecret
Google Cloud Classic v7.29.0 published on Wednesday, Jun 26, 2024 by Pulumi

gcp.kms.getKMSSecret

Explore with Pulumi AI

gcp logo
Google Cloud Classic v7.29.0 published on Wednesday, Jun 26, 2024 by Pulumi

    This data source allows you to use data encrypted with Google Cloud KMS within your resource definitions.

    For more information see the official documentation.

    NOTE: Using this data provider will allow you to conceal secret data within your resource definitions, but it does not take care of protecting that data in the logging output, plan output, or state output. Please take care to secure your secret data outside of resource definitions.

    Example Usage

    First, create a KMS KeyRing and CryptoKey using the resource definitions:

    import * as pulumi from "@pulumi/pulumi";
    import * as gcp from "@pulumi/gcp";
    
    const myKeyRing = new gcp.kms.KeyRing("my_key_ring", {
        project: "my-project",
        name: "my-key-ring",
        location: "us-central1",
    });
    const myCryptoKey = new gcp.kms.CryptoKey("my_crypto_key", {
        name: "my-crypto-key",
        keyRing: myKeyRing.id,
    });
    
    import pulumi
    import pulumi_gcp as gcp
    
    my_key_ring = gcp.kms.KeyRing("my_key_ring",
        project="my-project",
        name="my-key-ring",
        location="us-central1")
    my_crypto_key = gcp.kms.CryptoKey("my_crypto_key",
        name="my-crypto-key",
        key_ring=my_key_ring.id)
    
    package main
    
    import (
    	"github.com/pulumi/pulumi-gcp/sdk/v7/go/gcp/kms"
    	"github.com/pulumi/pulumi/sdk/v3/go/pulumi"
    )
    
    func main() {
    	pulumi.Run(func(ctx *pulumi.Context) error {
    		myKeyRing, err := kms.NewKeyRing(ctx, "my_key_ring", &kms.KeyRingArgs{
    			Project:  pulumi.String("my-project"),
    			Name:     pulumi.String("my-key-ring"),
    			Location: pulumi.String("us-central1"),
    		})
    		if err != nil {
    			return err
    		}
    		_, err = kms.NewCryptoKey(ctx, "my_crypto_key", &kms.CryptoKeyArgs{
    			Name:    pulumi.String("my-crypto-key"),
    			KeyRing: myKeyRing.ID(),
    		})
    		if err != nil {
    			return err
    		}
    		return nil
    	})
    }
    
    using System.Collections.Generic;
    using System.Linq;
    using Pulumi;
    using Gcp = Pulumi.Gcp;
    
    return await Deployment.RunAsync(() => 
    {
        var myKeyRing = new Gcp.Kms.KeyRing("my_key_ring", new()
        {
            Project = "my-project",
            Name = "my-key-ring",
            Location = "us-central1",
        });
    
        var myCryptoKey = new Gcp.Kms.CryptoKey("my_crypto_key", new()
        {
            Name = "my-crypto-key",
            KeyRing = myKeyRing.Id,
        });
    
    });
    
    package generated_program;
    
    import com.pulumi.Context;
    import com.pulumi.Pulumi;
    import com.pulumi.core.Output;
    import com.pulumi.gcp.kms.KeyRing;
    import com.pulumi.gcp.kms.KeyRingArgs;
    import com.pulumi.gcp.kms.CryptoKey;
    import com.pulumi.gcp.kms.CryptoKeyArgs;
    import java.util.List;
    import java.util.ArrayList;
    import java.util.Map;
    import java.io.File;
    import java.nio.file.Files;
    import java.nio.file.Paths;
    
    public class App {
        public static void main(String[] args) {
            Pulumi.run(App::stack);
        }
    
        public static void stack(Context ctx) {
            var myKeyRing = new KeyRing("myKeyRing", KeyRingArgs.builder()
                .project("my-project")
                .name("my-key-ring")
                .location("us-central1")
                .build());
    
            var myCryptoKey = new CryptoKey("myCryptoKey", CryptoKeyArgs.builder()
                .name("my-crypto-key")
                .keyRing(myKeyRing.id())
                .build());
    
        }
    }
    
    resources:
      myKeyRing:
        type: gcp:kms:KeyRing
        name: my_key_ring
        properties:
          project: my-project
          name: my-key-ring
          location: us-central1
      myCryptoKey:
        type: gcp:kms:CryptoKey
        name: my_crypto_key
        properties:
          name: my-crypto-key
          keyRing: ${myKeyRing.id}
    

    Next, use the Cloud SDK to encrypt some sensitive information:

    $ echo -n my-secret-password | gcloud kms encrypt \
    > --project my-project \
    > --location us-central1 \
    > --keyring my-key-ring \
    > --key my-crypto-key \
    > --plaintext-file - \
    > --ciphertext-file - \
    > | base64
    CiQAqD+xX4SXOSziF4a8JYvq4spfAuWhhYSNul33H85HnVtNQW4SOgDu2UZ46dQCRFl5MF6ekabviN8xq+F+2035ZJ85B+xTYXqNf4mZs0RJitnWWuXlYQh6axnnJYu3kDU=
    

    Finally, reference the encrypted ciphertext in your resource definitions:

    import * as pulumi from "@pulumi/pulumi";
    import * as gcp from "@pulumi/gcp";
    import * as random from "@pulumi/random";
    
    const sqlUserPassword = gcp.kms.getKMSSecret({
        cryptoKey: myCryptoKey.id,
        ciphertext: "CiQAqD+xX4SXOSziF4a8JYvq4spfAuWhhYSNul33H85HnVtNQW4SOgDu2UZ46dQCRFl5MF6ekabviN8xq+F+2035ZJ85B+xTYXqNf4mZs0RJitnWWuXlYQh6axnnJYu3kDU=",
    });
    const dbNameSuffix = new random.RandomId("db_name_suffix", {byteLength: 4});
    const main = new gcp.sql.DatabaseInstance("main", {
        name: pulumi.interpolate`main-instance-${dbNameSuffix.hex}`,
        databaseVersion: "MYSQL_5_7",
        settings: {
            tier: "db-f1-micro",
        },
    });
    const users = new gcp.sql.User("users", {
        name: "me",
        instance: main.name,
        host: "me.com",
        password: sqlUserPassword.then(sqlUserPassword => sqlUserPassword.plaintext),
    });
    
    import pulumi
    import pulumi_gcp as gcp
    import pulumi_random as random
    
    sql_user_password = gcp.kms.get_kms_secret(crypto_key=my_crypto_key["id"],
        ciphertext="CiQAqD+xX4SXOSziF4a8JYvq4spfAuWhhYSNul33H85HnVtNQW4SOgDu2UZ46dQCRFl5MF6ekabviN8xq+F+2035ZJ85B+xTYXqNf4mZs0RJitnWWuXlYQh6axnnJYu3kDU=")
    db_name_suffix = random.RandomId("db_name_suffix", byte_length=4)
    main = gcp.sql.DatabaseInstance("main",
        name=db_name_suffix.hex.apply(lambda hex: f"main-instance-{hex}"),
        database_version="MYSQL_5_7",
        settings=gcp.sql.DatabaseInstanceSettingsArgs(
            tier="db-f1-micro",
        ))
    users = gcp.sql.User("users",
        name="me",
        instance=main.name,
        host="me.com",
        password=sql_user_password.plaintext)
    
    package main
    
    import (
    	"fmt"
    
    	"github.com/pulumi/pulumi-gcp/sdk/v7/go/gcp/kms"
    	"github.com/pulumi/pulumi-gcp/sdk/v7/go/gcp/sql"
    	"github.com/pulumi/pulumi-random/sdk/v4/go/random"
    	"github.com/pulumi/pulumi/sdk/v3/go/pulumi"
    )
    
    func main() {
    	pulumi.Run(func(ctx *pulumi.Context) error {
    		sqlUserPassword, err := kms.GetKMSSecret(ctx, &kms.GetKMSSecretArgs{
    			CryptoKey:  myCryptoKey.Id,
    			Ciphertext: "CiQAqD+xX4SXOSziF4a8JYvq4spfAuWhhYSNul33H85HnVtNQW4SOgDu2UZ46dQCRFl5MF6ekabviN8xq+F+2035ZJ85B+xTYXqNf4mZs0RJitnWWuXlYQh6axnnJYu3kDU=",
    		}, nil)
    		if err != nil {
    			return err
    		}
    		dbNameSuffix, err := random.NewRandomId(ctx, "db_name_suffix", &random.RandomIdArgs{
    			ByteLength: pulumi.Int(4),
    		})
    		if err != nil {
    			return err
    		}
    		main, err := sql.NewDatabaseInstance(ctx, "main", &sql.DatabaseInstanceArgs{
    			Name: dbNameSuffix.Hex.ApplyT(func(hex string) (string, error) {
    				return fmt.Sprintf("main-instance-%v", hex), nil
    			}).(pulumi.StringOutput),
    			DatabaseVersion: pulumi.String("MYSQL_5_7"),
    			Settings: &sql.DatabaseInstanceSettingsArgs{
    				Tier: pulumi.String("db-f1-micro"),
    			},
    		})
    		if err != nil {
    			return err
    		}
    		_, err = sql.NewUser(ctx, "users", &sql.UserArgs{
    			Name:     pulumi.String("me"),
    			Instance: main.Name,
    			Host:     pulumi.String("me.com"),
    			Password: pulumi.String(sqlUserPassword.Plaintext),
    		})
    		if err != nil {
    			return err
    		}
    		return nil
    	})
    }
    
    using System.Collections.Generic;
    using System.Linq;
    using Pulumi;
    using Gcp = Pulumi.Gcp;
    using Random = Pulumi.Random;
    
    return await Deployment.RunAsync(() => 
    {
        var sqlUserPassword = Gcp.Kms.GetKMSSecret.Invoke(new()
        {
            CryptoKey = myCryptoKey.Id,
            Ciphertext = "CiQAqD+xX4SXOSziF4a8JYvq4spfAuWhhYSNul33H85HnVtNQW4SOgDu2UZ46dQCRFl5MF6ekabviN8xq+F+2035ZJ85B+xTYXqNf4mZs0RJitnWWuXlYQh6axnnJYu3kDU=",
        });
    
        var dbNameSuffix = new Random.RandomId("db_name_suffix", new()
        {
            ByteLength = 4,
        });
    
        var main = new Gcp.Sql.DatabaseInstance("main", new()
        {
            Name = dbNameSuffix.Hex.Apply(hex => $"main-instance-{hex}"),
            DatabaseVersion = "MYSQL_5_7",
            Settings = new Gcp.Sql.Inputs.DatabaseInstanceSettingsArgs
            {
                Tier = "db-f1-micro",
            },
        });
    
        var users = new Gcp.Sql.User("users", new()
        {
            Name = "me",
            Instance = main.Name,
            Host = "me.com",
            Password = sqlUserPassword.Apply(getKMSSecretResult => getKMSSecretResult.Plaintext),
        });
    
    });
    
    package generated_program;
    
    import com.pulumi.Context;
    import com.pulumi.Pulumi;
    import com.pulumi.core.Output;
    import com.pulumi.gcp.kms.KmsFunctions;
    import com.pulumi.gcp.kms.inputs.GetKMSSecretArgs;
    import com.pulumi.random.RandomId;
    import com.pulumi.random.RandomIdArgs;
    import com.pulumi.gcp.sql.DatabaseInstance;
    import com.pulumi.gcp.sql.DatabaseInstanceArgs;
    import com.pulumi.gcp.sql.inputs.DatabaseInstanceSettingsArgs;
    import com.pulumi.gcp.sql.User;
    import com.pulumi.gcp.sql.UserArgs;
    import java.util.List;
    import java.util.ArrayList;
    import java.util.Map;
    import java.io.File;
    import java.nio.file.Files;
    import java.nio.file.Paths;
    
    public class App {
        public static void main(String[] args) {
            Pulumi.run(App::stack);
        }
    
        public static void stack(Context ctx) {
            final var sqlUserPassword = KmsFunctions.getKMSSecret(GetKMSSecretArgs.builder()
                .cryptoKey(myCryptoKey.id())
                .ciphertext("CiQAqD+xX4SXOSziF4a8JYvq4spfAuWhhYSNul33H85HnVtNQW4SOgDu2UZ46dQCRFl5MF6ekabviN8xq+F+2035ZJ85B+xTYXqNf4mZs0RJitnWWuXlYQh6axnnJYu3kDU=")
                .build());
    
            var dbNameSuffix = new RandomId("dbNameSuffix", RandomIdArgs.builder()
                .byteLength(4)
                .build());
    
            var main = new DatabaseInstance("main", DatabaseInstanceArgs.builder()
                .name(dbNameSuffix.hex().applyValue(hex -> String.format("main-instance-%s", hex)))
                .databaseVersion("MYSQL_5_7")
                .settings(DatabaseInstanceSettingsArgs.builder()
                    .tier("db-f1-micro")
                    .build())
                .build());
    
            var users = new User("users", UserArgs.builder()
                .name("me")
                .instance(main.name())
                .host("me.com")
                .password(sqlUserPassword.applyValue(getKMSSecretResult -> getKMSSecretResult.plaintext()))
                .build());
    
        }
    }
    
    resources:
      dbNameSuffix:
        type: random:RandomId
        name: db_name_suffix
        properties:
          byteLength: 4
      main:
        type: gcp:sql:DatabaseInstance
        properties:
          name: main-instance-${dbNameSuffix.hex}
          databaseVersion: MYSQL_5_7
          settings:
            tier: db-f1-micro
      users:
        type: gcp:sql:User
        properties:
          name: me
          instance: ${main.name}
          host: me.com
          password: ${sqlUserPassword.plaintext}
    variables:
      sqlUserPassword:
        fn::invoke:
          Function: gcp:kms:getKMSSecret
          Arguments:
            cryptoKey: ${myCryptoKey.id}
            ciphertext: CiQAqD+xX4SXOSziF4a8JYvq4spfAuWhhYSNul33H85HnVtNQW4SOgDu2UZ46dQCRFl5MF6ekabviN8xq+F+2035ZJ85B+xTYXqNf4mZs0RJitnWWuXlYQh6axnnJYu3kDU=
    

    This will result in a Cloud SQL user being created with password my-secret-password.

    Using getKMSSecret

    Two invocation forms are available. The direct form accepts plain arguments and either blocks until the result value is available, or returns a Promise-wrapped result. The output form accepts Input-wrapped arguments and returns an Output-wrapped result.

    function getKMSSecret(args: GetKMSSecretArgs, opts?: InvokeOptions): Promise<GetKMSSecretResult>
    function getKMSSecretOutput(args: GetKMSSecretOutputArgs, opts?: InvokeOptions): Output<GetKMSSecretResult>
    def get_kms_secret(additional_authenticated_data: Optional[str] = None,
                       ciphertext: Optional[str] = None,
                       crypto_key: Optional[str] = None,
                       opts: Optional[InvokeOptions] = None) -> GetKMSSecretResult
    def get_kms_secret_output(additional_authenticated_data: Optional[pulumi.Input[str]] = None,
                       ciphertext: Optional[pulumi.Input[str]] = None,
                       crypto_key: Optional[pulumi.Input[str]] = None,
                       opts: Optional[InvokeOptions] = None) -> Output[GetKMSSecretResult]
    func GetKMSSecret(ctx *Context, args *GetKMSSecretArgs, opts ...InvokeOption) (*GetKMSSecretResult, error)
    func GetKMSSecretOutput(ctx *Context, args *GetKMSSecretOutputArgs, opts ...InvokeOption) GetKMSSecretResultOutput

    > Note: This function is named GetKMSSecret in the Go SDK.

    public static class GetKMSSecret 
    {
        public static Task<GetKMSSecretResult> InvokeAsync(GetKMSSecretArgs args, InvokeOptions? opts = null)
        public static Output<GetKMSSecretResult> Invoke(GetKMSSecretInvokeArgs args, InvokeOptions? opts = null)
    }
    public static CompletableFuture<GetKMSSecretResult> getKMSSecret(GetKMSSecretArgs args, InvokeOptions options)
    // Output-based functions aren't available in Java yet
    
    fn::invoke:
      function: gcp:kms/getKMSSecret:getKMSSecret
      arguments:
        # arguments dictionary

    The following arguments are supported:

    Ciphertext string
    The ciphertext to be decrypted, encoded in base64
    CryptoKey string
    The id of the CryptoKey that will be used to decrypt the provided ciphertext. This is represented by the format {projectId}/{location}/{keyRingName}/{cryptoKeyName}.
    AdditionalAuthenticatedData string
    The additional authenticated data used for integrity checks during encryption and decryption.
    Ciphertext string
    The ciphertext to be decrypted, encoded in base64
    CryptoKey string
    The id of the CryptoKey that will be used to decrypt the provided ciphertext. This is represented by the format {projectId}/{location}/{keyRingName}/{cryptoKeyName}.
    AdditionalAuthenticatedData string
    The additional authenticated data used for integrity checks during encryption and decryption.
    ciphertext String
    The ciphertext to be decrypted, encoded in base64
    cryptoKey String
    The id of the CryptoKey that will be used to decrypt the provided ciphertext. This is represented by the format {projectId}/{location}/{keyRingName}/{cryptoKeyName}.
    additionalAuthenticatedData String
    The additional authenticated data used for integrity checks during encryption and decryption.
    ciphertext string
    The ciphertext to be decrypted, encoded in base64
    cryptoKey string
    The id of the CryptoKey that will be used to decrypt the provided ciphertext. This is represented by the format {projectId}/{location}/{keyRingName}/{cryptoKeyName}.
    additionalAuthenticatedData string
    The additional authenticated data used for integrity checks during encryption and decryption.
    ciphertext str
    The ciphertext to be decrypted, encoded in base64
    crypto_key str
    The id of the CryptoKey that will be used to decrypt the provided ciphertext. This is represented by the format {projectId}/{location}/{keyRingName}/{cryptoKeyName}.
    additional_authenticated_data str
    The additional authenticated data used for integrity checks during encryption and decryption.
    ciphertext String
    The ciphertext to be decrypted, encoded in base64
    cryptoKey String
    The id of the CryptoKey that will be used to decrypt the provided ciphertext. This is represented by the format {projectId}/{location}/{keyRingName}/{cryptoKeyName}.
    additionalAuthenticatedData String
    The additional authenticated data used for integrity checks during encryption and decryption.

    getKMSSecret Result

    The following output properties are available:

    Ciphertext string
    CryptoKey string
    Id string
    The provider-assigned unique ID for this managed resource.
    Plaintext string
    Contains the result of decrypting the provided ciphertext.
    AdditionalAuthenticatedData string
    Ciphertext string
    CryptoKey string
    Id string
    The provider-assigned unique ID for this managed resource.
    Plaintext string
    Contains the result of decrypting the provided ciphertext.
    AdditionalAuthenticatedData string
    ciphertext String
    cryptoKey String
    id String
    The provider-assigned unique ID for this managed resource.
    plaintext String
    Contains the result of decrypting the provided ciphertext.
    additionalAuthenticatedData String
    ciphertext string
    cryptoKey string
    id string
    The provider-assigned unique ID for this managed resource.
    plaintext string
    Contains the result of decrypting the provided ciphertext.
    additionalAuthenticatedData string
    ciphertext str
    crypto_key str
    id str
    The provider-assigned unique ID for this managed resource.
    plaintext str
    Contains the result of decrypting the provided ciphertext.
    additional_authenticated_data str
    ciphertext String
    cryptoKey String
    id String
    The provider-assigned unique ID for this managed resource.
    plaintext String
    Contains the result of decrypting the provided ciphertext.
    additionalAuthenticatedData String

    Package Details

    Repository
    Google Cloud (GCP) Classic pulumi/pulumi-gcp
    License
    Apache-2.0
    Notes
    This Pulumi package is based on the google-beta Terraform Provider.
    gcp logo
    Google Cloud Classic v7.29.0 published on Wednesday, Jun 26, 2024 by Pulumi