Control what image you bake to I want to make a script that automatically bakes out several passes to several different images. In the standard baking setup, it bakes to the image you have in a texture node in your material. This gets strange when you have multiple image nodes. In my material I have a Diffuse, Gloss, AO, Normals, etc each as separate images. I want to bake each pass to the appropriate texture.

Is there a way to do this?
If we bake passes manually, they are baked to the selected texture node in the active objects material node tree.

We can create a texture image node, make it active, then assign it an image and bake a desired pass.

import bpy

BAKE_TYPES = ['DIFFUSE', 'GLOSSY', 'AO', 'NORMAL']

nodes = bpy.data.materials[0].node_tree.nodes
tex_node = nodes.new(type='ShaderNodeTexImage')
nodes.active = tex_node

for type in BAKE_TYPES:
    img = bpy.data.images.new('bake_' + type, 500, 500)

    # if you have images prepared, load them instead
    #img_diff = bpy.data.images['image_diff']

    nodes.active.image = img
    bpy.ops.object.bake(type=type)

nodes.remove(tex_node)