SQL Server Maintenance plan that goes to next step when the condition passes
As mentioned in the comments you got to refer Ola Hallengren's  maintenance solution.

However, following conditional script might be helpful for any other purpose that need consider only primary replica:

Declare @is_DB_HADREnabled bit;
Declare @isPrimaryReplica bit;
Declare @Databasename varchar (120) = DB_NAME();


select @is_DB_HADREnabled = IIF(group_database_id IS NULL, 0,1) from sys.databases where [name] = @DatabaseName;

        BEGIN
            IF EXISTS (select db.name
                        from sys.dm_hadr_database_replica_states as hadr
                            join sys.databases as db on hadr.group_database_id = db.group_database_id
                        where is_local = 1 and is_primary_replica = 1 and db.name = @DatabaseName
                        )
                SET @isPrimaryReplica = 1 
            ELSE 
                SET @isPrimaryReplica = 0 
        END


    IF @is_DB_HADREnabled = 0 or @isPrimaryReplica = 1

        BEGIN 
            Print 'This block able to run on only Primary replica when a database part of AG. Also, run for the databases which are not part of AG'
        END 

        ELSE 
        PRINT 'This has to be either Primary replica of DATABASE or DATABASE must not be part of any AG'