Posthook grant schema usage #11257
-
Hi, I'm new to dbt, and just saw that DBT is not applying grants to the schema the models resides in. I now had the idea to put a {{ config(
materialized='view',
grants = {
'+select': ['ROLE_A', 'ROLE_B'] }
post_hook = '{% for role in something %}GRANT USAGE ON {{ target.schema }} TO {{ role }}{% endfor %}'
) }} Would this be possible? Is there a way to collect all roles for the current target? Since |
Beta Was this translation helpful? Give feedback.
Answered by
nstein-gpjoule
Feb 12, 2025
Replies: 1 comment
-
I accomplished this using a global post-hook and these 3 Macros: models:
...
+post-hook: "{{ generate_schema_grants(this) }}"
seeds:
...
+post-hook: "{{ generate_schema_grants(this) }}" Get the Model config: {% macro get_model_config(model_ref) %}
{% if execute %}
{%- set model_name = model_ref.identifier -%}
{% for node in graph.nodes.values() %}
{%- set curr_model_name = node.unique_id.split('.')[-1] -%}
{%- if model_name == curr_model_name -%}
{%- set model_config = node.config -%}
{{ return(model_config) }}
{%- endif -%}
{% endfor %}
{% endif %}
{% endmacro %} Extract the roles: {% macro get_model_grant_roles(model_ref) %}
{% if execute %}
{%- set model_config = get_model_config(model_ref) -%}
{%- set roles = [] -%}
{% for model_grant, model_roles in model_config.grants.items() %}
{%- set roles = roles.extend(model_roles) -%}
{% endfor %}
{{ return(roles | unique | list) }}
{% endif %}
{% endmacro %} Create the sql string: {% macro generate_schema_grants(model_ref) %}
{% if execute %}
{%- set roles = get_model_grant_roles(model_ref) -%}
{% if roles | length %}
{%- set sql_strings = [] -%}
{% for curr_role in roles %}
{{ sql_strings.append("GRANT USAGE ON SCHEMA " + model_ref.database + '.' + model_ref.schema + " TO " + curr_role + ';') }}
{{ log("Granting usage on Schema: " ~ model_ref.database + '.' + model_ref.schema ~ " to Role: " ~ curr_role, info = true) }}
{% endfor %}
{{ return(' '.join(sql_strings)) }}
{% endif %}
{% endif %}
{% endmacro %} |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
nstein-gpjoule
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I accomplished this using a global post-hook and these 3 Macros:
Get the Model config:
Extract the roles: