https://pulumi.com logo
#python
Title
# python
a

astonishing-branch-30086

08/17/2020, 12:45 PM
Is there a hook for the event that Pulumi creates a resource? I would like to print a message if and only if a resource of a particular type was created by Pulumi in the current
pulumi up
call.
s

stocky-spoon-28903

08/17/2020, 2:52 PM
I don't think there's a hook as such - the easiest way to achieve this is to use a dynamic resource which depends on the first. There's an example of making this happen for Provisioners here: https://github.com/pulumi/examples/blob/master/aws-py-ec2-provisioners/__main__.py
👍 1
g

gentle-diamond-70147

08/18/2020, 3:39 AM
You could do this with a CrossGuard
ResourceValidationPolicy
- e.g. https://github.com/pulumi/templates-policy/blob/master/aws-python/__main__.py#L10-L15 and run pulumi with
pulumi up --policy-pack path-to-policy-code/
.
a

astonishing-branch-30086

08/18/2020, 2:20 PM
Thanks @stocky-spoon-28903, seems to be exactly what I want. A bit more involved than I would have liked for this specific purpose, but I might as well learn about this now as I might need the concept later.
We're not planning to use CrossGuard for now, this is an interesting alternative though @gentle-diamond-70147. Thanks!
👍 1
g

gentle-diamond-70147

08/18/2020, 4:02 PM
James's suggestion is good if you explicitly know the resource being created as you have to "link" it into the dynamic resource that James mentioned. A policy will let you run code for any resource of that type that's defined, JFWIW.
👍 1
a

astonishing-branch-30086

08/19/2020, 11:16 AM
I came up with
Copy code
from typing import Optional, Any
from uuid import uuid4

import pulumi
from pulumi import dynamic


class OnCreateWarningProvider(dynamic.ResourceProvider):

    warning_printed = False

    def print_warning(self, message):
        if not self.warning_printed:
            pulumi.warn(message)
            OnCreateWarningProvider.warning_printed = True

    def create(self, inputs: Any):
        self.print_warning(inputs['message'])
        return dynamic.CreateResult(id_=uuid4().hex, outs={})


class OnCreateWarning(dynamic.Resource):
    def __init__(self, name: str, message: str, opts: Optional[pulumi.ResourceOptions] = None):

        super().__init__(
            OnCreateWarningProvider(),
            name,
            {'message': message},
            opts=opts
        )
that I would call with something like
Copy code
messaging.OnCreateWarning(
    name=f"on-create-warning-{resource_name}",
    message="Resource was created!",
    opts=pulumi.ResourceOptions(depends_on=[resource]),
)
How does this look, @stocky-spoon-28903, @gentle-diamond-70147? Any ideas on simplyfing or improving this further? Do I need to set the CreateResult id_, for example? Thanks!
2 Views