How to query for all posts that have a particular meta key?

I think something like this should do the job:

$meta_query = array(
    array(
         'key'     => 'foo',
         'compare' => 'EXISTS',
    ),
);

$args = array(
    'meta_query' => $meta_query
);

$query = new WP_Query( $args );

if ( $query->have_posts() ) {
    while ( $query->have_posts() ) {
        $query->the_post();
        $post_id = get_the_ID();
    }
} else {
    // no posts found
}

wp_reset_postdata();