Use agent policies (GA)

You create and manage agent policies by using thegcloud compute instances ops-agents policies commandgroup in the Google Cloud CLI or theops-agent-policy Terraform module.Agent policies use theVM Manager suite of tools inCompute Engine to manageOS policies,which can automate the deployment and maintenance of software configurationslike theOps Agent. These policies can't be applied to the legacyMonitoring agent or the legacy Logging agent.

The GA agent policies useOS policy assignmentresources in the OS Config API. Although there is a general gcloud CLIcommand group for managing OS policy assignments,gcloud compute os-config os-policy-assignments, thegcloud compute instances ops-agents policies command group is designed specifically for the agentpolicies described in this document.

Note:This document describes theGA agent policies. Agent policies are also available in a beta release.For information about the differences between thetwo releases and about converting beta agent policies to GA agent policies,seeOverview of agentpolicies for the Ops Agent.

Before you begin

Theops-agent-policy Terraform module is built on top of thegcloud compute instances ops-agents policies commands from the Google Cloud SDK. For information about how Terraform works, seeUsing Terraform.

Before using the Google Cloud CLI or the Terraform module to create agentpolicies, complete the following steps:

  1. If you are going to use thegcloud compute instances ops-agents policies commands and ifyou haven't done so already, then install theGoogle Cloud CLI.

  2. If you are going to use the Terraform module, then do the following:

    1. For information about installing Terraform, seeInstall and configureTerraform.Cloud Shell has Terraform already installed.

    2. Clone theterraform-google-cloud-operations repository, whichcontains theops-agent-policy module:

      git clone https://github.com/terraform-google-modules/terraform-google-cloud-operations
  3. Download and run theprepare-for-ops-agents-policies.sh script toenable the required APIs and to set the proper permissions for using theGoogle Cloud CLI or Terraform.

    For information about the script, seeTheprepare-for-ops-agents-policies.shscript.

    Note: Theprepare-for-ops-agents-policies.sh script is designed to run on Linux. If you'reusing a machine on a different operating system, then run the script fromCloud Shell.

Uninstall the legacy Monitoring agent and Logging agent

If you're creating a policy for the Ops Agent, ensure that your VMsdon't have the legacy Logging agent or Monitoring agent installed on them. Running theOps Agent and the legacy agents on the same VM can cause ingestion ofduplicate logs or a conflict in metrics ingestion. If necessary,uninstall the Monitoring agentanduninstall theLogging agent before creating a policy to install the Ops Agent.

Verify that the OS Config agent is installed

You might need to manually install and configure the OS Config agent onVMs that predate OS Config. For information about manually installingand verifying the OS Config agent, see theVM Manager verification checklist.

Find values for operating-system information

If you want to apply agent policies to specific operating systemsor versions, you need to know the values that OS Config uses to referto them.

To find values for theosShortName andosVersion fields for a VM, usethe following commands:

gcloud compute instances os-inventory describeINSTANCE_NAME \--zoneZONE | grep "^ShortName: "
gcloud compute instances os-inventory describeINSTANCE_NAME \--zoneZONE | grep "^Version: "

These commands require the OS Config agent to be installed on the VM.

Create an agent policy to manage the Ops Agent

Command-line

To create an agent policy, use thegcloud compute instances ops-agents policiescreate command.This command has the following structure:

gcloud compute instances ops-agents policiescreatePOLICY_ID \  --zoneZONE \  --filepath/to/policy-description-file.yaml \  --projectPROJECT_ID

When using this command, replace the variables as follows:

  • POLICY_ID is a name for your policy.
  • ZONE is a Compute Engine zone. Agent policies are applied only to VMs inthe specified zone; to apply a policy in multiple zones, you must createmultiple policies.
  • path/to/policy-description-file.yaml is the path to a YAML file that describes the policy.For information about the structure of this file, seeDescribe agent policies.
  • PROJECT_ID is the ID of your Google Cloud project.

For information about the other commands in the command group andthe available options, see thegcloud compute instances ops-agents policies documentation.

Describe agent policies

You provide policy information to thegcloud compute instances ops-agents policiescreate bycreating a YAML file that describes the policy and passing that file to thecommand as the value of the--fileoption.

This section describes the structure of the policy-description file.For additional information, seeExample policy-description files.

Format of the YAML policy-description file

The description file for an agent policy must include two field groups:

  • agentsRule, which tells the agent policy whether to install or removethe Ops Agent, and specifies the version of the Ops Agent to operate on.

  • instanceFilter, which describes the VMs on which the apply the policy.

Structure of theagentsRule field group

TheagentsRule field group has the following structure:

agentsRule:packageState:installed|removedversion:latest|2.*.*|2.x.y
  • ThepackageState field tells the policy the intended state of theOps Agent. The valid values areinstalled andremoved.
  • Theversion field indicates the version of the Ops Agent to install orremove. You can specify the following values:

    • latest is the most recent version of the Ops Agent.
    • 2.*.* is the most recent release of major version 2 of the Ops Agent.
    • 2.x.y indicates a specific release of major version 2.

    For information about the available versions of the Ops Agent, seethe agent'sGitHub repository.

Structure of theinstanceFilter field group

TheinstanceFilter field group indicates the VMs in a zone to which thefilter applies. This field group is a YAML representation of theInstanceFilterstructure used by theOSPolicyAssignment resource in the OS Config API.

TheinstanceFilter field group has one of the following structures:

  • To apply the agent policy to all VMs in a zone, use the following:

    instanceFilter:all:True

    If you use theall: True filter, then you can't specifyany other criteria.

  • To apply the agent policy to a specific set of VMs in a zone, describethe VMs by using a combination of any of the following:

    • Labels on the VM, either for inclusion or exclusion:
      • inclusionLabels:
      • exclusionLabels:
    • Operating system:inventories:

    For example, the following filter applies the agent policy to the VMswith the specified operating systems that have the label "env=prod"and don't have the label "app=web":

    instanceFilter:inclusionLabels:-labels:env:prodexclusionLabels:-labels:app:webinventories:-osShortName:rhelosVersion:'7.*'-osShortName:debianosVersion:'11'

    For information about finding the operating-system values, seeFind operating system information.

Terraform

To create a fully customized agent policy, use theops-agent-policy module in themodulesdirectory of theterraform-google-cloud-operations repository.This module requires the same information that thegcloud compute instances ops-agents policiescreate command requires. For a description of all the fields used to describe an agent policy,select theCommand-line tab.

Theexamples directory in theterraform-google-cloud-operations repository contains files thatprovide many of the variables needed by theops-agent-policy modulefor you. For more information, seeExample policy configurations.

To learn how to apply or remove a Terraformconfiguration, seeBasic Terraformcommands. For information about how Terraform works, seeUsing Terraform.

Verify the status of agent policies

This section describes how to check the status of created policiesand the installation of the Ops Agent. This information can also help withtroubleshooting your agent policies.

Compute EngineOS policies page

The Compute EngineOS policies page provides information aboutthe agent policies that manage the Ops Agent and about VMs on theVM instances tab. For example:

  • TheState column indicates whether a policy was successfully installed ("Compliant"), in progress ("Pending"), possibly failed ("Unknown"), or missing ("No policies").
  • TheVM monitored column indicates whether the Ops Agent is being managed by the OS Config ("Monitored") or not ("Not monitored").

    If a policy is "Compliant" but the VM shows "Not monitored", then there might be a problem installing the Ops Agent. You might, for example, have alegacy agent already installed.

In the Google Cloud console, go to theOS policies page:

Go toOS policies

If you use the search bar to find this page, then select the result whose subheading isCompute Engine.

TheVM instances on the Compute EngineOS policiestabshows information about agents managed by all OS policies in yourGoogle Cloud project. These policies are labeledgoog-ops-agent-policy.

  • Thegoog-ops-agent-policy indicator includes several types of policies:
    • Policies created by using thegcloud compute instances ops-agents policies commands.
    • Policies created for you if you requestedOps Agent installation when you created the VM.
    • Policies created by using Terraform to manage the Ops Agent.

    To distinguish between policies, use theOS policy assignments tab on the page to see the policy IDs for all the policy assignments in your Google Cloud project.

  • ThisVM monitored column doesn't reflect the installation of the Ops Agent by other means, like manual installation or bybeta agent policies.

Cloud MonitoringVM Instances page

TheVM Instances page in Cloud Monitoring includes anAgent column that lists the agent installed on each VM, and for theOps Agent, includes an indicator for installed agents that are older thanthe latest version.

In the Google Cloud console, go to theVM Instances page:

Go toVM Instances

If you use the search bar to find this page, then select the result whose subheading isMonitoring.

Example policy configurations

This section describes examples for setting up agent policies when usingeither the Google Cloud SDK or Terraform.

Command-line

Example policy-description files

This section provides some examples of YAML policy-description files fora variety of scenarios. The examples assume that you put theYAML in a file namedagent-policy-description.yaml and thatyou create the policy in theus-central1-a zone by using a commandlike the following:

gcloud compute instances ops-agents policiescreatePOLICY_ID \  --zone us-central1-a \  --file agent-policy-description.yaml \  --projectPROJECT_ID

Install on all VMs

To install the latest version of the Ops Agent on all VMs in theus-central1-a zone, use the following policy description:

agentsRule:packageState:installedversion:latestinstanceFilter:all:True

Remove from all VMs

To remove the latest version of the Ops Agent on all VMs in theus-central1-a zone, use the following policy description:

agentsRule:packageState:removedversion:latestinstanceFilter:all:True

Install on VMs based on labels

To install the latest version of the Ops Agent on all VMs in theus-central1-a zone with the label "env=prod" or "app=web",use the following policy description:

agentsRule:packageState:installedversion:latestinstanceFilter:inclusionLabels:-labels:env:prod-labels:app:web

When you specify multiplelabels: entries for inclusion or exclusion, a VMmatches if any of the labels is present; that is, the sets of labelsfor inclusion or exclusion are matched as a logicalOR operation,not a logicalAND operation.

Install on VMs based on other labels

To install the latest version of the Ops Agent on all VMs in theus-central1-a zone running Debian 11, except those with the labels "env=prod"and "app=web6", use the following policy description:

agentsRule:packageState:installedversion:latestinstanceFilter:exclusionLabels:-labels:env:prodapp:web6inventories:-osShortName:debianosVersion:'11'

When you specify multiple key-value pairs under a singlelabels: entryfor inclusion or exclusion, a VM matches if all of the labels are present;that is, the labels are matched as a logicalAND operation, not alogicalOR operation.

Install on VMs based on operating system

To install the latest version 2 of the Ops Agent on all VMs runningDebian 11 or RHEL 7.* in theus-central1-a zone, use the followingpolicy description:

agentsRule:packageState:installedversion:2.*.*instanceFilter:inventories:-osShortName:rhelosVersion:'7.*'-osShortName:debianosVersion:'11'

Terraform

This section describes the examples in theexamples directoryof theterraform-google-cloud-operations repository. These examplescontain files that configure many of the variables required by theops-agent-policy module for you. You can also copy and modify theexamples. For example, these examples all install the Ops Agent;you can modify them to delete the agent instead.

To learn how to apply or remove a Terraformconfiguration, seeBasic Terraformcommands.

Example:ops_agent_policy_install_all

This example installs the latest version of the Ops Agent on alleligible VMs in your Google Cloud project.

When you run theterraform plan orterraform apply command, you are prompted for the followingvalues:

  • PROJECT_ID: The ID of your Google Cloud project

Example:ops_agent_policy_install_all_in_region

This example installs the latest version of the Ops Agent on alleligible VMs in a given region, likeus-west1. A region containsmultiple zones, in this case,us-west-1a,us-west-1b, andus-west-1c.

When you run theterraform plan orterraform apply command, you are prompted for the followingvalues:

  • PROJECT_ID: The ID of your Google Cloud project
  • REGION: The region in which to install the agent on VMs

Example:ops_agent_policy_install_all_in_zone

This example installs the latest version of the Ops Agent on alleligible VMs in a given zone, likeus-central1-a.

When you run theterraform plan orterraform apply command, you are prompted for the followingvalues:

  • PROJECT_ID: The ID of your Google Cloud project
  • ZONE: The zone in which to install the agent on VMs

Troubleshoot GA agent policies

This section provides information to help you resolve problems withGA agent policies for the Ops Agent. The information described inVerify the status of agent policies might also behelpful.

Theops-agents policy commands fail

When agcloud compute instances ops-agents policies command fails, the response shows avalidation error. Correct the errors by fixing the command arguments andflags as suggested by the error message.

In addition to the validation errors, you might see errors that indicate thefollowing conditions:

The following sections describe these conditions in more detail.

Insufficient IAM permission

If agcloud compute instances ops-agents policies command fails with a permission error, thenmake sure you have run theprepare-for-ops-agents-policies.sh script as described inBefore you beginto set up the OS Config policy roles:

For more information about theprepare-for-ops-agents-policies.sh script, seeTheprepare-for-ops-agents-policies.sh script.

OS Config API isn't enabled

A sample error looks like the following:

API [osconfig.googleapis.com] not enabled on projectPROJECT_ID.Would you like to enable and retry (this will take a few minutes)?(y/N)?

You can entery to enable the API, or you can run theprepare-for-ops-agents-policies.shscript, described inBefore you begin,to grant all the necessary permissions. If you entery at theprompt in the error message, then you still need to run theprepare-for-ops-agents-policies.sh script to set the needed permissions.

To verify that the OS Config API is enabled for the project, run thefollowing commands:

gcloudserviceslist--projectPROJECT_ID|greposconfig.googleapis.com

The expected output follows:

osconfig.googleapis.com    Cloud OS Config API

The policy already exists

A sample error looks like the following:

ALREADY_EXISTS: Requested entity already exists

This error means this policy already exists with the same name, project ID andregion. You can use thegcloud compute instances ops-agents policiesdescribe command to confirm this.

The policy does not exist

A sample error looks like the following:

NOT_FOUND: Requested entity was not found

This error might meant that the policy was never created, the policy has beendeleted, or that the specified policy ID is incorrect. Make sure thePOLICY_ID used in agcloud compute instances ops-agents policiesdescribe,update ordelete command corresponds to an existing policy. To get a list of agentpolicies, use thegcloud compute instances ops-agents policieslist command.

The policy is created but seems to have no effect

OS Config agents are deployed to each Compute Engine instance to manage thepackages for the Logging and Monitoring agents.The policy may seem to have no effect if the underlying OS Config agent isn'tinstalled.

Linux

To verify that the OS Config agent is installed, run the following command:

gcloud compute sshinstance-id \    --projectproject-id \    -- sudo systemctl status google-osconfig-agent

A sample output is:

    google-osconfig-agent.service - Google OSConfig Agent    Loaded: loaded (/lib/systemd/system/google-osconfig-agent.service; enabled; vendor preset:    Active: active (running) since Wed 2020-01-15 00:14:22 UTC; 6min ago    Main PID: 369 (google_osconfig)     Tasks: 8 (limit: 4374)    Memory: 102.7M    CGroup: /system.slice/google-osconfig-agent.service            └─369 /usr/bin/google_osconfig_agent

Windows

To verify that the OS Config agent is installed, run the following steps:

  1. Connect to your instance using RDP or a similar tool and login to Windows.

  2. Open a PowerShell terminal, then run the following PowerShell command. Youdon't need administrator privileges.

    Get-Service google_osconfig_agent

A sample output is:

    Status   Name               DisplayName    ------   ----               -----------    Running  google_osconfig_a… Google OSConfig Agent

If the OS Config agent is not installed, then you might be using anoperating system that doesn't support VM Manager. TheCompute EngineOperating system details documentindicates which VM Manager features are supported for eachCompute Engine operating system.

If the operating system supports VM Manager, then youcaninstall the OS Config agent manually.

The OS Config agent is installed but does not install the Ops Agent

To verify if there are any errors when the OS Config agent applies policies, youcan check the OS Config agent's log. This can be done either by usingLogs Explorer or using SSH or RDP to check individual Compute Engineinstances.

To view OS Config agent logs inLogs Explorer,use the following filter:

resource.type="gce_instance"logId(OSConfigAgent)

To view OS Config agent logs, do the following:

CentOS, RHEL,
SLES, SUSE

Run the following command:

gcloudcomputesshINSTANCE_ID\--projectPROJECT_ID\--sudocat/var/log/messages\|grep"OSConfigAgent\|google-fluentd\|stackdriver-agent"

Debian, Ubuntu

Run the following command:

gcloudcomputesshINSTANCE_ID\--projectPROJECT_ID\--sudocat/var/log/syslog\|grep"OSConfigAgent\|google-fluentd\|stackdriver-agent"

Windows

  1. Connect to your instance using RDP or a similar tool and login to Windows.

  2. Open the Event Viewer app, then selectWindows Logs > Application, and searchfor logs withSource equal toOSConfigAgent.

If there is an error connecting to the OS Config service, make sure you run theprepare-for-ops-agents-policies.sh script as described inBefore you beginto set up the OS Config metadata.

To verify that the OS Config metadata is enabled, you can run the followingcommand:

gcloud compute project-info describe \    --projectPROJECT_ID \    | grep "enable-osconfig\|enable-guest-attributes" -A 1

The expected output follows:

- key: enable-guest-attributes  value: 'TRUE'- key: enable-osconfig  value: 'TRUE'

The Ops Agent is installed but not functioning properly

For more information about debugging Ops Agent problems, seeTroubleshoot the Ops Agent.

Enable debug-level logs for the OS Config agent

It can be useful to enable debug-level logging in the OS Config agent whenreporting an issue.

You can set theosconfig-log-level: debug metadata to enable debug-levellogging for the OS Config agent. The collected logs have more information tohelp with the investigation.

To enable debug-level logging for the entire project, run the following command:

gcloud compute project-info add-metadata \    --projectPROJECT_ID \    --metadata osconfig-log-level=debug

To enable debug-level logging for one VM, run the following command:

gcloud compute instances add-metadataINSTANCE_ID \    --projectPROJECT_ID \    --metadata osconfig-log-level=debug

Helper scripts

This section provides additional information about the helper scriptsdescribed in this document:

Theprepare-for-ops-agents-policies.sh script

After you download theprepare-for-ops-agents-policies.sh script, youcan use the script to perform the following actions, based on the argumentsyou provide:

The following examples show some common invocations for the script.For more information, see the comments in the script itself.

To enable the APIs, grant the necessary roles to the default service account,and enable the OS Config metadata for a project, run the script as follows:

bash prepare-for-ops-agents-policies.sh --project=PROJECT_ID

To additionally grant one of the OS Config roles to a user who doesnot have the Owner (roles/owner) role on the project, run the script asfollows:

bash prepare-for-ops-agents-policies.sh --project=PROJECT_ID \  --iam-user=USER_EMAIL \  --iam-policy-access=[admin|editor|viewer]

To additionally grant one of the OS Config roles to a non-defaultservice account, run the script as follows:

bash prepare-for-ops-agents-policies.sh --project=PROJECT_ID \  --iam-service-account=SERVICE_ACCT_EMAIL \  --iam-policy-access=[admin|editor|viewer]

Thediagnose_policies.sh script

Given a project ID, a Compute Engine instance ID, a Compute Engine zone, and the agent policy ID, thediagnose_policies.sh script automatically collectsthe necessary information to help diagnose issues with the policy:

  • The OS Config agent version
  • The underlying OS policy assignment
  • The OS policy assignments that are applicable to thisCompute Engine instance
  • A description of this Compute Engine instance

To invoke the script, run the following command:

bash diagnose_policies.sh --project-id=PROJECT_ID \   --gce-instance-id=INSTANCE_ID \  --policy-id=POLICY_ID \  --zone=ZONE

Pricing

Thegcloud compute instances ops-agents policies commands are implemented by usingOS policy assignmentresources fromVM Manager.Theprepare-for-ops-agents-policies.sh script, described inBefore you begin, setsup VM Manager inlimited-feature mode(OSCONFIG_B),which is sufficient for creating and managing agent policies. There is no costto use VM Manager in limited mode.

If you have configured VM Manager in full-feature mode(OSCONFIG_C), then you might incur costs.

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-12-15 UTC.